blob: 0566543615aec8492b56f7cd416ed0a87540eafa [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080024#include <cstdlib>
Ruben Brunkcc776712015-02-17 20:18:47 -080025#include <cstring>
26#include <ctime>
Austin Borgered99f642023-06-01 16:51:35 -070027#include <iostream>
28#include <sstream>
Ruben Brunkcc776712015-02-17 20:18:47 -080029#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080031#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <pthread.h>
Avichal Rakesh84147132021-11-11 17:47:11 -080033#include <poll.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070034
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080035#include <android/hardware/ICamera.h>
36#include <android/hardware/ICameraClient.h>
37
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -070038#include <aidl/AidlCameraService.h>
Alex Deymo9c2a2c22016-08-25 11:59:14 -070039#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080040#include <android-base/parseint.h>
Biswarup Pal37a75182024-01-16 15:53:35 +000041#include <android_companion_virtualdevice_flags.h>
42#include <android/companion/virtualnative/IVirtualDeviceManagerNative.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080043#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080044#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046#include <binder/MemoryBase.h>
47#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080048#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080049#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080050#include <binderthreadstate/CallerUtils.h>
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -070051#include <com_android_internal_camera_flags.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070052#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070053#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080054#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080055#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070057#include "hidl/HidlCameraService.h"
58#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080059#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070060#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080062#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070063#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070064#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000065#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070066#include <utils/Errors.h>
67#include <utils/Log.h>
68#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070069#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080070#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080071#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080072#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080073#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070074#include <system/camera_metadata.h>
Kunal Malhotrabfc96052023-02-28 23:25:34 +000075#include <binder/IServiceManager.h>
76#include <binder/IActivityManager.h>
Biswarup Pal37a75182024-01-16 15:53:35 +000077#include <camera/CameraUtils.h>
Austin Borgered99f642023-06-01 16:51:35 -070078#include <camera/StringUtils.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080079
Ruben Brunkb2119af2014-05-09 19:57:56 -070080#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070081
82#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070083#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070084#include "api2/CameraDeviceClient.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070085#include "utils/CameraServiceProxyWrapper.h"
Emilian Peev31bd2422024-04-23 22:24:09 +000086#include "utils/CameraTraces.h"
Shuzhen Wang045be6c2023-10-12 10:01:10 -070087#include "utils/SessionConfigurationUtils.h"
Emilian Peev31bd2422024-04-23 22:24:09 +000088#include "utils/TagMonitor.h"
89#include "utils/Utils.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070090
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080091namespace {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080092 const char* kActivityServiceName = "activity";
93 const char* kSensorPrivacyServiceName = "sensor_privacy";
94 const char* kAppopsServiceName = "appops";
Jyoti Bhayanada519ab2023-05-15 15:49:15 -070095 const char* kProcessInfoServiceName = "processinfo";
Biswarup Pal37a75182024-01-16 15:53:35 +000096 const char* kVirtualDeviceBackCameraId = "0";
97 const char* kVirtualDeviceFrontCameraId = "1";
98
99 int32_t getDeviceId(const android::CameraMetadata& cameraInfo) {
100 if (!cameraInfo.exists(ANDROID_INFO_DEVICE_ID)) {
101 return android::kDefaultDeviceId;
102 }
103
104 const auto &deviceIdEntry = cameraInfo.find(ANDROID_INFO_DEVICE_ID);
105 return deviceIdEntry.data.i32[0];
106 }
107} // namespace anonymous
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -0800108
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109namespace android {
110
Austin Borgerea931242021-12-13 23:10:41 +0000111using namespace camera3;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700112using namespace camera3::SessionConfigurationUtils;
113
114using binder::Status;
Biswarup Pal37a75182024-01-16 15:53:35 +0000115using companion::virtualnative::IVirtualDeviceManagerNative;
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700116using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700117using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800118using hardware::ICamera;
119using hardware::ICameraClient;
120using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800121using hardware::camera2::ICameraInjectionCallback;
122using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800123using hardware::camera2::utils::CameraIdAndSessionConfiguration;
124using hardware::camera2::utils::ConcurrentCameraIdCombination;
Biswarup Pal37a75182024-01-16 15:53:35 +0000125
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -0700126namespace flags = com::android::internal::camera::flags;
Biswarup Pal37a75182024-01-16 15:53:35 +0000127namespace vd_flags = android::companion::virtualdevice::flags;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800128
Mathias Agopian65ab4712010-07-14 17:59:35 -0700129// ----------------------------------------------------------------------------
130// Logging support -- this is for debugging only
131// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700132volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700133
Steve Blockb8a80522011-12-20 16:23:08 +0000134#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
135#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700136
137static void setLogLevel(int level) {
138 android_atomic_write(level, &gLogLevel);
139}
140
Henri Chataingbcb99452023-11-01 17:40:30 +0000141int32_t format_as(CameraService::StatusInternal s) {
142 return fmt::underlying(s);
143}
144
Mathias Agopian65ab4712010-07-14 17:59:35 -0700145// ----------------------------------------------------------------------------
146
Austin Borger249e6592024-03-10 22:28:11 -0700147// Permission strings (references to AttributionAndPermissionUtils for brevity)
148static const std::string &sDumpPermission =
149 AttributionAndPermissionUtils::sDumpPermission;
150static const std::string &sManageCameraPermission =
151 AttributionAndPermissionUtils::sManageCameraPermission;
152static const std::string &sCameraSendSystemEventsPermission =
153 AttributionAndPermissionUtils::sCameraSendSystemEventsPermission;
154static const std::string &sCameraInjectExternalCameraPermission =
155 AttributionAndPermissionUtils::sCameraInjectExternalCameraPermission;
156
Kunal Malhotrabfc96052023-02-28 23:25:34 +0000157// Constant integer for FGS Logging, used to denote the API type for logger
158static const int LOG_FGS_CAMERA_API = 1;
Rucha Katakwardf223072021-06-15 10:21:00 -0700159const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800160static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
161static constexpr int32_t kSystemNativeClientState =
162 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Austin Borgered99f642023-06-01 16:51:35 -0700163static const std::string kServiceName("cameraserver");
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700164
Austin Borgered99f642023-06-01 16:51:35 -0700165const std::string CameraService::kOfflineDevice("offline-");
166const std::string CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700167
Biswarup Pal7d072862024-04-17 15:24:47 +0000168constexpr int32_t kInvalidDeviceId = -1;
169
Rucha Katakward9ea6452021-05-06 11:57:16 -0700170// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700171static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700172
Austin Borger74fca042022-05-23 12:41:21 -0700173CameraService::CameraService(
Austin Borger249e6592024-03-10 22:28:11 -0700174 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,
175 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils) :
176 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils == nullptr ?
177 std::make_shared<AttributionAndPermissionUtils>()\
178 : attributionAndPermissionUtils),
Austin Borger74fca042022-05-23 12:41:21 -0700179 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
180 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800181 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800182 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700183 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700184 mSoundRef(0), mInitialized(false),
185 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000186 ALOGI("CameraService started (pid=%d)", getpid());
Austin Borger249e6592024-03-10 22:28:11 -0700187 mAttributionAndPermissionUtils->setCameraService(this);
Ruben Brunkcc776712015-02-17 20:18:47 -0800188 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700189 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
190 if (mMemFd == -1) {
191 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
192 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700193}
194
Charles Chena7b613c2023-01-24 21:57:33 +0000195// Enable processes with isolated AID to request the binder
196void CameraService::instantiate() {
197 CameraService::publish(true);
198}
199
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800200void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700201 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800202 return;
203 }
204
205 ALOGV("appops service registered. setting camera audio restriction");
206 mAppOps.setCameraAudioRestriction(mAudioRestriction);
207}
208
Iliyan Malchev8951a972011-04-14 16:55:59 -0700209void CameraService::onFirstRef()
210{
Ruben Brunkcc776712015-02-17 20:18:47 -0800211 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800212
Iliyan Malchev8951a972011-04-14 16:55:59 -0700213 BnCameraService::onFirstRef();
214
Ruben Brunk99e69712015-05-26 17:25:07 -0700215 // Update battery life tracking if service is restarting
216 BatteryNotifier& notifier(BatteryNotifier::getInstance());
217 notifier.noteResetCamera();
218 notifier.noteResetFlashlight();
219
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800220 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800221
Emilian Peevf53f66e2017-04-11 14:29:43 +0100222 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800223 if (res == OK) {
224 mInitialized = true;
225 }
226
Svet Ganova453d0d2018-01-11 15:37:58 -0800227 mUidPolicy = new UidPolicy(this);
228 mUidPolicy->registerSelf();
Austin Borger249e6592024-03-10 22:28:11 -0700229 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this, mAttributionAndPermissionUtils);
Michael Grooverd1d435a2018-12-18 17:39:42 -0800230 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800231 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800232
233 // appops function setCamerAudioRestriction uses getService which
234 // is blocking till the appops service is ready. To enable early
235 // boot availability for cameraservice, use checkService which is
236 // non blocking and register for notifications
237 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700238 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800239 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700240 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800241 } else {
242 mAppOps.setCameraAudioRestriction(mAudioRestriction);
243 }
244
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700245 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
246 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000247 // Deprecated, so it will fail to register on newer devices
248 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700249 __FUNCTION__);
250 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700251
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700252 if (!AidlCameraService::registerService(this)) {
253 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
254 }
255
Shuzhen Wang24b44152019-09-20 10:38:11 -0700256 // This needs to be last call in this function, so that it's as close to
257 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700258 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700259 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800260}
261
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800262status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800263 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100264
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800265 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000266 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800267 {
268 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800269
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800270 if (nullptr == mCameraProviderManager.get()) {
271 mCameraProviderManager = new CameraProviderManager();
272 res = mCameraProviderManager->initialize(this);
273 if (res != OK) {
274 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
275 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700276 logServiceError("Unable to initialize camera provider manager",
277 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800278 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100279 }
280 }
281
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800282 // Setup vendor tags before we call get_camera_info the first time
283 // because HAL might need to setup static vendor keys in get_camera_info
284 // TODO: maybe put this into CameraProviderManager::initialize()?
285 mCameraProviderManager->setUpVendorTags();
286
287 if (nullptr == mFlashlight.get()) {
288 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700289 }
290
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800291 res = mFlashlight->findFlashUnits();
292 if (res != OK) {
293 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
294 }
295
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000296 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800297 }
298
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800299 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700300 if (getCameraState(cameraId) == nullptr) {
301 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800302 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000303 if (unavailPhysicalIds.count(cameraId) > 0) {
304 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700305 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000306 }
307 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800308 }
309
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700310 // Derive primary rear/front cameras, and filter their charactierstics.
311 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700312 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700313 // Assume internal cameras are advertised from the same
314 // provider. If multiple providers are registered at different time,
315 // and each provider contains multiple internal color cameras, the current
316 // logic may filter the characteristics of more than one front/rear color
317 // cameras.
318 Mutex::Autolock l(mServiceLock);
319 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700320 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700321
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800322 return OK;
323}
324
Austin Borgered99f642023-06-01 16:51:35 -0700325void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700326 SystemCameraKind systemCameraKind) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000327 // Get the device id and app-visible camera id for the given HAL-visible camera id.
328 auto [deviceId, mappedCameraId] =
329 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
330
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800331 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800332 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700333 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
334 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000335 ALOGV("%s: Skipping torch callback for system-only camera device %s",
336 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700337 continue;
338 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000339
Austin Borgere8e2c422022-05-12 13:45:24 -0700340 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Biswarup Pal37a75182024-01-16 15:53:35 +0000341 mappedCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700342 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
343 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800344 }
345}
346
Mathias Agopian65ab4712010-07-14 17:59:35 -0700347CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800348 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800349 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800350 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800351 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700352}
353
Emilian Peevaee727d2017-05-04 16:35:48 +0100354void CameraService::onNewProviderRegistered() {
355 enumerateProviders();
356}
357
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700358void CameraService::filterAPI1SystemCameraLocked(
359 const std::vector<std::string> &normalDeviceIds) {
360 mNormalDeviceIdsWithoutSystemCamera.clear();
Biswarup Pal37a75182024-01-16 15:53:35 +0000361 for (auto &cameraId : normalDeviceIds) {
362 if (vd_flags::camera_device_awareness()) {
363 CameraMetadata cameraInfo;
364 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000365 cameraId, false, &cameraInfo,
366 hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +0000367 int32_t deviceId = kDefaultDeviceId;
368 if (res != OK) {
369 ALOGW("%s: Not able to get camera characteristics for camera id %s",
370 __FUNCTION__, cameraId.c_str());
371 } else {
372 deviceId = getDeviceId(cameraInfo);
373 }
374 // Cameras associated with non-default device id's (i.e., virtual cameras) can never be
375 // system cameras, so skip for non-default device id's.
376 if (deviceId != kDefaultDeviceId) {
377 continue;
378 }
379 }
380
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700381 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Biswarup Pal37a75182024-01-16 15:53:35 +0000382 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
383 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700384 continue;
385 }
386 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700387 // All system camera ids will necessarily come after public camera
388 // device ids as per the HAL interface contract.
389 break;
390 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000391 mNormalDeviceIdsWithoutSystemCamera.push_back(cameraId);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700392 }
393 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
394 mNormalDeviceIdsWithoutSystemCamera.size());
395}
396
Austin Borgered99f642023-06-01 16:51:35 -0700397status_t CameraService::getSystemCameraKind(const std::string& cameraId,
398 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700399 auto state = getCameraState(cameraId);
400 if (state != nullptr) {
401 *kind = state->getSystemCameraKind();
402 return OK;
403 }
404 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700405 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700406}
407
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800408void CameraService::updateCameraNumAndIds() {
409 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700410 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
411 // Excludes hidden secure cameras
412 mNumberOfCameras =
413 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
414 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800415 mNormalDeviceIds =
416 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700417 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800418}
419
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700420void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700421 // To claim to be S Performance primary cameras, the cameras must be
422 // backward compatible. So performance class primary camera Ids must be API1
423 // compatible.
424 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
425 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
426 int facing = -1;
427 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800428 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000429 getDeviceVersion(cameraId,
430 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
431 /*out*/&portraitRotation, /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700432 if (facing == -1) {
433 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
434 return;
435 }
436
437 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
438 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700439 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
440 if (res == OK) {
441 mPerfClassPrimaryCameraIds.insert(cameraId);
442 } else {
443 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
444 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
445 break;
446 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700447
448 if (facing == hardware::CAMERA_FACING_BACK) {
449 firstRearCameraSeen = true;
450 }
451 if (facing == hardware::CAMERA_FACING_FRONT) {
452 firstFrontCameraSeen = true;
453 }
454 }
455
456 if (firstRearCameraSeen && firstFrontCameraSeen) {
457 break;
458 }
459 }
460}
461
Austin Borgered99f642023-06-01 16:51:35 -0700462void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700463 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100464 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
465 if (res != OK) {
466 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
467 return;
468 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000469 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700470 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
471 if (res != OK) {
472 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
473 return;
474 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000475 std::vector<std::string> physicalCameraIds;
476 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700477 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100478 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700479 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100480 }
481
482 {
483 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700484 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000485 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100486 }
487
Austin Borgered99f642023-06-01 16:51:35 -0700488 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100489 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700490 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800491
Austin Borgered99f642023-06-01 16:51:35 -0700492 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100493 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800494
495 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700496 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100497}
498
Austin Borgered99f642023-06-01 16:51:35 -0700499void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800500 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700501 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100502 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700503 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100504 }
505
506 {
507 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700508 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100509 }
510}
511
Austin Borgered99f642023-06-01 16:51:35 -0700512void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800513 CameraDeviceStatus newHalStatus) {
514 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700515 cameraId.c_str(), eToI(newHalStatus));
Igor Murashkincba2c162013-03-20 15:56:31 -0700516
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800517 StatusInternal newStatus = mapToInternal(newHalStatus);
518
Austin Borgered99f642023-06-01 16:51:35 -0700519 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800520
521 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700522 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100523 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700524 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100525
526 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700527 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100528
Austin Borgered99f642023-06-01 16:51:35 -0700529 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700530 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700531 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700532 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700533 return;
534 }
535
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800536 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800537
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800538 if (oldStatus == newStatus) {
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700539 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__,
540 eToI(newStatus));
Igor Murashkincba2c162013-03-20 15:56:31 -0700541 return;
542 }
543
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800544 if (newStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000545 logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
546 oldStatus, newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800547 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
548 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700549 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000550 mVirtualDeviceCameraIdMapper.removeCamera(cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800551
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800552 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700553 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800554 // Don't do this in updateStatus to avoid deadlock over mServiceLock
555 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700556
Ruben Brunkcc776712015-02-17 20:18:47 -0800557 // Remove cached shim parameters
558 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700559
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800560 // Remove online as well as offline client from the list of active clients,
561 // if they are present
Austin Borgered99f642023-06-01 16:51:35 -0700562 clientToDisconnectOnline = removeClientLocked(cameraId);
563 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700564 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800565
Austin Borgered99f642023-06-01 16:51:35 -0700566 disconnectClient(cameraId, clientToDisconnectOnline);
567 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700568
Austin Borgered99f642023-06-01 16:51:35 -0700569 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800570 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800571 if (oldStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000572 logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
573 oldStatus, newStatus));
Ruben Brunka8ca9152015-04-07 14:23:40 -0700574 }
Austin Borgered99f642023-06-01 16:51:35 -0700575 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700576 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800577}
Igor Murashkincba2c162013-03-20 15:56:31 -0700578
Austin Borgered99f642023-06-01 16:51:35 -0700579void CameraService::onDeviceStatusChanged(const std::string& id,
580 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800581 CameraDeviceStatus newHalStatus) {
582 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700583 __FUNCTION__, id.c_str(), physicalId.c_str(), eToI(newHalStatus));
Shuzhen Wang43858162020-01-10 13:42:15 -0800584
585 StatusInternal newStatus = mapToInternal(newHalStatus);
586
587 std::shared_ptr<CameraState> state = getCameraState(id);
588
589 if (state == nullptr) {
590 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700591 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800592 return;
593 }
594
595 StatusInternal logicalCameraStatus = state->getStatus();
596 if (logicalCameraStatus != StatusInternal::PRESENT &&
597 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
598 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700599 __FUNCTION__, physicalId.c_str(), eToI(newHalStatus), eToI(logicalCameraStatus));
Shuzhen Wang43858162020-01-10 13:42:15 -0800600 return;
601 }
602
603 bool updated = false;
604 if (newStatus == StatusInternal::PRESENT) {
605 updated = state->removeUnavailablePhysicalId(physicalId);
606 } else {
607 updated = state->addUnavailablePhysicalId(physicalId);
608 }
609
610 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700611 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800612 if (newStatus == StatusInternal::PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000613 logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800614 } else {
Henri Chataingbcb99452023-11-01 17:40:30 +0000615 logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800616 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700617 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
618 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
619 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700620 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700621 return;
622 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800623 Mutex::Autolock lock(mStatusListenerLock);
624 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700625 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
626 listener->getListenerPid(), listener->getListenerUid())) {
627 ALOGV("Skipping discovery callback for system-only camera device %s",
628 id.c_str());
629 continue;
630 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700631 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Biswarup Pal37a75182024-01-16 15:53:35 +0000632 mapToInterface(newStatus), id, physicalId, kDefaultDeviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700633 listener->handleBinderStatus(ret,
634 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
635 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
636 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800637 }
638 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700639}
640
Austin Borgered99f642023-06-01 16:51:35 -0700641void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800642 if (clientToDisconnect.get() != nullptr) {
643 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700644 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800645 // Notify the client of disconnection
646 clientToDisconnect->notifyError(
647 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
648 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800649 clientToDisconnect->disconnect();
650 }
651}
652
Austin Borgered99f642023-06-01 16:51:35 -0700653void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800654 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700655 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
656 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
657 if (res != OK) {
658 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700659 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700660 return;
661 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800662 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700663 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800664}
665
Austin Borgered99f642023-06-01 16:51:35 -0700666void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700667 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
668 Mutex::Autolock al(mTorchStatusMutex);
669 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
670}
671
Austin Borgered99f642023-06-01 16:51:35 -0700672void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800673 int32_t newStrengthLevel) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000674 // Get the device id and app-visible camera id for the given HAL-visible camera id.
675 auto [deviceId, mappedCameraId] =
676 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
677
Rucha Katakwar38284522021-11-10 11:25:21 -0800678 Mutex::Autolock lock(mStatusListenerLock);
679 for (auto& i : mListenerList) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000680 auto ret = i->getListener()->onTorchStrengthLevelChanged(mappedCameraId,
681 newStrengthLevel, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700682 i->handleBinderStatus(ret,
683 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
684 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800685 }
686}
687
Austin Borgered99f642023-06-01 16:51:35 -0700688void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700689 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800690 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700691 __FUNCTION__, cameraId.c_str(), eToI(newStatus));
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800692
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800693 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800694 status_t res = getTorchStatusLocked(cameraId, &status);
695 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700696 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700697 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800698 return;
699 }
700 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800701 return;
702 }
703
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800704 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800705 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800706 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
707 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800708 return;
709 }
710
Ruben Brunkcc776712015-02-17 20:18:47 -0800711 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700712 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700713 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700714 auto iter = mTorchUidMap.find(cameraId);
715 if (iter != mTorchUidMap.end()) {
716 int oldUid = iter->second.second;
717 int newUid = iter->second.first;
718 BatteryNotifier& notifier(BatteryNotifier::getInstance());
719 if (oldUid != newUid) {
720 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800721 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700722 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700723 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800724 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700725 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700726 }
727 iter->second.second = newUid;
728 } else {
729 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800730 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700731 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700732 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700733 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700734 }
735 }
736 }
737 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700738 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800739}
740
Austin Borger249e6592024-03-10 22:28:11 -0700741bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700742 // Returns false if this is not an automotive device type.
743 if (!isAutomotiveDevice())
744 return false;
745
746 // Returns false if no camera id is provided.
Austin Borger1c1bee02023-06-01 16:51:35 -0700747 if (cam_id.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700748 return false;
749
750 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
751 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
752 // This isn't a known camera ID, so it's not a system camera.
753 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
754 return false;
755 }
756
757 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
758 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
759 return false;
760 }
761
762 CameraMetadata cameraInfo;
763 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000764 cam_id, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700765 if (res != OK){
766 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
767 cam_id.c_str());
768 return false;
769 }
770
771 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
772 if (auto_location.count != 1)
773 return false;
774
775 uint8_t location = auto_location.data.u8[0];
776 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
777 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
778 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
779 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
780 return false;
781 }
782
783 return true;
784}
785
Austin Borger65e64642024-06-11 15:58:23 -0700786Status CameraService::getNumberOfCameras(int32_t type,
787 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +0000788 int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700789 ATRACE_CALL();
Austin Borger65e64642024-06-11 15:58:23 -0700790 if (vd_flags::camera_device_awareness() && (clientAttribution.deviceId != kDefaultDeviceId)
Biswarup Pal37a75182024-01-16 15:53:35 +0000791 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
Austin Borger65e64642024-06-11 15:58:23 -0700792 *numCameras = mVirtualDeviceCameraIdMapper.getNumberOfCameras(clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000793 return Status::ok();
794 }
795
Emilian Peevaee727d2017-05-04 16:35:48 +0100796 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700797 bool hasSystemCameraPermissions =
Austin Borger22c5c852024-03-08 13:31:36 -0800798 hasPermissionsForSystemCamera(std::string(), getCallingPid(),
799 getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700800 switch (type) {
801 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700802 if (hasSystemCameraPermissions) {
803 *numCameras = static_cast<int>(mNormalDeviceIds.size());
804 } else {
805 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
806 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800807 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700808 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700809 if (hasSystemCameraPermissions) {
810 *numCameras = mNumberOfCameras;
811 } else {
812 *numCameras = mNumberOfCamerasWithoutSystemCamera;
813 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800814 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700815 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800816 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700817 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800818 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
819 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700820 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800821 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700822}
823
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700824Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
Austin Borger65e64642024-06-11 15:58:23 -0700825 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700826 /* out */
827 hardware::camera2::impl::CameraMetadataNative* request) {
828 ATRACE_CALL();
829
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700830 if (!mInitialized) {
831 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
832 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
833 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
834 }
835
Austin Borger65e64642024-06-11 15:58:23 -0700836 std::optional<std::string> cameraIdOptional =
837 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000838 if (!cameraIdOptional.has_value()) {
839 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700840 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000841 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
842 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
843 }
844 std::string cameraId = cameraIdOptional.value();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700845
846 binder::Status res;
847 if (request == nullptr) {
848 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
849 "Camera %s: Error creating default request", cameraId.c_str());
850 return res;
851 }
852 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
853 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
854 cameraId, templateId, &tempId);
855 if (!res.isOk()) {
856 ALOGE("%s: Camera %s: failed to map request Template %d",
857 __FUNCTION__, cameraId.c_str(), templateId);
858 return res;
859 }
860
861 if (shouldRejectSystemCameraConnection(cameraId)) {
862 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
863 "request for system only device %s: ", cameraId.c_str());
864 }
865
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700866 CameraMetadata metadata;
867 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
868 if (err == OK) {
869 request->swap(metadata);
870 } else if (err == BAD_VALUE) {
871 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
872 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
873 cameraId.c_str(), templateId, strerror(-err), err);
874 } else {
875 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
876 "Camera %s: Error creating default request for template %d: %s (%d)",
877 cameraId.c_str(), templateId, strerror(-err), err);
878 }
879 return res;
880}
881
882Status CameraService::isSessionConfigurationWithParametersSupported(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700883 const std::string& unresolvedCameraId, int targetSdkVersion,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700884 const SessionConfiguration& sessionConfiguration,
Austin Borger65e64642024-06-11 15:58:23 -0700885 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700886 /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700887 ATRACE_CALL();
888
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700889 if (!mInitialized) {
890 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
891 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
892 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
893 }
894
Austin Borger65e64642024-06-11 15:58:23 -0700895 std::optional<std::string> cameraIdOptional =
896 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000897 if (!cameraIdOptional.has_value()) {
898 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700899 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000900 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
901 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
902 }
903 std::string cameraId = cameraIdOptional.value();
904
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700905 if (supported == nullptr) {
906 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
907 unresolvedCameraId.c_str());
908 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
909 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
910 }
911
912 if (shouldRejectSystemCameraConnection(cameraId)) {
913 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
914 "session configuration with parameters support for system only device %s: ",
915 cameraId.c_str());
916 }
917
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700918 bool overrideForPerfClass = flags::calculate_perf_override_during_session_support() &&
919 SessionConfigurationUtils::targetPerfClassPrimaryCamera(
920 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
921
Shuzhen Wange3e8e732024-05-22 17:48:01 -0700922 auto ret = isSessionConfigurationWithParametersSupportedUnsafe(cameraId,
923 sessionConfiguration, overrideForPerfClass, supported);
924 if (flags::analytics_24q3()) {
925 mCameraServiceProxyWrapper->logFeatureCombinationQuery(cameraId,
926 getCallingUid(), sessionConfiguration, ret);
927 }
928 return ret;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700929}
930
931Status CameraService::isSessionConfigurationWithParametersSupportedUnsafe(
932 const std::string& cameraId, const SessionConfiguration& sessionConfiguration,
933 bool overrideForPerfClass, /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700934 *supported = false;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700935 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(
936 cameraId, sessionConfiguration, overrideForPerfClass,
937 /*checkSessionParams=*/true, supported);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700938 binder::Status res;
939 switch (ret) {
940 case OK:
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700941 // Expected. Do Nothing.
942 return Status::ok();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700943 case INVALID_OPERATION: {
944 std::string msg = fmt::sprintf(
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700945 "Camera %s: Session configuration with parameters supported query not "
946 "supported!",
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700947 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700948 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
949 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
950 *supported = false;
951 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700952 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700953 break;
954 case NAME_NOT_FOUND: {
955 std::string msg = fmt::sprintf("Camera %s: Unknown camera ID.", cameraId.c_str());
956 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
957 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
958 *supported = false;
959 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
960 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700961 break;
962 default: {
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700963 std::string msg = fmt::sprintf(
964 "Unable to retrieve session configuration support for camera "
965 "device %s: Error: %s (%d)",
966 cameraId.c_str(), strerror(-ret), ret);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700967 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700968 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
969 *supported = false;
970 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700971 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700972 break;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700973 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700974}
975
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800976Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000977 int targetSdkVersion, int rotationOverride,
Austin Borger65e64642024-06-11 15:58:23 -0700978 const SessionConfiguration& sessionConfiguration,
979 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +0000980 /*out*/ CameraMetadata* outMetadata) {
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800981 ATRACE_CALL();
982
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800983 if (outMetadata == nullptr) {
984 std::string msg =
985 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
986 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
987 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
988 }
989
Avichal Rakesh4baf7262024-03-20 19:16:04 -0700990 if (!mInitialized) {
991 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
992 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
993 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
994 }
995
Austin Borger65e64642024-06-11 15:58:23 -0700996 std::optional<std::string> cameraIdOptional =
997 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000998 if (!cameraIdOptional.has_value()) {
999 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001000 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001001 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1002 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1003 }
1004 std::string cameraId = cameraIdOptional.value();
1005
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001006 if (shouldRejectSystemCameraConnection(cameraId)) {
1007 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1008 "Unable to retrieve camera"
1009 "characteristics for system only device %s: ",
1010 cameraId.c_str());
1011 }
1012
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001013 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1014 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001015 if (flags::check_session_support_before_session_char()) {
1016 bool sessionConfigSupported;
1017 Status res = isSessionConfigurationWithParametersSupportedUnsafe(
1018 cameraId, sessionConfiguration, overrideForPerfClass, &sessionConfigSupported);
1019 if (!res.isOk()) {
1020 // isSessionConfigurationWithParametersSupportedUnsafe should log what went wrong and
1021 // report the correct Status to send to the client. Simply forward the error to
1022 // the client.
1023 outMetadata->clear();
1024 return res;
1025 }
1026 if (!sessionConfigSupported) {
1027 std::string msg = fmt::sprintf(
1028 "Session configuration not supported for camera device %s.", cameraId.c_str());
1029 outMetadata->clear();
1030 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1031 }
1032 }
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001033
1034 status_t ret = mCameraProviderManager->getSessionCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001035 cameraId, sessionConfiguration, overrideForPerfClass, rotationOverride, outMetadata);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001036
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001037 switch (ret) {
1038 case OK:
1039 // Expected, no handling needed.
1040 break;
1041 case INVALID_OPERATION: {
1042 std::string msg = fmt::sprintf(
1043 "Camera %s: Session characteristics query not supported!",
1044 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001045 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001046 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1047 outMetadata->clear();
1048 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1049 }
1050 break;
1051 case NAME_NOT_FOUND: {
1052 std::string msg = fmt::sprintf(
1053 "Camera %s: Unknown camera ID.",
1054 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001055 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001056 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1057 outMetadata->clear();
1058 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001059 }
1060 break;
1061 default: {
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001062 std::string msg = fmt::sprintf(
1063 "Unable to retrieve session characteristics for camera device %s: "
1064 "Error: %s (%d)",
1065 cameraId.c_str(), strerror(-ret), ret);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001066 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001067 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1068 outMetadata->clear();
1069 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001070 }
1071 }
1072
Shuzhen Wange3e8e732024-05-22 17:48:01 -07001073 Status res = filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
1074 if (flags::analytics_24q3()) {
1075 mCameraServiceProxyWrapper->logSessionCharacteristicsQuery(cameraId,
1076 getCallingUid(), sessionConfiguration, res);
1077 }
1078 return res;
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001079}
1080
1081Status CameraService::filterSensitiveMetadataIfNeeded(
1082 const std::string& cameraId, CameraMetadata* metadata) {
1083 int callingPid = getCallingPid();
1084 int callingUid = getCallingUid();
1085
1086 if (callingPid == getpid()) {
1087 // Caller is cameraserver; no need to remove keys
1088 return Status::ok();
1089 }
1090
1091 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1092 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1093 ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
1094 metadata->clear();
1095 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1096 "Unable to retrieve camera kind for device %s", cameraId.c_str());
1097 }
1098 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
1099 // Attempting to query system only camera without system camera permission would have
1100 // failed the shouldRejectSystemCameraConnection in the caller. So if we get here
1101 // for a system only camera, then the caller has the required permission.
1102 // No need to remove keys
1103 return Status::ok();
1104 }
1105
1106 std::vector<int32_t> tagsRemoved;
Biswarup Pale506e732024-03-27 13:46:20 +00001107 // Get the device id that owns this camera.
1108 auto [cameraOwnerDeviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1109 cameraId);
1110 bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid,
1111 cameraOwnerDeviceId);
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001112 if (hasCameraPermission) {
1113 // Caller has camera permission; no need to remove keys
1114 return Status::ok();
1115 }
1116
1117 status_t ret = metadata->removePermissionEntries(
1118 mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1119 if (ret != OK) {
1120 metadata->clear();
1121 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1122 "Failed to remove camera characteristics needing camera permission "
1123 "for device %s:%s (%d)",
1124 cameraId.c_str(), strerror(-ret), ret);
1125 }
1126
1127 if (!tagsRemoved.empty()) {
1128 ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1129 tagsRemoved.data(), tagsRemoved.size());
1130 if (ret != OK) {
1131 metadata->clear();
1132 return STATUS_ERROR_FMT(
1133 ERROR_INVALID_OPERATION,
1134 "Failed to insert camera keys needing permission for device %s: %s (%d)",
1135 cameraId.c_str(), strerror(-ret), ret);
1136 }
1137 }
1138 return Status::ok();
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001139}
1140
malikakash22af94c2023-12-04 18:13:14 +00001141Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001142 const std::string& cameraId,
1143 const CameraMetadata& sessionParams) {
1144 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001145 const int pid = getCallingPid();
1146 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001147 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1148 __FUNCTION__, pid, uid);
1149 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1150 "Permission Denial: no permission to inject session params");
1151 }
1152
Biswarup Pal37a75182024-01-16 15:53:35 +00001153 // Do not allow session params injection for a virtual camera.
1154 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1155 if (deviceId != kDefaultDeviceId) {
1156 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1157 "Cannot inject session params for a virtual camera");
1158 }
1159
malikakash22af94c2023-12-04 18:13:14 +00001160 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1161 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1162
1163 auto clientDescriptor = mActiveClientManager.get(cameraId);
1164 if (clientDescriptor == nullptr) {
1165 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1166 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1167 "No active client for camera id %s", cameraId.c_str());
1168 }
1169
1170 sp<BasicClient> clientSp = clientDescriptor->getValue();
1171 status_t res = clientSp->injectSessionParams(sessionParams);
1172
1173 if (res != OK) {
1174 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1175 "Error injecting session params into camera \"%s\": %s (%d)",
1176 cameraId.c_str(), strerror(-res), res);
1177 }
1178 return Status::ok();
1179}
1180
Biswarup Pal37a75182024-01-16 15:53:35 +00001181std::optional<std::string> CameraService::resolveCameraId(
1182 const std::string& inputCameraId,
1183 int32_t deviceId,
malikakash98260df2024-05-10 23:33:57 +00001184 int32_t devicePolicy) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001185 if ((deviceId == kDefaultDeviceId)
1186 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1187 auto [storedDeviceId, _] =
1188 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1189 if (storedDeviceId != kDefaultDeviceId) {
1190 // Trying to access a virtual camera from default-policy device context, we should fail.
1191 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1192 inputCameraId.c_str(), deviceId);
1193 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1194 return std::nullopt;
1195 }
malikakash98260df2024-05-10 23:33:57 +00001196 return inputCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001197 }
1198
1199 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1200}
1201
Austin Borger65e64642024-06-11 15:58:23 -07001202Status CameraService::getCameraInfo(int cameraId, int rotationOverride,
1203 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
1204 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001205 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001206 Mutex::Autolock l(mServiceLock);
Austin Borger65e64642024-06-11 15:58:23 -07001207 std::string cameraIdStr =
1208 cameraIdIntToStrLocked(cameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001209 if (cameraIdStr.empty()) {
1210 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001211 cameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001212 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1213 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1214 }
malikakashedb38962023-09-06 00:03:35 +00001215
Austin Borgered99f642023-06-01 16:51:35 -07001216 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001217 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1218 "characteristics for system only device %s: ", cameraIdStr.c_str());
1219 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001220
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001221 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001222 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001223 return STATUS_ERROR(ERROR_DISCONNECTED,
1224 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001225 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001226 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001227 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001228 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1229 if (hasSystemCameraPermissions) {
1230 cameraIdBound = mNumberOfCameras;
1231 }
1232 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001233 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1234 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001235 }
1236
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001237 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001238 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001239 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001240 cameraIdStr, rotationOverride, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001241 if (err != OK) {
1242 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1243 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1244 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001245 logServiceError(std::string("Error retrieving camera info from device ")
1246 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001247 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001248
Ruben Brunkcc776712015-02-17 20:18:47 -08001249 return ret;
1250}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001251
Biswarup Pal37a75182024-01-16 15:53:35 +00001252std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1253 int32_t deviceId, int32_t devicePolicy) {
1254 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1255 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1256 std::optional<std::string> cameraIdOptional =
1257 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1258 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1259 }
1260
1261 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001262 auto callingPid = getCallingPid();
1263 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001264 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1265 callingPid, callingUid, /* checkCameraPermissions= */ false);
1266 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001267 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001268 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001269 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1270 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1271 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001272 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001273 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001274
malikakash98260df2024-05-10 23:33:57 +00001275 return (*cameraIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001276}
1277
Biswarup Pal37a75182024-01-16 15:53:35 +00001278std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1279 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001280 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001281 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001282}
1283
Austin Borgered99f642023-06-01 16:51:35 -07001284Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07001285 int targetSdkVersion, int rotationOverride, const AttributionSourceState& clientAttribution,
1286 int32_t devicePolicy, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001287 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001288
Zhijun He2b59be82013-09-25 10:14:30 -07001289 if (!cameraInfo) {
1290 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001291 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001292 }
1293
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001294 if (!mInitialized) {
1295 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001296 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001297 return STATUS_ERROR(ERROR_DISCONNECTED,
1298 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001299 }
1300
Austin Borger65e64642024-06-11 15:58:23 -07001301 std::optional<std::string> cameraIdOptional =
1302 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001303 if (!cameraIdOptional.has_value()) {
1304 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001305 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001306 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1307 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1308 }
1309 std::string cameraId = cameraIdOptional.value();
1310
Austin Borgered99f642023-06-01 16:51:35 -07001311 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001312 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001313 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001314 }
1315
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001316 bool overrideForPerfClass =
1317 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001318 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001319 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001320 cameraId, overrideForPerfClass, cameraInfo, rotationOverride);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001321 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001322 if (res == NAME_NOT_FOUND) {
1323 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001324 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001325 strerror(-res), res);
1326 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001327 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1328 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001329 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001330 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001331 strerror(-res), res);
1332 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001333 }
Emilian Peeve20c6372018-08-14 18:45:53 +01001334
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001335 return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -07001336}
1337
Austin Borger65e64642024-06-11 15:58:23 -07001338Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId,
1339 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00001340 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001341 ATRACE_CALL();
1342 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001343
Austin Borger65e64642024-06-11 15:58:23 -07001344 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
1345 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001346 if (!cameraIdOptional.has_value()) {
1347 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001348 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001349 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1350 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1351 }
1352 std::string cameraId = cameraIdOptional.value();
1353
Rucha Katakwar38284522021-11-10 11:25:21 -08001354 if (!mInitialized) {
1355 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1356 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1357 }
1358
Biswarup Pal37a75182024-01-16 15:53:35 +00001359 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001360 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1361 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1362 }
1363
Austin Borgered99f642023-06-01 16:51:35 -07001364 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001365 if (res != OK) {
1366 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001367 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001368 strerror(-res), res);
1369 }
1370 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1371 return Status::ok();
1372}
1373
Austin Borgered99f642023-06-01 16:51:35 -07001374std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001375 time_t now = time(nullptr);
1376 char formattedTime[64];
1377 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001378 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001379}
1380
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001381Status CameraService::getCameraVendorTagDescriptor(
1382 /*out*/
1383 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001384 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001385 if (!mInitialized) {
1386 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001387 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001388 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001389 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1390 if (globalDescriptor != nullptr) {
1391 *desc = *(globalDescriptor.get());
1392 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001393 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001394}
1395
Emilian Peev71c73a22017-03-21 16:35:51 +00001396Status CameraService::getCameraVendorTagCache(
1397 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1398 ATRACE_CALL();
1399 if (!mInitialized) {
1400 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1401 return STATUS_ERROR(ERROR_DISCONNECTED,
1402 "Camera subsystem not available");
1403 }
1404 sp<VendorTagDescriptorCache> globalCache =
1405 VendorTagDescriptorCache::getGlobalVendorTagCache();
1406 if (globalCache != nullptr) {
1407 *cache = *(globalCache.get());
1408 }
1409 return Status::ok();
1410}
1411
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001412void CameraService::clearCachedVariables() {
1413 BasicClient::BasicClient::sCameraService = nullptr;
1414}
1415
Austin Borgered99f642023-06-01 16:51:35 -07001416std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001417 int rotationOverride, int* portraitRotation, int* facing,
1418 int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001419 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001420
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001421 int deviceVersion = 0;
1422
Emilian Peevf53f66e2017-04-11 14:29:43 +01001423 status_t res;
1424 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001425 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001426 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001427 if (res != OK || transport == IPCTransport::INVALID) {
1428 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001429 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001430 return std::make_pair(-1, IPCTransport::INVALID) ;
1431 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001432 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001433
Emilian Peevf53f66e2017-04-11 14:29:43 +01001434 hardware::CameraInfo info;
1435 if (facing) {
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001436 res = mCameraProviderManager->getCameraInfo(cameraId, rotationOverride,
Austin Borger18b30a72022-10-27 12:20:29 -07001437 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001438 if (res != OK) {
1439 return std::make_pair(-1, IPCTransport::INVALID);
1440 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001441 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001442 if (orientation) {
1443 *orientation = info.orientation;
1444 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001445 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001446
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001447 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001448}
1449
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001450Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001451 switch(err) {
1452 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001453 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001454 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001455 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1456 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001457 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001458 return STATUS_ERROR(ERROR_DISCONNECTED,
1459 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001460 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001461 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1462 "Camera HAL encountered error %d: %s",
1463 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001464 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001465}
1466
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001467Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001468 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1469 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001470 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001471 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001472 apiLevel effectiveApiLevel, bool overrideForPerfClass, int rotationOverride,
malikakash73125c62023-07-21 22:44:34 +00001473 bool forceSlowJpegMode, const std::string& originalCameraId,
1474 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001475 // For HIDL devices
1476 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1477 // Create CameraClient based on device version reported by the HAL.
1478 int deviceVersion = deviceVersionAndTransport.first;
1479 switch(deviceVersion) {
1480 case CAMERA_DEVICE_API_VERSION_1_0:
1481 ALOGE("Camera using old HAL version: %d", deviceVersion);
1482 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1483 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001484 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001485 break;
1486 case CAMERA_DEVICE_API_VERSION_3_0:
1487 case CAMERA_DEVICE_API_VERSION_3_1:
1488 case CAMERA_DEVICE_API_VERSION_3_2:
1489 case CAMERA_DEVICE_API_VERSION_3_3:
1490 case CAMERA_DEVICE_API_VERSION_3_4:
1491 case CAMERA_DEVICE_API_VERSION_3_5:
1492 case CAMERA_DEVICE_API_VERSION_3_6:
1493 case CAMERA_DEVICE_API_VERSION_3_7:
1494 break;
1495 default:
1496 // Should not be reachable
1497 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1498 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1499 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001500 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001501 }
1502 }
1503 if (effectiveApiLevel == API_1) { // Camera1 API route
1504 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001505 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001506 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001507 api1CameraId, facing, sensorOrientation,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001508 clientPid, clientUid, servicePid, overrideForPerfClass, rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00001509 forceSlowJpegMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001510 ALOGI("%s: Camera1 API (legacy), rotationOverride %d, forceSlowJpegMode %d",
1511 __FUNCTION__, rotationOverride, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001512 } else { // Camera2 API route
1513 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1514 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001515 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001516 cameraService->mCameraServiceProxyWrapper,
1517 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001518 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001519 overrideForPerfClass, rotationOverride, originalCameraId);
1520 ALOGI("%s: Camera2 API, rotationOverride %d", __FUNCTION__, rotationOverride);
Ruben Brunkcc776712015-02-17 20:18:47 -08001521 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001522 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001523}
1524
Austin Borgered99f642023-06-01 16:51:35 -07001525std::string CameraService::toString(std::set<userid_t> intSet) {
1526 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001527 bool first = true;
1528 for (userid_t i : intSet) {
1529 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001530 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001531 first = false;
1532 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001533 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001534 }
1535 }
Yi Kong3ac211f2024-08-12 07:31:44 +08001536 return s.str();
Ruben Brunk6267b532015-04-30 17:44:07 -07001537}
1538
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001539int32_t CameraService::mapToInterface(TorchModeStatus status) {
1540 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1541 switch (status) {
1542 case TorchModeStatus::NOT_AVAILABLE:
1543 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1544 break;
1545 case TorchModeStatus::AVAILABLE_OFF:
1546 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1547 break;
1548 case TorchModeStatus::AVAILABLE_ON:
1549 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1550 break;
1551 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001552 ALOGW("Unknown new flash status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001553 }
1554 return serviceStatus;
1555}
1556
1557CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1558 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1559 switch (status) {
1560 case CameraDeviceStatus::NOT_PRESENT:
1561 serviceStatus = StatusInternal::NOT_PRESENT;
1562 break;
1563 case CameraDeviceStatus::PRESENT:
1564 serviceStatus = StatusInternal::PRESENT;
1565 break;
1566 case CameraDeviceStatus::ENUMERATING:
1567 serviceStatus = StatusInternal::ENUMERATING;
1568 break;
1569 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001570 ALOGW("Unknown new HAL device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001571 }
1572 return serviceStatus;
1573}
1574
1575int32_t CameraService::mapToInterface(StatusInternal status) {
1576 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1577 switch (status) {
1578 case StatusInternal::NOT_PRESENT:
1579 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1580 break;
1581 case StatusInternal::PRESENT:
1582 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1583 break;
1584 case StatusInternal::ENUMERATING:
1585 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1586 break;
1587 case StatusInternal::NOT_AVAILABLE:
1588 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1589 break;
1590 case StatusInternal::UNKNOWN:
1591 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1592 break;
1593 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001594 ALOGW("Unknown new internal device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001595 }
1596 return serviceStatus;
1597}
1598
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001599Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001600 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001601
Austin Borgered99f642023-06-01 16:51:35 -07001602 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001603 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001604 sp<Client> tmp = nullptr;
Austin Borger7d2b9232024-07-22 14:17:14 -07001605
Austin Borgerb01a8702024-07-22 16:20:34 -07001606 int callingPid = getCallingPid();
1607 logConnectionAttempt(callingPid, kServiceName, cameraIdStr, API_1);
Austin Borger7d2b9232024-07-22 14:17:14 -07001608
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001609 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001610 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
Austin Borgerb01a8702024-07-22 16:20:34 -07001611 kServiceName, /*systemNativeClient*/ false, {}, uid, callingPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001612 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001613 /*targetSdkVersion*/ __ANDROID_API_FUTURE__,
1614 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_OVERRIDE_TO_PORTRAIT,
Austin Borger7d2b9232024-07-22 14:17:14 -07001615 /*forceSlowJpegMode*/false, cameraIdStr, /*isNonSystemNdk*/ false, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001616 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001617 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001618 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001619 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001620}
1621
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001622Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001623 /*out*/
1624 CameraParameters* parameters) {
1625
1626 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1627
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001628 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001629
1630 if (parameters == NULL) {
1631 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001632 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001633 }
1634
malikakash98260df2024-05-10 23:33:57 +00001635 std::string cameraIdStr = std::to_string(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001636
1637 // Check if we already have parameters
1638 {
1639 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001640 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001641 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001642 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001643 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001644 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001645 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001646 }
1647 CameraParameters p = cameraState->getShimParams();
1648 if (!p.isEmpty()) {
1649 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001650 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001651 }
1652 }
1653
Austin Borger22c5c852024-03-08 13:31:36 -08001654 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001655 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001656 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001657 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001658 // Error already logged by callee
1659 return ret;
1660 }
1661
1662 // Check for parameters again
1663 {
1664 // Scope for service lock
1665 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001666 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001667 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001668 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001669 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001670 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001671 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001672 CameraParameters p = cameraState->getShimParams();
1673 if (!p.isEmpty()) {
1674 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001675 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001676 }
1677 }
1678
Ruben Brunkcc776712015-02-17 20:18:47 -08001679 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1680 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001681 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001682}
1683
Austin Borgered99f642023-06-01 16:51:35 -07001684Status CameraService::validateConnectLocked(const std::string& cameraId,
Austin Borgerb01a8702024-07-22 16:20:34 -07001685 const std::string& clientName8, int clientUid, int clientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001686
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001687#ifdef __BRILLO__
1688 UNUSED(clientName8);
1689 UNUSED(clientUid);
1690 UNUSED(clientPid);
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001691#else
Austin Borger6e831c42024-07-22 13:07:56 -07001692 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001693 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001694 return allowed;
1695 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001696#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001697
Austin Borger22c5c852024-03-08 13:31:36 -08001698 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001699
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001700 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001701 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1702 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001703 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001704 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001705 }
1706
Ruben Brunkcc776712015-02-17 20:18:47 -08001707 if (getCameraState(cameraId) == nullptr) {
1708 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001709 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001710 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001711 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001712 }
1713
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001714 status_t err = checkIfDeviceIsUsable(cameraId);
1715 if (err != NO_ERROR) {
1716 switch(err) {
1717 case -ENODEV:
1718 case -EBUSY:
1719 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001720 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001721 default:
1722 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001723 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001724 }
1725 }
1726 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001727}
1728
Austin Borgerb01a8702024-07-22 16:20:34 -07001729Status CameraService::errorNotTrusted(int clientPid, int clientUid, const std::string& cameraId,
1730 const std::string& clientName, bool isPid) const {
Austin Borger22c5c852024-03-08 13:31:36 -08001731 int callingPid = getCallingPid();
1732 int callingUid = getCallingUid();
Austin Borgerb01a8702024-07-22 16:20:34 -07001733 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1734 "(don't trust %s %d)", callingPid, callingUid, isPid ? "clientPid" : "clientUid",
1735 isPid ? clientPid : clientUid);
1736 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1737 "Untrusted caller (calling PID %d, UID %d) trying to "
1738 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1739 getCallingPid(), getCallingUid(), cameraId.c_str(),
1740 clientName.c_str(), clientPid, clientUid);
1741}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742
Austin Borgerb01a8702024-07-22 16:20:34 -07001743Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1744 const std::string& clientName, int clientUid, int clientPid) const {
1745 int callingPid = getCallingPid();
1746 int callingUid = getCallingUid();
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001747
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001748 if (shouldRejectSystemCameraConnection(cameraId)) {
1749 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1750 cameraId.c_str());
1751 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001752 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001753 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001754 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1755 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001756 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001757 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001758 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001759 }
1760
Biswarup Pale506e732024-03-27 13:46:20 +00001761 // Get the device id that owns this camera.
1762 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1763
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001764 // If it's not calling from cameraserver, check the permission if the
1765 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1766 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001767 bool checkPermissionForCamera =
Biswarup Pale506e732024-03-27 13:46:20 +00001768 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName, deviceId);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001769 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001770 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001771 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001772 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1773 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001774 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001775 }
1776
Svet Ganova453d0d2018-01-11 15:37:58 -08001777 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001778 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001779 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001780 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1781 clientPid, clientUid);
1782 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001783 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1784 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001785 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001786 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001787 }
1788
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001789 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1790 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1791 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1792 if ((!isAutomotivePrivilegedClient(callingUid) ||
1793 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1794 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001795 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1796 return STATUS_ERROR_FMT(ERROR_DISABLED,
1797 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001798 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001799 }
1800
Austin Borger6e831c42024-07-22 13:07:56 -07001801 userid_t clientUserId = multiuser_get_user_id(clientUid);
1802
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001803 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1804 // connected to camera service directly.
Wu-cheng Lia3355432011-05-20 14:54:25 +08001805
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001806 // For non-system clients : Only allow clients who are being used by the current foreground
1807 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08001808 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001809 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001810 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1811 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001812 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001813 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1814 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001815 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001816 }
1817
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001818 if (flags::camera_hsum_permission()) {
1819 // If the System User tries to access the camera when the device is running in
1820 // headless system user mode, ensure that client has the required permission
1821 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07001822 if (isHeadlessSystemUserMode()
1823 && (clientUserId == USER_SYSTEM)
1824 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Austin Borger6e831c42024-07-22 13:07:56 -07001825 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", callingPid, clientUid);
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001826 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1827 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1828 User without camera headless system user permission",
Austin Borger6e831c42024-07-22 13:07:56 -07001829 clientName.c_str(), callingPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001830 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001831 }
1832
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001833 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001834}
1835
Austin Borgered99f642023-06-01 16:51:35 -07001836status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001837 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001838 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001839 if (cameraState == nullptr) {
1840 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001841 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001842 return -ENODEV;
1843 }
1844
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001845 StatusInternal currentStatus = cameraState->getStatus();
1846 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001847 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001848 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001849 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001850 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001851 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001852 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001853 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001854 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001855
Ruben Brunkcc776712015-02-17 20:18:47 -08001856 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001857}
1858
Ruben Brunkcc776712015-02-17 20:18:47 -08001859void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001860 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001861
Ruben Brunkcc776712015-02-17 20:18:47 -08001862 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001863 auto clientDescriptor =
1864 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001865 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001866 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1867
1868 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001869 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001870
1871 if (evicted.size() > 0) {
1872 // This should never happen - clients should already have been removed in disconnect
1873 for (auto& i : evicted) {
1874 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001875 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001876 }
1877
1878 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1879 __FUNCTION__);
1880 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001881
1882 // And register a death notification for the client callback. Do
1883 // this last to avoid Binder policy where a nested Binder
1884 // transaction might be pre-empted to service the client death
1885 // notification if the client process dies before linkToDeath is
1886 // invoked.
1887 sp<IBinder> remoteCallback = client->getRemote();
1888 if (remoteCallback != nullptr) {
1889 remoteCallback->linkToDeath(this);
1890 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001891}
1892
Austin Borgered99f642023-06-01 16:51:35 -07001893status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1894 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1895 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001896 /*out*/
1897 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001898 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001899 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001900 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001901 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001902 DescriptorPtr clientDescriptor;
1903 {
1904 if (effectiveApiLevel == API_1) {
1905 // If we are using API1, any existing client for this camera ID with the same remote
1906 // should be returned rather than evicted to allow MediaRecorder to work properly.
1907
1908 auto current = mActiveClientManager.get(cameraId);
1909 if (current != nullptr) {
1910 auto clientSp = current->getValue();
1911 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001912 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001913 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001914 " API level, evicting prior client...");
1915 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001916 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001917 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001918 *client = clientSp;
1919 return NO_ERROR;
1920 }
1921 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001922 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001923 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001924
Ruben Brunkcc776712015-02-17 20:18:47 -08001925 // Get state for the given cameraId
1926 auto state = getCameraState(cameraId);
1927 if (state == nullptr) {
1928 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001929 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001930 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001931 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001932 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001933
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001934 sp<IServiceManager> sm = defaultServiceManager();
1935 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08001936 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001937 // If processinfo service is not available and the client is automotive privileged
1938 // client used for safety critical uses cases such as rear-view and surround-view which
1939 // needs to be available before android boot completes, then use the hardcoded values
1940 // for the process state and priority score. As this scenario is before android system
1941 // services are up and client is native client, hence using NATIVE_ADJ as the priority
1942 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
1943 // visible on the top.
1944 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1945 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1946 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
1947 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
1948 } else {
1949 // Get current active client PIDs
1950 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1951 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001952
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001953 std::vector<int> priorityScores(ownerPids.size());
1954 std::vector<int> states(ownerPids.size());
1955
1956 // Get priority scores of all active PIDs
1957 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
1958 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
1959 if (err != OK) {
1960 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
1961 return err;
1962 }
1963
1964 // Update all active clients' priorities
1965 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
1966 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1967 pidToPriorityMap.emplace(ownerPids[i],
1968 resource_policy::ClientPriority(priorityScores[i], states[i],
1969 /* isVendorClient won't get copied over*/ false,
1970 /* oomScoreOffset won't get copied over*/ 0));
1971 }
1972 mActiveClientManager.updatePriorities(pidToPriorityMap);
1973
1974 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1975 int32_t actualState = states[states.size() - 1];
1976
1977 // Make descriptor for incoming client. We store the oomScoreOffset
1978 // since we might need it later on new handleEvictionsLocked and
1979 // ProcessInfoService would not take that into account.
1980 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1981 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1982 state->getConflicting(), actualScore, clientPid, actualState,
1983 oomScoreOffset, systemNativeClient);
1984 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001985
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001986 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1987
Ruben Brunkcc776712015-02-17 20:18:47 -08001988 // Find clients that would be evicted
1989 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1990
1991 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1992 // background, so we cannot do evictions
1993 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1994 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1995 " priority).", clientPid);
1996
1997 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07001998 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08001999 auto incompatibleClients =
2000 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2001
Austin Borgered99f642023-06-01 16:51:35 -07002002 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2003 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2004 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002005 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002006
2007 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002008 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002009 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002010 i->getKey().c_str(),
2011 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002012 i->getOwnerId(), i->getPriority().getScore(),
2013 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002014 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002015 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2016 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002017 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002018 }
2019
2020 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002021 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002022 mEventLog.add(msg);
2023
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002024 auto current = mActiveClientManager.get(cameraId);
2025 if (current != nullptr) {
2026 return -EBUSY; // CAMERA_IN_USE
2027 } else {
2028 return -EUSERS; // MAX_CAMERAS_IN_USE
2029 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002030 }
2031
2032 for (auto& i : evicted) {
2033 sp<BasicClient> clientSp = i->getValue();
2034 if (clientSp.get() == nullptr) {
2035 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2036
2037 // TODO: Remove this
2038 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2039 __FUNCTION__);
2040 mActiveClientManager.remove(i);
2041 continue;
2042 }
2043
2044 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002045 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002046 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002047
Ruben Brunkcc776712015-02-17 20:18:47 -08002048 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002049 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002050 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2051 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002052 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002053 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002054 i->getPriority().getState(), cameraId.c_str(),
2055 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002056 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002057
2058 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002059 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002060 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002061 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002062 }
2063
Ruben Brunkcc776712015-02-17 20:18:47 -08002064 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2065 // other clients from connecting in mServiceLockWrapper if held
2066 mServiceLock.unlock();
2067
2068 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002069 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002070
2071 // Destroy evicted clients
2072 for (auto& i : evictedClients) {
2073 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002074 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002075 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002076
Austin Borger22c5c852024-03-08 13:31:36 -08002077 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002078
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002079 for (const auto& i : evictedClients) {
2080 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002081 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002082 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2083 if (ret == TIMED_OUT) {
2084 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002085 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2086 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002087 return -EBUSY;
2088 }
2089 if (ret != NO_ERROR) {
2090 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002091 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2092 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002093 return ret;
2094 }
2095 }
2096
2097 evictedClients.clear();
2098
Ruben Brunkcc776712015-02-17 20:18:47 -08002099 // Once clients have been disconnected, relock
2100 mServiceLock.lock();
2101
2102 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2103 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2104 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002105 }
2106
Ruben Brunkcc776712015-02-17 20:18:47 -08002107 *partial = clientDescriptor;
2108 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002109}
2110
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002111Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002112 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002113 int api1CameraId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002114 int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002115 int rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00002116 bool forceSlowJpegMode,
Austin Borger65e64642024-06-11 15:58:23 -07002117 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00002118 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002119 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002120 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002121 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002122 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002123
Austin Borger65e64642024-06-11 15:58:23 -07002124 std::string cameraIdStr =
2125 cameraIdIntToStr(api1CameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002126 if (cameraIdStr.empty()) {
2127 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002128 api1CameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002129 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2130 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2131 }
malikakashedb38962023-09-06 00:03:35 +00002132
Austin Borger7d2b9232024-07-22 14:17:14 -07002133 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
2134 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
2135 std::string clientPackageName = resolvePackageName(clientAttribution.uid,
2136 clientPackageNameMaybe);
2137 logConnectionAttempt(clientAttribution.pid, clientPackageName, cameraIdStr, API_1);
2138
Austin Borgerb01a8702024-07-22 16:20:34 -07002139 int clientUid = clientAttribution.uid;
2140 int clientPid = clientAttribution.pid;
2141
2142 // Resolve the client identity. In the near future, we will no longer rely on USE_CALLING_*, and
2143 // need a way to guarantee the caller identity early.
2144
2145 // Check if we can trust clientUid
2146 if (!resolveClientUid(clientUid)) {
2147 return errorNotTrusted(clientPid, clientUid, cameraIdStr, clientPackageName,
2148 /* isPid=*/ false);
2149 }
2150
2151 // Check if we can trust clientUid
2152 if (!resolveClientPid(clientPid)) {
2153 return errorNotTrusted(clientPid, clientUid, cameraIdStr, clientPackageName,
2154 /* isPid= */ true);
2155 }
2156
Ruben Brunkcc776712015-02-17 20:18:47 -08002157 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002158 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
Austin Borger7d2b9232024-07-22 14:17:14 -07002159 clientPackageName, /*systemNativeClient*/ false, {},
Austin Borgerb01a8702024-07-22 16:20:34 -07002160 clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002161 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borger7d2b9232024-07-22 14:17:14 -07002162 rotationOverride, forceSlowJpegMode, cameraIdStr, isNonSystemNdk, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002163
Biswarup Pal37a75182024-01-16 15:53:35 +00002164 if (!ret.isOk()) {
Austin Borgerd1ad6c62024-07-01 11:28:31 -07002165 logRejected(cameraIdStr, getCallingPid(), clientAttribution.packageName.value_or(""),
2166 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002167 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002168 }
2169
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002170 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002171
2172 const sp<IServiceManager> sm(defaultServiceManager());
2173 const auto& mActivityManager = getActivityManager();
2174 if (mActivityManager) {
2175 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002176 getCallingUid(),
2177 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002178 }
2179
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002180 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002181}
2182
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002183bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2184 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002185 // If the client is not a vendor client, don't add listener if
2186 // a) the camera is a publicly hidden secure camera OR
2187 // b) the camera is a system only camera and the client doesn't
2188 // have android.permission.SYSTEM_CAMERA permissions.
2189 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2190 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002191 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002192 return true;
2193 }
2194 return false;
2195}
2196
Austin Borgered99f642023-06-01 16:51:35 -07002197bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002198 // Rules for rejection:
2199 // 1) If cameraserver tries to access this camera device, accept the
2200 // connection.
2201 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002202 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002203 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2204 // and the serving thread is a non hwbinder thread, the client must have
2205 // android.permission.SYSTEM_CAMERA permissions to connect.
2206
Austin Borger22c5c852024-03-08 13:31:36 -08002207 int cPid = getCallingPid();
2208 int cUid = getCallingUid();
2209 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002210 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2211 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002212 // This isn't a known camera ID, so it's not a system camera
2213 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2214 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002215 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002216
2217 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002218 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002219 return false;
2220 }
2221 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002222 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002223 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2224 return true;
2225 }
2226 // (3) Here we only check for permissions if it is a system only camera device. This is since
2227 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2228 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2229 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002230 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002231 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002232 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2233 cameraId.c_str());
2234 return true;
2235 }
2236
2237 return false;
2238}
2239
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002240Status CameraService::connectDevice(
2241 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002242 const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002243 int oomScoreOffset, int targetSdkVersion,
2244 int rotationOverride, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Ruben Brunkcc776712015-02-17 20:18:47 -08002245 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002246 sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002247 ATRACE_CALL();
Emilian Peev31bd2422024-04-23 22:24:09 +00002248 RunThreadWithRealtimePriority priorityBump;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002249 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002250 sp<CameraDeviceClient> client = nullptr;
Austin Borger7d2b9232024-07-22 14:17:14 -07002251 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
Austin Borger22c5c852024-03-08 13:31:36 -08002252 int callingPid = getCallingPid();
2253 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002254 bool systemNativeClient = false;
Austin Borger7d2b9232024-07-22 14:17:14 -07002255 if (callerHasSystemUid() && (clientPackageNameMaybe.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002256 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borger7d2b9232024-07-22 14:17:14 -07002257 clientPackageNameMaybe = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002258 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002259 }
Austin Borger249e6592024-03-10 22:28:11 -07002260
Austin Borger65e64642024-06-11 15:58:23 -07002261 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2262 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002263 if (!cameraIdOptional.has_value()) {
2264 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002265 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002266 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2267 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2268 }
2269 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002270
Austin Borger7d2b9232024-07-22 14:17:14 -07002271 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
2272 std::string clientPackageName = resolvePackageName(clientAttribution.uid,
2273 clientPackageNameMaybe);
2274 logConnectionAttempt(clientAttribution.pid, clientPackageName, cameraId, API_2);
2275
Austin Borgerb01a8702024-07-22 16:20:34 -07002276 userid_t clientUserId = multiuser_get_user_id(clientAttribution.uid);
2277 if (clientAttribution.uid == USE_CALLING_UID) {
2278 clientUserId = multiuser_get_user_id(callingUid);
2279 }
2280
2281 // Resolve the client identity. In the near future, we will no longer rely on USE_CALLING_*, and
2282 // need a way to guarantee the caller identity early.
2283
2284 int clientUid = clientAttribution.uid;
2285 int clientPid = callingPid;
2286 // Check if we can trust clientUid
2287 if (!resolveClientUid(clientUid)) {
2288 return errorNotTrusted(clientPid, clientUid, cameraId, clientPackageName,
2289 /* isPid= */ false);
2290 }
2291
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002292 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002293 std::string msg =
2294 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
Austin Borger7d2b9232024-07-22 14:17:14 -07002295 "camera id %s", clientPackageName.c_str(), callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07002296 cameraId.c_str());
2297 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2298 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002299 }
2300
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002301 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2302 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002303 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2304 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002305 std::string msg = "Camera disabled by device policy";
2306 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2307 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002308 }
2309
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002310 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002311 if (oomScoreOffset > 0
2312 && !hasPermissionsForSystemCamera(cameraId, callingPid,
Austin Borger249e6592024-03-10 22:28:11 -07002313 callingUid)
2314 && !isTrustedCallingUid(callingUid)) {
Austin Borgered99f642023-06-01 16:51:35 -07002315 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002316 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borger7d2b9232024-07-22 14:17:14 -07002317 clientPackageName.c_str(), callingPid, cameraId.c_str());
Austin Borgered99f642023-06-01 16:51:35 -07002318 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2319 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002320 }
2321
Austin Borgered99f642023-06-01 16:51:35 -07002322 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
Austin Borger7d2b9232024-07-22 14:17:14 -07002323 cameraId, /*api1CameraId*/-1, clientPackageName, systemNativeClient,
Austin Borgerb01a8702024-07-22 16:20:34 -07002324 clientAttribution.attributionTag, clientUid, clientPid, API_2,
Austin Borgerd1ad6c62024-07-01 11:28:31 -07002325 /*shimUpdateOnly*/ false, oomScoreOffset, targetSdkVersion, rotationOverride,
Austin Borger7d2b9232024-07-22 14:17:14 -07002326 /*forceSlowJpegMode*/false, unresolvedCameraId, isNonSystemNdk, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002327
Biswarup Pal37a75182024-01-16 15:53:35 +00002328 if (!ret.isOk()) {
Austin Borger7d2b9232024-07-22 14:17:14 -07002329 logRejected(cameraId, callingPid, clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002330 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002331 }
2332
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002333 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002334 Mutex::Autolock lock(mServiceLock);
2335
2336 // Clear the previous cached logs and reposition the
2337 // file offset to beginning of the file to log new data.
2338 // If either truncate or lseek fails, close the previous file and create a new one.
2339 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2340 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2341 // Close the previous memfd.
2342 close(mMemFd);
2343 // If failure to wipe the data, then create a new file and
2344 // assign the new value to mMemFd.
2345 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2346 if (mMemFd == -1) {
2347 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2348 }
2349 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002350 const sp<IServiceManager> sm(defaultServiceManager());
2351 const auto& mActivityManager = getActivityManager();
2352 if (mActivityManager) {
2353 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002354 callingUid,
2355 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002356 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002357 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002358}
2359
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002360bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2361 int callingPid, int callingUid) {
2362 if (!isAutomotiveDevice()) {
2363 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2364 }
2365
2366 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2367 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2368 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2369 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2370 "using camera %s", callingUid, cam_id.c_str());
2371 return false;
2372 }
2373
2374 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2375 return true;
2376 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2377 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002378 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2379 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002380 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2381 return false;
2382 } else {
2383 return true;
2384 }
2385 }
2386 return false;
2387}
2388
Austin Borger7d2b9232024-07-22 14:17:14 -07002389void CameraService::logConnectionAttempt(int clientPid, const std::string& clientPackageName,
2390 const std::string& cameraId, apiLevel effectiveApiLevel) const {
2391 int packagePid = (clientPid == USE_CALLING_PID) ?
2392 getCallingPid() : clientPid;
2393 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
2394 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
2395 static_cast<int>(effectiveApiLevel));
2396}
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002397
Austin Borger7d2b9232024-07-22 14:17:14 -07002398std::string CameraService::resolvePackageName(int clientUid,
2399 const std::string& clientPackageNameMaybe) const {
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002400 if (clientPackageNameMaybe.size() <= 0) {
Austin Borger7d2b9232024-07-22 14:17:14 -07002401 int packageUid = (clientUid == USE_CALLING_UID) ?
2402 getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002403 // NDK calls don't come with package names, but we need one for various cases.
2404 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2405 // do exist. For all authentication cases, all packages under the same UID get the
2406 // same permissions, so picking any associated package name is sufficient. For some
2407 // other cases, this may give inaccurate names for clients in logs.
Austin Borger7d2b9232024-07-22 14:17:14 -07002408 return getPackageNameFromUid(packageUid);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002409 } else {
Austin Borger7d2b9232024-07-22 14:17:14 -07002410 return clientPackageNameMaybe;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002411 }
Austin Borger7d2b9232024-07-22 14:17:14 -07002412}
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002413
Austin Borger7d2b9232024-07-22 14:17:14 -07002414template<class CALLBACK, class CLIENT>
2415Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2416 int api1CameraId, const std::string& clientPackageName, bool systemNativeClient,
2417 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
2418 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
2419 int rotationOverride, bool forceSlowJpegMode,
2420 const std::string& originalCameraId, bool isNonSystemNdk, /*out*/sp<CLIENT>& device) {
2421 binder::Status ret = binder::Status::ok();
2422
2423 int packageUid = (clientUid == USE_CALLING_UID) ?
2424 getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002425 int packagePid = (clientPid == USE_CALLING_PID) ?
Austin Borger7d2b9232024-07-22 14:17:14 -07002426 getCallingPid() : clientPid;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002427
Shuzhen Wang316781a2020-08-18 18:11:01 -07002428 nsecs_t openTimeNs = systemTime();
2429
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002430 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002431 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002432 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002433
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002434 {
2435 // Acquire mServiceLock and prevent other clients from connecting
2436 std::unique_ptr<AutoConditionLock> lock =
2437 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2438
2439 if (lock == nullptr) {
2440 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2441 , clientPid);
2442 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2443 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002444 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002445 }
2446
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002447 // Enforce client permissions and do basic validity checks
Biswarup Pal37a75182024-01-16 15:53:35 +00002448 if (!(ret = validateConnectLocked(cameraId, clientPackageName,
Austin Borger6e831c42024-07-22 13:07:56 -07002449 /*inout*/clientUid, /*inout*/clientPid)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002450 return ret;
2451 }
2452
2453 // Check the shim parameters after acquiring lock, if they have already been updated and
2454 // we were doing a shim update, return immediately
2455 if (shimUpdateOnly) {
2456 auto cameraState = getCameraState(cameraId);
2457 if (cameraState != nullptr) {
2458 if (!cameraState->getShimParams().isEmpty()) return ret;
2459 }
2460 }
2461
2462 status_t err;
2463
2464 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002465 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Austin Borger6e831c42024-07-22 13:07:56 -07002466 if ((err = handleEvictionsLocked(cameraId, clientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002467 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2468 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002469 switch (err) {
2470 case -ENODEV:
2471 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2472 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002473 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002474 case -EBUSY:
2475 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2476 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002477 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002478 case -EUSERS:
2479 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2480 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002481 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002482 default:
2483 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2484 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002485 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002486 }
2487 }
2488
2489 if (clientTmp.get() != nullptr) {
2490 // Handle special case for API1 MediaRecorder where the existing client is returned
2491 device = static_cast<CLIENT*>(clientTmp.get());
2492 return ret;
2493 }
2494
2495 // give flashlight a chance to close devices if necessary.
2496 mFlashlight->prepareDeviceOpen(cameraId);
2497
Austin Borger18b30a72022-10-27 12:20:29 -07002498 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002499 auto deviceVersionAndTransport =
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002500 getDeviceVersion(cameraId, rotationOverride, /*out*/&portraitRotation,
Austin Borger18b30a72022-10-27 12:20:29 -07002501 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002502 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002503 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002504 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002505 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002506 }
2507
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002508 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002509 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002510 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002511
Austin Borger6e831c42024-07-22 13:07:56 -07002512 // Only use passed in clientPid to check permission. Use calling PID as the client PID
2513 // that's connected to camera service directly.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002514 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002515 clientFeatureId, cameraId, api1CameraId, facing,
Austin Borger7d2b9232024-07-22 14:17:14 -07002516 orientation, getCallingPid(), clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002517 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002518 rotationOverride, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002519 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002520 return ret;
2521 }
2522 client = static_cast<CLIENT*>(tmp.get());
2523
2524 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2525 __FUNCTION__);
2526
Austin Borgered99f642023-06-01 16:51:35 -07002527 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002528 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002529 if (err != OK) {
2530 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002531 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002532 mServiceLock.unlock();
2533 client->disconnect();
2534 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002535 switch(err) {
2536 case BAD_VALUE:
2537 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002538 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002539 case -EBUSY:
2540 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002541 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002542 case -EUSERS:
2543 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2544 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002545 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002546 case PERMISSION_DENIED:
2547 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002548 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002549 case -EACCES:
2550 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002551 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002552 case -ENODEV:
2553 default:
2554 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002555 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002556 strerror(-err), err);
2557 }
2558 }
2559
2560 // Update shim paremeters for legacy clients
2561 if (effectiveApiLevel == API_1) {
2562 // Assume we have always received a Client subclass for API1
2563 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2564 String8 rawParams = shimClient->getParameters();
2565 CameraParameters params(rawParams);
2566
2567 auto cameraState = getCameraState(cameraId);
2568 if (cameraState != nullptr) {
2569 cameraState->setShimParams(params);
2570 } else {
2571 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002572 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002573 }
2574 }
2575
Ravneetaeb20dc2022-03-30 05:33:03 +00002576 // Enable/disable camera service watchdog
2577 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2578
Emilian Peev6d45db82024-01-18 20:11:54 +00002579 CameraMetadata chars;
2580 bool rotateAndCropSupported = true;
2581 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002582 &chars, rotationOverride);
Emilian Peev6d45db82024-01-18 20:11:54 +00002583 if (err == OK) {
2584 auto availableRotateCropEntry = chars.find(
2585 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2586 if (availableRotateCropEntry.count <= 1) {
2587 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002588 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002589 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002590 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2591 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002592 }
2593
Emilian Peev6d45db82024-01-18 20:11:54 +00002594 if (rotateAndCropSupported) {
2595 // Set rotate-and-crop override behavior
2596 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2597 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002598 } else if (rotationOverride != hardware::ICameraService::ROTATION_OVERRIDE_NONE &&
2599 portraitRotation != 0) {
Emilian Peev6d45db82024-01-18 20:11:54 +00002600 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2601 switch (portraitRotation) {
2602 case 90:
2603 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2604 break;
2605 case 180:
2606 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2607 break;
2608 case 270:
2609 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2610 break;
2611 default:
2612 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2613 break;
2614 }
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002615 // Here we're communicating to the client the chosen rotate
2616 // and crop mode to send to the HAL
Emilian Peev6d45db82024-01-18 20:11:54 +00002617 client->setRotateAndCropOverride(rotateAndCropMode);
2618 } else {
2619 client->setRotateAndCropOverride(
2620 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2621 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2622 }
2623 }
2624
2625 bool autoframingSupported = true;
2626 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2627 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2628 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2629 autoframingSupported = false;
2630 }
2631
2632 if (autoframingSupported) {
2633 // Set autoframing override behaviour
2634 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2635 client->setAutoframingOverride(mOverrideAutoframingMode);
2636 } else {
2637 client->setAutoframingOverride(
2638 mCameraServiceProxyWrapper->getAutoframingOverride(
2639 clientPackageName));
2640 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002641 }
2642
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002643 bool isCameraPrivacyEnabled;
2644 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002645 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002646 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2647 toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2648 } else {
2649 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002650 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002651 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002652
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002653 if (client->supportsCameraMute()) {
2654 client->setCameraMute(
2655 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2656 } else if (isCameraPrivacyEnabled) {
2657 // no camera mute supported, but privacy is on! => disconnect
2658 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2659 client->getPackageName().c_str(), cameraId.c_str());
2660 // Do not hold mServiceLock while disconnecting clients, but
2661 // retain the condition blocking other clients from connecting
2662 // in mServiceLockWrapper if held.
2663 mServiceLock.unlock();
2664 // Clear caller identity temporarily so client disconnect PID
2665 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002666 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002667 // Note AppOp to trigger the "Unblock" dialog
2668 client->noteAppOp();
2669 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002670 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002671 // Reacquire mServiceLock
2672 mServiceLock.lock();
2673
2674 return STATUS_ERROR_FMT(ERROR_DISABLED,
2675 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002676 }
2677
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002678 if (shimUpdateOnly) {
2679 // If only updating legacy shim parameters, immediately disconnect client
2680 mServiceLock.unlock();
2681 client->disconnect();
2682 mServiceLock.lock();
2683 } else {
2684 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002685 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002686 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002687
2688 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002689 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002690 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002691 } // lock is destroyed, allow further connect calls
2692
2693 // Important: release the mutex here so the client can call back into the service from its
2694 // destructor (can be at the end of the call)
2695 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002696
2697 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002698 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002699 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002700
Cliff Wud3a05312021-04-26 23:07:31 +08002701 {
2702 Mutex::Autolock lock(mInjectionParametersLock);
2703 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2704 mInjectionInitPending = false;
2705 status_t res = NO_ERROR;
2706 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2707 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002708 sp<BasicClient> clientSp = clientDescriptor->getValue();
2709 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2710 if(res != OK) {
2711 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2712 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002713 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002714 }
2715 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002716 if (res != OK) {
2717 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2718 }
2719 } else {
2720 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002721 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002722 res = NO_INIT;
2723 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2724 }
2725 }
2726 }
2727
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002728 return ret;
2729}
2730
Austin Borgered99f642023-06-01 16:51:35 -07002731status_t CameraService::addOfflineClient(const std::string &cameraId,
2732 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002733 if (offlineClient.get() == nullptr) {
2734 return BAD_VALUE;
2735 }
2736
2737 {
2738 // Acquire mServiceLock and prevent other clients from connecting
2739 std::unique_ptr<AutoConditionLock> lock =
2740 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2741
2742 if (lock == nullptr) {
2743 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2744 , __FUNCTION__, offlineClient->getClientPid());
2745 return TIMED_OUT;
2746 }
2747
2748 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2749 if (onlineClientDesc.get() == nullptr) {
2750 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2751 cameraId.c_str());
2752 return BAD_VALUE;
2753 }
2754
2755 // Offline clients do not evict or conflict with other online devices. Resource sharing
2756 // conflicts are handled by the camera provider which will either succeed or fail before
2757 // reaching this method.
2758 const auto& onlinePriority = onlineClientDesc->getPriority();
2759 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2760 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002761 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002762 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002763 // native clients don't have offline processing support.
2764 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002765 if (offlineClientDesc == nullptr) {
2766 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2767 return BAD_VALUE;
2768 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002769
2770 // Allow only one offline device per camera
2771 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2772 if (!incompatibleClients.empty()) {
2773 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2774 return BAD_VALUE;
2775 }
2776
Austin Borgered99f642023-06-01 16:51:35 -07002777 std::string monitorTags = isClientWatched(offlineClient.get())
2778 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002779 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002780 if (err != OK) {
2781 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2782 return err;
2783 }
2784
2785 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2786 if (evicted.size() > 0) {
2787 for (auto& i : evicted) {
2788 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002789 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002790 }
2791
2792 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2793 "properly", __FUNCTION__);
2794
2795 return BAD_VALUE;
2796 }
2797
2798 logConnectedOffline(offlineClientDesc->getKey(),
2799 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002800 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002801
2802 sp<IBinder> remoteCallback = offlineClient->getRemote();
2803 if (remoteCallback != nullptr) {
2804 remoteCallback->linkToDeath(this);
2805 }
2806 } // lock is destroyed, allow further connect calls
2807
2808 return OK;
2809}
2810
Austin Borgered99f642023-06-01 16:51:35 -07002811Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002812 int32_t torchStrength, const sp<IBinder>& clientBinder,
2813 const AttributionSourceState& clientAttribution, int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002814 Mutex::Autolock lock(mServiceLock);
2815
2816 ATRACE_CALL();
2817 if (clientBinder == nullptr) {
2818 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2819 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2820 "Torch client binder in null.");
2821 }
2822
Austin Borger22c5c852024-03-08 13:31:36 -08002823 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002824 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2825 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002826 if (!cameraIdOptional.has_value()) {
2827 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002828 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002829 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2830 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2831 }
2832 std::string cameraId = cameraIdOptional.value();
2833
Austin Borgered99f642023-06-01 16:51:35 -07002834 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002835 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002836 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002837 }
2838
2839 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002840 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002841 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002842 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002843 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002844 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002845 }
2846
2847 StatusInternal cameraStatus = state->getStatus();
2848 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2849 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002850 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002851 (int)cameraStatus);
2852 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002853 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002854 }
2855
2856 {
2857 Mutex::Autolock al(mTorchStatusMutex);
2858 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002859 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002860 if (err != OK) {
2861 if (err == NAME_NOT_FOUND) {
2862 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002863 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002864 }
2865 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002866 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002867 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2868 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002869 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002870 }
2871
2872 if (status == TorchModeStatus::NOT_AVAILABLE) {
2873 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2874 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002875 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002876 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2877 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002878 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002879 } else {
2880 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002881 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002882 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2883 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002884 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002885 }
2886 }
2887 }
2888
2889 {
2890 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002891 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002892 }
2893 // Check if the current torch strength level is same as the new one.
2894 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002895 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002896
Austin Borgered99f642023-06-01 16:51:35 -07002897 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002898
2899 if (err != OK) {
2900 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002901 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002902 switch (err) {
2903 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002904 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2905 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002906 errorCode = ERROR_ILLEGAL_ARGUMENT;
2907 break;
2908 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002909 msg = fmt::sprintf("Camera \"%s\" is in use",
2910 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002911 errorCode = ERROR_CAMERA_IN_USE;
2912 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002913 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002914 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002915 "valid range.", torchStrength);
2916 errorCode = ERROR_ILLEGAL_ARGUMENT;
2917 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002918 default:
Austin Borgered99f642023-06-01 16:51:35 -07002919 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002920 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002921 }
Austin Borgered99f642023-06-01 16:51:35 -07002922 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2923 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002924 }
2925
2926 {
2927 // update the link to client's death
2928 // Store the last client that turns on each camera's torch mode.
2929 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002930 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002931 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002932 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002933 } else {
2934 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2935 mTorchClientMap.replaceValueAt(index, clientBinder);
2936 }
2937 clientBinder->linkToDeath(this);
2938 }
2939
Austin Borger22c5c852024-03-08 13:31:36 -08002940 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002941 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002942 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002943 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002944 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002945 }
2946 return Status::ok();
2947}
2948
malikakash73125c62023-07-21 22:44:34 +00002949Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Austin Borger65e64642024-06-11 15:58:23 -07002950 const sp<IBinder>& clientBinder, const AttributionSourceState& clientAttribution,
2951 int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002952 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002953
2954 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002955 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002956 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002957 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2958 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002959 }
2960
Austin Borger22c5c852024-03-08 13:31:36 -08002961 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002962 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2963 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002964 if (!cameraIdOptional.has_value()) {
2965 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002966 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002967 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2968 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2969 }
2970 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002971
Austin Borgered99f642023-06-01 16:51:35 -07002972 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002973 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07002974 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002975 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002976 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07002977 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08002978 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002979 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002980 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002981 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002982 }
2983
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002984 StatusInternal cameraStatus = state->getStatus();
2985 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002986 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07002987 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
2988 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002989 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002990 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002991 }
2992
2993 {
2994 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002995 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002996 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002997 if (err != OK) {
2998 if (err == NAME_NOT_FOUND) {
2999 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003000 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003001 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003002 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003003 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003004 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07003005 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003006 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003007 }
3008
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003009 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003010 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003011 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003012 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003013 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3014 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003015 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003016 } else {
3017 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003018 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003019 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3020 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003021 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003022 }
3023 }
3024 }
3025
Ruben Brunk99e69712015-05-26 17:25:07 -07003026 {
3027 // Update UID map - this is used in the torch status changed callbacks, so must be done
3028 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003029 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003030 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003031 }
3032
Austin Borgered99f642023-06-01 16:51:35 -07003033 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003034
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003035 if (err != OK) {
3036 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003037 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003038 switch (err) {
3039 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003040 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3041 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003042 errorCode = ERROR_ILLEGAL_ARGUMENT;
3043 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003044 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003045 msg = fmt::sprintf("Camera \"%s\" is in use",
3046 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003047 errorCode = ERROR_CAMERA_IN_USE;
3048 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003049 default:
Austin Borgered99f642023-06-01 16:51:35 -07003050 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003051 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003052 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003053 errorCode = ERROR_INVALID_OPERATION;
3054 }
Austin Borgered99f642023-06-01 16:51:35 -07003055 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3056 logServiceError(msg, errorCode);
3057 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003058 }
3059
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003060 {
3061 // update the link to client's death
3062 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003063 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003064 if (enabled) {
3065 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003066 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003067 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003068 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003069 mTorchClientMap.replaceValueAt(index, clientBinder);
3070 }
3071 clientBinder->linkToDeath(this);
3072 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003073 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003074 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003075 }
3076
Austin Borger22c5c852024-03-08 13:31:36 -08003077 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003078 std::string torchState = enabled ? "on" : "off";
3079 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3080 torchState.c_str(), clientPid);
3081 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003082 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003083}
3084
Austin Borgered99f642023-06-01 16:51:35 -07003085void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3086 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3087 mTorchUidMap[cameraId].first = uid;
3088 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003089 } else {
3090 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003091 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003092 }
3093}
3094
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003095Status CameraService::notifySystemEvent(int32_t eventId,
3096 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003097 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003098 const int selfPid = getpid();
3099
3100 // Permission checks
3101 if (pid != selfPid) {
3102 // Ensure we're being called by system_server, or similar process with
3103 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003104 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003105 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003106 ALOGE("Permission Denial: cannot send updates to camera service about system"
3107 " events from pid=%d, uid=%d", pid, uid);
3108 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003109 "No permission to send updates to camera service about system events"
3110 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003111 }
3112 }
3113
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003114 ATRACE_CALL();
3115
Ruben Brunk36597b22015-03-20 22:15:57 -07003116 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003117 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003118 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003119 // from a system server crash
3120 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003121 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003122 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003123 break;
3124 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003125 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3126 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003127 if (args.size() != 1) {
3128 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3129 "USB Device Event requires 1 argument");
3130 }
3131
Valentin Iftime29e2e152021-08-13 15:17:33 +02003132 // Notify CameraProviderManager for lazy HALs
3133 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3134 std::to_string(args[0]));
3135 break;
3136 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003137 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003138 default: {
3139 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3140 eventId);
3141 break;
3142 }
3143 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003144 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003145}
3146
Emilian Peev53722fa2019-02-22 17:47:20 -08003147void CameraService::notifyMonitoredUids() {
3148 Mutex::Autolock lock(mStatusListenerLock);
3149
3150 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003151 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003152 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3153 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003154 }
3155}
3156
Austin Borgerdddb7552023-03-30 17:53:01 -07003157void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3158 Mutex::Autolock lock(mStatusListenerLock);
3159
3160 for (const auto& it : mListenerList) {
3161 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3162 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3163 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3164 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3165 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3166 }
3167 }
3168}
3169
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003170Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003171 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003172 const int selfPid = getpid();
3173
3174 // Permission checks
3175 if (pid != selfPid) {
3176 // Ensure we're being called by system_server, or similar process with
3177 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003178 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003179 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003180 ALOGE("Permission Denial: cannot send updates to camera service about device"
3181 " state changes from pid=%d, uid=%d", pid, uid);
3182 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3183 "No permission to send updates to camera service about device state"
3184 " changes from pid=%d, uid=%d", pid, uid);
3185 }
3186 }
3187
3188 ATRACE_CALL();
3189
Austin Borger18b30a72022-10-27 12:20:29 -07003190 {
3191 Mutex::Autolock lock(mServiceLock);
3192 mDeviceState = newState;
3193 }
3194
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003195 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003196
3197 return Status::ok();
3198}
3199
Emilian Peev8b64f282021-03-25 16:49:57 -07003200Status CameraService::notifyDisplayConfigurationChange() {
3201 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003202 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003203 const int selfPid = getpid();
3204
3205 // Permission checks
3206 if (callingPid != selfPid) {
3207 // Ensure we're being called by system_server, or similar process with
3208 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003209 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003210 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003211 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3212 " changes from pid=%d, uid=%d", callingPid, uid);
3213 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3214 "No permission to send updates to camera service about orientation"
3215 " changes from pid=%d, uid=%d", callingPid, uid);
3216 }
3217 }
3218
3219 Mutex::Autolock lock(mServiceLock);
3220
3221 // Don't do anything if rotate-and-crop override via cmd is active
3222 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3223
3224 const auto clients = mActiveClientManager.getAll();
3225 for (auto& current : clients) {
3226 if (current != nullptr) {
3227 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003228 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3229 basicClient->setRotateAndCropOverride(
3230 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3231 basicClient->getPackageName(),
3232 basicClient->getCameraFacing(),
3233 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003234 }
3235 }
3236 }
3237
3238 return Status::ok();
3239}
3240
3241Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003242 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3243 ATRACE_CALL();
3244 if (!concurrentCameraIds) {
3245 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3246 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3247 }
3248
3249 if (!mInitialized) {
3250 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003251 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003252 return STATUS_ERROR(ERROR_DISCONNECTED,
3253 "Camera subsystem is not available");
3254 }
3255 // First call into the provider and get the set of concurrent camera
3256 // combinations
3257 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003258 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003259 for (auto &combination : concurrentCameraCombinations) {
Biswarup Pal7d072862024-04-17 15:24:47 +00003260 std::vector<std::pair<std::string, int32_t>> validCombination;
3261 int32_t firstDeviceId = kInvalidDeviceId;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003262 for (auto &cameraId : combination) {
3263 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003264 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003265 if (state == nullptr) {
3266 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3267 continue;
3268 }
3269 StatusInternal status = state->getStatus();
3270 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3271 continue;
3272 }
Austin Borgered99f642023-06-01 16:51:35 -07003273 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003274 continue;
3275 }
Biswarup Pal7d072862024-04-17 15:24:47 +00003276 auto [cameraOwnerDeviceId, mappedCameraId] =
3277 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
3278 if (firstDeviceId == kInvalidDeviceId) {
3279 firstDeviceId = cameraOwnerDeviceId;
3280 } else if (firstDeviceId != cameraOwnerDeviceId) {
3281 // Found an invalid combination which contains cameras with different device id's,
3282 // hence discard it.
3283 validCombination.clear();
3284 break;
3285 }
3286 validCombination.push_back({mappedCameraId, cameraOwnerDeviceId});
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003287 }
3288 if (validCombination.size() != 0) {
3289 concurrentCameraIds->push_back(std::move(validCombination));
3290 }
3291 }
3292 return Status::ok();
3293}
3294
3295Status CameraService::isConcurrentSessionConfigurationSupported(
3296 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Austin Borger65e64642024-06-11 15:58:23 -07003297 int targetSdkVersion, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal7d072862024-04-17 15:24:47 +00003298 /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003299 if (!isSupported) {
3300 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3301 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3302 }
3303
3304 if (!mInitialized) {
3305 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3306 return STATUS_ERROR(ERROR_DISCONNECTED,
3307 "Camera subsystem is not available");
3308 }
3309
Biswarup Pal7d072862024-04-17 15:24:47 +00003310 for (auto cameraIdAndSessionConfiguration : cameraIdsAndSessionConfigurations) {
3311 std::optional<std::string> cameraIdOptional =
Austin Borger65e64642024-06-11 15:58:23 -07003312 resolveCameraId(cameraIdAndSessionConfiguration.mCameraId,
3313 clientAttribution.deviceId, devicePolicy);
Biswarup Pal7d072862024-04-17 15:24:47 +00003314 if (!cameraIdOptional.has_value()) {
3315 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07003316 cameraIdAndSessionConfiguration.mCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal7d072862024-04-17 15:24:47 +00003317 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3318 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3319 }
3320 cameraIdAndSessionConfiguration.mCameraId = cameraIdOptional.value();
3321 }
3322
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003323 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003324 int callingPid = getCallingPid();
3325 int callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003326 bool hasCameraPermission = ((callingPid == getpid()) ||
Biswarup Pal7d072862024-04-17 15:24:47 +00003327 hasPermissionsForCamera(callingPid, callingUid,
3328 devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT
Austin Borger65e64642024-06-11 15:58:23 -07003329 ? kDefaultDeviceId : clientAttribution.deviceId));
Austin Borger249e6592024-03-10 22:28:11 -07003330 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003331 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3332 "android.permission.CAMERA needed to call"
3333 "isConcurrentSessionConfigurationSupported");
3334 }
3335
3336 status_t res =
3337 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003338 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3339 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003340 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003341 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003342 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003343 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3344 "support %s (%d)", strerror(-res), res);
3345 }
3346 return Status::ok();
3347}
3348
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003349Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3350 /*out*/
3351 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003352 return addListenerHelper(listener, cameraStatuses);
3353}
3354
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003355binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3356 std::vector<hardware::CameraStatus>* cameraStatuses) {
3357 return addListenerHelper(listener, cameraStatuses, false, true);
3358}
3359
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003360Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3361 /*out*/
3362 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003363 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003364 ATRACE_CALL();
3365
Igor Murashkinbfc99152013-02-27 12:55:20 -08003366 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003367
Ruben Brunk3450ba72015-06-16 11:00:37 -07003368 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003369 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003370 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003371 }
3372
Austin Borger22c5c852024-03-08 13:31:36 -08003373 auto clientPid = getCallingPid();
3374 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003375 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003376
Igor Murashkinbfc99152013-02-27 12:55:20 -08003377 Mutex::Autolock lock(mServiceLock);
3378
Ruben Brunkcc776712015-02-17 20:18:47 -08003379 {
3380 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003381 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003382 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003383 ALOGW("%s: Tried to add listener %p which was already subscribed",
3384 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003385 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003386 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003387 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003388
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003389 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003390 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3391 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003392 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003393 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003394 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003395 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003396 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3397 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3398 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003399 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003400 // The listener still needs to be added to the list of listeners, regardless of what
3401 // permissions the listener process has / whether it is a vendor listener. Since it might be
3402 // eligible to listen to other camera ids.
3403 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003404 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003405 }
3406
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003407 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003408 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003409 Mutex::Autolock lock(mCameraStatesLock);
3410 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003411 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3412 auto [deviceId, mappedCameraId] =
3413 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3414
3415 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003416 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003417 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3418 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003419 }
3420 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003421 // Remove the camera statuses that should be hidden from the client, we do
3422 // this after collecting the states in order to avoid holding
3423 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3424 // the same time.
3425 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3426 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003427 std::string cameraId = s.cameraId;
3428 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
malikakash98260df2024-05-10 23:33:57 +00003429 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM);
Biswarup Pal37a75182024-01-16 15:53:35 +00003430 if (!cameraIdOptional.has_value()) {
3431 std::string msg =
3432 fmt::sprintf(
3433 "Camera %s: Invalid camera id for device id %d",
3434 s.cameraId.c_str(), s.deviceId);
3435 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3436 return true;
3437 }
3438 cameraId = cameraIdOptional.value();
3439 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3440 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3441 ALOGE("%s: Invalid camera id %s, skipping status update",
3442 __FUNCTION__, s.cameraId.c_str());
3443 return true;
3444 }
3445 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3446 clientUid);
3447 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003448
Biswarup Pal37a75182024-01-16 15:53:35 +00003449 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003450 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003451 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003452 // Add only default device cameras here, as virtual cameras currently don't support torch
3453 // anyway. Note that this is a simplification of the implementation here, and we should
3454 // change this when virtual cameras support torch.
3455 if (s.deviceId == kDefaultDeviceId) {
3456 idsChosenForCallback.insert(s.cameraId);
3457 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003458 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003459
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003460 /*
3461 * Immediately signal current torch status to this listener only
3462 * This may be a subset of all the devices, so don't include it in the response directly
3463 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003464 {
3465 Mutex::Autolock al(mTorchStatusMutex);
3466 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003467 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003468 // The camera id is visible to the client. Fine to send torch
3469 // callback.
3470 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003471 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3472 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003473 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003474 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003475 }
3476
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003477 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003478}
Ruben Brunkcc776712015-02-17 20:18:47 -08003479
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003480Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003481 ATRACE_CALL();
3482
Igor Murashkinbfc99152013-02-27 12:55:20 -08003483 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3484
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003485 if (listener == 0) {
3486 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003487 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003488 }
3489
Igor Murashkinbfc99152013-02-27 12:55:20 -08003490 Mutex::Autolock lock(mServiceLock);
3491
Ruben Brunkcc776712015-02-17 20:18:47 -08003492 {
3493 Mutex::Autolock lock(mStatusListenerLock);
3494 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003495 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003496 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003497 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003498 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003499 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003500 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003501 }
3502 }
3503
3504 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3505 __FUNCTION__, listener.get());
3506
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003507 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003508}
3509
Austin Borgered99f642023-06-01 16:51:35 -07003510Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003511
3512 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003513 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3514
3515 if (parameters == NULL) {
3516 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003517 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003518 }
3519
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003520 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003521
3522 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003523 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003524 // Error logged by caller
3525 return ret;
3526 }
3527
3528 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003529
Austin Borgered99f642023-06-01 16:51:35 -07003530 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003531
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003532 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003533}
3534
malikakash98260df2024-05-10 23:33:57 +00003535Status CameraService::supportsCameraApi(const std::string& cameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003536 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003537 ATRACE_CALL();
3538
Austin Borgered99f642023-06-01 16:51:35 -07003539 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003540
3541 switch (apiVersion) {
3542 case API_VERSION_1:
3543 case API_VERSION_2:
3544 break;
3545 default:
Austin Borgered99f642023-06-01 16:51:35 -07003546 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3547 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3548 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003549 }
3550
Austin Borger18b30a72022-10-27 12:20:29 -07003551 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00003552 auto deviceVersionAndTransport =
3553 getDeviceVersion(cameraId,
3554 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
3555 &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003556 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003557 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3558 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3559 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003560 }
3561 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3562 int deviceVersion = deviceVersionAndTransport.first;
3563 switch (deviceVersion) {
3564 case CAMERA_DEVICE_API_VERSION_1_0:
3565 case CAMERA_DEVICE_API_VERSION_3_0:
3566 case CAMERA_DEVICE_API_VERSION_3_1:
3567 if (apiVersion == API_VERSION_2) {
3568 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003569 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003570 *isSupported = false;
3571 } else { // if (apiVersion == API_VERSION_1) {
3572 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003573 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003574 *isSupported = true;
3575 }
3576 break;
3577 case CAMERA_DEVICE_API_VERSION_3_2:
3578 case CAMERA_DEVICE_API_VERSION_3_3:
3579 case CAMERA_DEVICE_API_VERSION_3_4:
3580 case CAMERA_DEVICE_API_VERSION_3_5:
3581 case CAMERA_DEVICE_API_VERSION_3_6:
3582 case CAMERA_DEVICE_API_VERSION_3_7:
3583 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003584 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003585 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003586 break;
3587 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003588 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3589 deviceVersion, cameraId.c_str());
3590 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3591 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003592 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003593 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003594 } else {
3595 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003596 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003597 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003598}
3599
malikakash98260df2024-05-10 23:33:57 +00003600Status CameraService::isHiddenPhysicalCamera(const std::string& cameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003601 /*out*/ bool *isSupported) {
3602 ATRACE_CALL();
3603
Austin Borgered99f642023-06-01 16:51:35 -07003604 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3605 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003606
3607 return Status::ok();
3608}
3609
Cliff Wud8cae102021-03-11 01:37:42 +08003610Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003611 const std::string& packageName, const std::string& internalCamId,
3612 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003613 const sp<ICameraInjectionCallback>& callback,
3614 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003615 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003616 ATRACE_CALL();
3617
Austin Borgered99f642023-06-01 16:51:35 -07003618 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003619 const int pid = getCallingPid();
3620 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003621 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3622 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003623 "Permission Denial: no permission to inject camera");
3624 }
3625
3626 // Do not allow any camera injection that injects or replaces a virtual camera.
3627 auto [deviceIdForInternalCamera, _] =
3628 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3629 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3630 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3631 "Cannot replace a virtual camera");
3632 }
3633 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3634 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3635 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3636 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3637 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003638 }
3639
3640 ALOGV(
3641 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3642 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003643 __FUNCTION__, packageName.c_str(),
3644 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003645
Cliff Wud3a05312021-04-26 23:07:31 +08003646 {
3647 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003648 mInjectionInternalCamId = internalCamId;
3649 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003650 mInjectionStatusListener->addListener(callback);
3651 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003652 status_t res = NO_ERROR;
3653 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3654 // If the client already exists, we can directly connect to the camera device through the
3655 // client's injectCamera(), otherwise we need to wait until the client is established
3656 // (execute connectHelper()) before injecting the camera to the camera device.
3657 if (clientDescriptor != nullptr) {
3658 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003659 sp<BasicClient> clientSp = clientDescriptor->getValue();
3660 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3661 if(res != OK) {
3662 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3663 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003664 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003665 }
3666 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003667 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003668 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3669 }
3670 } else {
3671 mInjectionInitPending = true;
3672 }
3673 }
Cliff Wud8cae102021-03-11 01:37:42 +08003674
Cliff Wud3a05312021-04-26 23:07:31 +08003675 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003676}
3677
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003678Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003679 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003680 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3681 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3682 return Status::ok();
3683}
3684
Ruben Brunkcc776712015-02-17 20:18:47 -08003685void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003686 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003687 for (auto& i : mActiveClientManager.getAll()) {
3688 auto clientSp = i->getValue();
3689 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003690 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003691 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003692 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003693 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003694 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003695}
3696
Ruben Brunkcc776712015-02-17 20:18:47 -08003697bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003698 bool ret = false;
3699 {
3700 // Acquire mServiceLock and prevent other clients from connecting
3701 std::unique_ptr<AutoConditionLock> lock =
3702 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003703
Ruben Brunkcc776712015-02-17 20:18:47 -08003704 std::vector<sp<BasicClient>> evicted;
3705 for (auto& i : mActiveClientManager.getAll()) {
3706 auto clientSp = i->getValue();
3707 if (clientSp.get() == nullptr) {
3708 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3709 mActiveClientManager.remove(i);
3710 continue;
3711 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003712 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003713 mActiveClientManager.remove(i);
3714 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003715
Ruben Brunkcc776712015-02-17 20:18:47 -08003716 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003717 clientSp->notifyError(
3718 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003719 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003720 }
3721 }
3722
Ruben Brunkcc776712015-02-17 20:18:47 -08003723 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3724 // other clients from connecting in mServiceLockWrapper if held
3725 mServiceLock.unlock();
3726
Ruben Brunk36597b22015-03-20 22:15:57 -07003727 // Do not clear caller identity, remote caller should be client proccess
3728
Ruben Brunkcc776712015-02-17 20:18:47 -08003729 for (auto& i : evicted) {
3730 if (i.get() != nullptr) {
3731 i->disconnect();
3732 ret = true;
3733 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003734 }
3735
Ruben Brunkcc776712015-02-17 20:18:47 -08003736 // Reacquire mServiceLock
3737 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003738
Ruben Brunkcc776712015-02-17 20:18:47 -08003739 } // lock is destroyed, allow further connect calls
3740
3741 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003742}
3743
Ruben Brunkcc776712015-02-17 20:18:47 -08003744std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003745 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003746 std::shared_ptr<CameraState> state;
3747 {
3748 Mutex::Autolock lock(mCameraStatesLock);
3749 auto iter = mCameraStates.find(cameraId);
3750 if (iter != mCameraStates.end()) {
3751 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003752 }
3753 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003754 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003755}
3756
Austin Borgered99f642023-06-01 16:51:35 -07003757sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003758 // Remove from active clients list
3759 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3760 if (clientDescriptorPtr == nullptr) {
3761 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003762 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003763 return sp<BasicClient>{nullptr};
3764 }
3765
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003766 sp<BasicClient> client = clientDescriptorPtr->getValue();
3767 if (client.get() != nullptr) {
3768 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3769 }
3770 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003771}
3772
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003773void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003774 // Acquire mServiceLock and prevent other clients from connecting
3775 std::unique_ptr<AutoConditionLock> lock =
3776 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3777
Ruben Brunk6267b532015-04-30 17:44:07 -07003778 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003779 for (size_t i = 0; i < newUserIds.size(); i++) {
3780 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003781 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003782 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003783 return;
3784 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003785 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003786 }
3787
Ruben Brunka8ca9152015-04-07 14:23:40 -07003788
Ruben Brunk6267b532015-04-30 17:44:07 -07003789 if (newAllowedUsers == mAllowedUsers) {
3790 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3791 return;
3792 }
3793
3794 logUserSwitch(mAllowedUsers, newAllowedUsers);
3795
3796 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003797
3798 // Current user has switched, evict all current clients.
3799 std::vector<sp<BasicClient>> evicted;
3800 for (auto& i : mActiveClientManager.getAll()) {
3801 auto clientSp = i->getValue();
3802
3803 if (clientSp.get() == nullptr) {
3804 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3805 continue;
3806 }
3807
Ruben Brunk6267b532015-04-30 17:44:07 -07003808 // Don't evict clients that are still allowed.
3809 uid_t clientUid = clientSp->getClientUid();
3810 userid_t clientUserId = multiuser_get_user_id(clientUid);
3811 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3812 continue;
3813 }
3814
Ruben Brunk36597b22015-03-20 22:15:57 -07003815 evicted.push_back(clientSp);
3816
Ruben Brunk36597b22015-03-20 22:15:57 -07003817 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003818 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003819
Ruben Brunk36597b22015-03-20 22:15:57 -07003820 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003821 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003822 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003823 " to user switch.", i->getKey().c_str(),
3824 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003825 i->getOwnerId(), i->getPriority().getScore(),
3826 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003827
3828 }
3829
3830 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3831 // blocking other clients from connecting in mServiceLockWrapper if held.
3832 mServiceLock.unlock();
3833
3834 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08003835 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003836
3837 for (auto& i : evicted) {
3838 i->disconnect();
3839 }
3840
Austin Borger22c5c852024-03-08 13:31:36 -08003841 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003842
3843 // Reacquire mServiceLock
3844 mServiceLock.lock();
3845}
Ruben Brunkcc776712015-02-17 20:18:47 -08003846
Austin Borgered99f642023-06-01 16:51:35 -07003847void CameraService::logEvent(const std::string &event) {
3848 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003849 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003850 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003851 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003852 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003853 mEventLog.add(msg);
3854 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3855 // Error event not added to the dumpsys log before
3856 mEventLog.add(msg);
3857 sServiceErrorEventSet.insert(msg);
3858 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003859}
3860
Austin Borgered99f642023-06-01 16:51:35 -07003861void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3862 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003863 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003864 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3865 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003866}
3867
Austin Borgered99f642023-06-01 16:51:35 -07003868void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3869 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003870 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003871 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3872 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003873}
3874
Austin Borgered99f642023-06-01 16:51:35 -07003875void CameraService::logConnected(const std::string &cameraId, int clientPid,
3876 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003877 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003878 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3879 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003880}
3881
Austin Borgered99f642023-06-01 16:51:35 -07003882void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3883 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003884 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003885 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3886 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003887}
3888
Austin Borgered99f642023-06-01 16:51:35 -07003889void CameraService::logRejected(const std::string &cameraId, int clientPid,
3890 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003891 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003892 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3893 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003894}
3895
Austin Borgered99f642023-06-01 16:51:35 -07003896void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3897 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003898 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003899 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3900 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003901}
3902
Ruben Brunk6267b532015-04-30 17:44:07 -07003903void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3904 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003905 std::string newUsers = toString(newUserIds);
3906 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003907 if (oldUsers.size() == 0) {
3908 oldUsers = "<None>";
3909 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003910 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003911 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3912 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003913}
3914
Austin Borgered99f642023-06-01 16:51:35 -07003915void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003916 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003917 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003918}
3919
Austin Borgered99f642023-06-01 16:51:35 -07003920void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003921 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003922 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003923}
3924
Austin Borgered99f642023-06-01 16:51:35 -07003925void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003926 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003927 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003928}
3929
Austin Borgered99f642023-06-01 16:51:35 -07003930void CameraService::logServiceError(const std::string &msg, int errorCode) {
3931 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3932 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003933}
3934
Ruben Brunk36597b22015-03-20 22:15:57 -07003935status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3936 uint32_t flags) {
3937
Mathias Agopian65ab4712010-07-14 17:59:35 -07003938 // Permission checks
3939 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003940 case SHELL_COMMAND_TRANSACTION: {
3941 int in = data.readFileDescriptor();
3942 int out = data.readFileDescriptor();
3943 int err = data.readFileDescriptor();
3944 int argc = data.readInt32();
3945 Vector<String16> args;
3946 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3947 args.add(data.readString16());
3948 }
3949 sp<IBinder> unusedCallback;
3950 sp<IResultReceiver> resultReceiver;
3951 status_t status;
3952 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3953 return status;
3954 }
3955 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3956 return status;
3957 }
3958 status = shellCommand(in, out, err, args);
3959 if (resultReceiver != nullptr) {
3960 resultReceiver->send(status);
3961 }
3962 return NO_ERROR;
3963 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003964 }
3965
3966 return BnCameraService::onTransact(code, data, reply, flags);
3967}
3968
Mathias Agopian65ab4712010-07-14 17:59:35 -07003969// We share the media players for shutter and recording sound for all clients.
3970// A reference count is kept to determine when we will actually release the
3971// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09003972sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3973 sp<MediaPlayer> mp = new MediaPlayer();
3974 status_t error;
3975 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003976 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003977 error = mp->prepare();
3978 }
3979 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003980 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003981 mp->disconnect();
3982 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003983 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003984 }
3985 return mp;
3986}
3987
username5755fea2018-12-27 09:48:08 +08003988void CameraService::increaseSoundRef() {
3989 Mutex::Autolock lock(mSoundLock);
3990 mSoundRef++;
3991}
3992
3993void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003994 ATRACE_CALL();
3995
username5755fea2018-12-27 09:48:08 +08003996 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3997 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3998 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3999 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
4000 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4001 }
4002 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
4003 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4004 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4005 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004006 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08004007 }
4008 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4009 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4010 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4011 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4012 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004013 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004014}
4015
username5755fea2018-12-27 09:48:08 +08004016void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004017 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004018 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004019 if (--mSoundRef) return;
4020
4021 for (int i = 0; i < NUM_SOUNDS; i++) {
4022 if (mSoundPlayer[i] != 0) {
4023 mSoundPlayer[i]->disconnect();
4024 mSoundPlayer[i].clear();
4025 }
4026 }
4027}
4028
4029void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004030 ATRACE_CALL();
4031
Mathias Agopian65ab4712010-07-14 17:59:35 -07004032 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004033 if (kind < 0 || kind >= NUM_SOUNDS) {
4034 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4035 return;
4036 }
4037
Mathias Agopian65ab4712010-07-14 17:59:35 -07004038 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004039 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004040 sp<MediaPlayer> player = mSoundPlayer[kind];
4041 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004042 player->seekTo(0);
4043 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004044 }
4045}
4046
4047// ----------------------------------------------------------------------------
4048
4049CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004050 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004051 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004052 const std::string& clientPackageName, bool systemNativeClient,
4053 const std::optional<std::string>& clientFeatureId,
4054 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004055 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004056 int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004057 int servicePid, int rotationOverride) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004058 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004059 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07004060 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004061 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004062 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004063 clientPid, clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004064 servicePid, rotationOverride),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004065 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004066{
Austin Borger22c5c852024-03-08 13:31:36 -08004067 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004068 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004069
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004070 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004071
username5755fea2018-12-27 09:48:08 +08004072 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004073
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004074 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004075}
4076
Mathias Agopian65ab4712010-07-14 17:59:35 -07004077// tear down the client
4078CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004079 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004080 mDestructionStarted = true;
4081
username5755fea2018-12-27 09:48:08 +08004082 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004083 // unconditionally disconnect. function is idempotent
4084 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004085}
4086
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004087sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4088
Igor Murashkin634a5152013-02-20 17:15:11 -08004089CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004090 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004091 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004092 const std::string& clientPackageName, bool nativeClient,
4093 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004094 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004095 int servicePid, int rotationOverride):
Austin Borger249e6592024-03-10 22:28:11 -07004096 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004097 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004098 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004099 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4100 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004101 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004102 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004103 mDisconnected(false), mUidIsTrusted(false),
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004104 mRotationOverride(rotationOverride),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004105 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004106 mRemoteBinder(remoteCallback),
4107 mOpsActive(false),
4108 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004109{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004110 if (sCameraService == nullptr) {
4111 sCameraService = cameraService;
4112 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004113
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004114 // There are 2 scenarios in which a client won't have AppOps operations
4115 // (both scenarios : native clients)
4116 // 1) It's an system native client*, the package name will be empty
4117 // and it will return from this function in the previous if condition
4118 // (This is the same as the previously existing behavior).
4119 // 2) It is a system native client, but its package name has been
4120 // modified for debugging, however it still must not use AppOps since
4121 // the package name is not a real one.
4122 //
4123 // * system native client - native client with UID < AID_APP_START. It
4124 // doesn't exclude clients not on the system partition.
4125 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004126 mAppOpsManager = std::make_unique<AppOpsManager>();
4127 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004128
Charles Chenf075f082024-03-04 23:32:55 +00004129 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004130}
4131
4132CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004133 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004134 mDestructionStarted = true;
4135}
4136
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004137binder::Status CameraService::BasicClient::disconnect() {
4138 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004139 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004140 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004141 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004142 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004143
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004144 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004145 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004146 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004147 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004148
4149 sp<IBinder> remote = getRemote();
4150 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004151 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004152 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004153
4154 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004155 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004156 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004157 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004158 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004159
Igor Murashkincba2c162013-03-20 15:56:31 -07004160 // client shouldn't be able to call into us anymore
4161 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004162
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004163 const auto& mActivityManager = getActivityManager();
4164 if (mActivityManager) {
4165 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004166 getCallingUid(),
4167 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004168 }
4169
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004170 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004171}
4172
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004173status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4174 // No dumping of clients directly over Binder,
4175 // must go through CameraService::dump
4176 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004177 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004178 return OK;
4179}
4180
Austin Borgered99f642023-06-01 16:51:35 -07004181status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004182 // Can't watch tags directly, must go through CameraService::startWatchingTags
4183 return OK;
4184}
4185
4186status_t CameraService::BasicClient::stopWatchingTags(int) {
4187 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4188 return OK;
4189}
4190
4191status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4192 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4193 return OK;
4194}
4195
Austin Borgered99f642023-06-01 16:51:35 -07004196std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004197 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004198}
4199
Emilian Peev8b64f282021-03-25 16:49:57 -07004200int CameraService::BasicClient::getCameraFacing() const {
4201 return mCameraFacing;
4202}
4203
4204int CameraService::BasicClient::getCameraOrientation() const {
4205 return mOrientation;
4206}
Ruben Brunkcc776712015-02-17 20:18:47 -08004207
4208int CameraService::BasicClient::getClientPid() const {
4209 return mClientPid;
4210}
4211
Ruben Brunk6267b532015-04-30 17:44:07 -07004212uid_t CameraService::BasicClient::getClientUid() const {
4213 return mClientUid;
4214}
4215
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004216bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4217 // Defaults to API2.
4218 return level == API_2;
4219}
4220
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004221status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004222 {
4223 Mutex::Autolock l(mAudioRestrictionLock);
4224 mAudioRestriction = mode;
4225 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004226 sCameraService->updateAudioRestriction();
4227 return OK;
4228}
4229
4230int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004231 return sCameraService->updateAudioRestriction();
4232}
4233
4234int32_t CameraService::BasicClient::getAudioRestriction() const {
4235 Mutex::Autolock l(mAudioRestrictionLock);
4236 return mAudioRestriction;
4237}
4238
4239bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4240 switch (mode) {
4241 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4242 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4243 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4244 return true;
4245 default:
4246 return false;
4247 }
4248}
4249
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004250status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4251 if (mode == AppOpsManager::MODE_ERRORED) {
4252 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004253 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004254 return PERMISSION_DENIED;
4255 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4256 // If the calling Uid is trusted (a native service), the AppOpsManager could
4257 // return MODE_IGNORED. Do not treat such case as error.
4258 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4259 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004260
4261 bool isCameraPrivacyEnabled;
4262 if (flags::camera_privacy_allowlist()) {
4263 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4264 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4265 } else {
4266 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004267 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004268 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004269 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4270 // We prefer to successfully open the camera and perform camera muting
4271 // or blocking in connectHelper as handleAppOpMode can be called before the
4272 // connection has been fully established and at that time camera muting
4273 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004274 if (!isUidActive || !isCameraPrivacyEnabled) {
Austin Borgerfd05d982024-04-22 15:54:50 -07004275 ALOGI("Camera %s: Access for \"%s\" has been restricted."
4276 "uid active: %s, privacy enabled: %s", mCameraIdStr.c_str(),
4277 mClientPackageName.c_str(), isUidActive ? "true" : "false",
4278 isCameraPrivacyEnabled ? "true" : "false");
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004279 // Return the same error as for device policy manager rejection
4280 return -EACCES;
4281 }
4282 }
4283 return OK;
4284}
4285
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004286status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004287 ATRACE_CALL();
4288
Igor Murashkine6800ce2013-03-04 17:25:57 -08004289 {
4290 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004291 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004292 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004293 if (mAppOpsManager != nullptr) {
4294 // Notify app ops that the camera is not available
4295 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004296
Austin Borger5755d9b2024-09-09 11:15:44 -07004297 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4298 toString16(mClientPackageName),
4299 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004300
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004301 // Just check for camera acccess here on open - delay startOp until
4302 // camera frames start streaming in startCameraStreamingOps
4303 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004304 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004305 status_t res = handleAppOpMode(mode);
4306 if (res != OK) {
4307 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004308 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004309 }
4310
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004311 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004312
4313 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004314 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004315
Austin Borgerdddb7552023-03-30 17:53:01 -07004316 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004317
Shuzhen Wang695044d2020-03-06 09:02:23 -08004318 // Notify listeners of camera open/close status
4319 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4320
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004321 return OK;
4322}
4323
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004324status_t CameraService::BasicClient::startCameraStreamingOps() {
4325 ATRACE_CALL();
4326
4327 if (!mOpsActive) {
4328 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4329 return INVALID_OPERATION;
4330 }
4331 if (mOpsStreaming) {
4332 ALOGV("%s: Streaming already active!", __FUNCTION__);
4333 return OK;
4334 }
4335
4336 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004337 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004338
4339 if (mAppOpsManager != nullptr) {
4340 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004341 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4342 toString16(mClientFeatureId),
4343 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004344 status_t res = handleAppOpMode(mode);
4345 if (res != OK) {
4346 return res;
4347 }
4348 }
4349
4350 mOpsStreaming = true;
4351
4352 return OK;
4353}
4354
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004355status_t CameraService::BasicClient::noteAppOp() {
4356 ATRACE_CALL();
4357
4358 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004359 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004360
4361 // noteAppOp is only used for when camera mute is not supported, in order
4362 // to trigger the sensor privacy "Unblock" dialog
4363 if (mAppOpsManager != nullptr) {
4364 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004365 toString16(mClientPackageName), toString16(mClientFeatureId),
4366 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004367 status_t res = handleAppOpMode(mode);
4368 if (res != OK) {
4369 return res;
4370 }
4371 }
4372
4373 return OK;
4374}
4375
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004376status_t CameraService::BasicClient::finishCameraStreamingOps() {
4377 ATRACE_CALL();
4378
4379 if (!mOpsActive) {
4380 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4381 return INVALID_OPERATION;
4382 }
4383 if (!mOpsStreaming) {
4384 ALOGV("%s: Streaming not active!", __FUNCTION__);
4385 return OK;
4386 }
4387
4388 if (mAppOpsManager != nullptr) {
4389 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004390 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004391 mOpsStreaming = false;
4392 }
4393
4394 return OK;
4395}
4396
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004397status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004398 ATRACE_CALL();
4399
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004400 if (mOpsStreaming) {
4401 // Make sure we've notified everyone about camera stopping
4402 finishCameraStreamingOps();
4403 }
4404
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004405 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004406 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004407 mOpsActive = false;
4408
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004409 // This function is called when a client disconnects. This should
4410 // release the camera, but actually only if it was in a proper
4411 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004412 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004413 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004414
Ruben Brunkcc776712015-02-17 20:18:47 -08004415 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004416 sCameraService->updateStatus(StatusInternal::PRESENT,
4417 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004418 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004419 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004420 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4421 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004422 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004423 mOpsCallback.clear();
4424
Austin Borgerdddb7552023-03-30 17:53:01 -07004425 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004426
Shuzhen Wang695044d2020-03-06 09:02:23 -08004427 // Notify listeners of camera open/close status
4428 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4429
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004430 return OK;
4431}
4432
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004433void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004434 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004435 if (mAppOpsManager == nullptr) {
4436 return;
4437 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004438 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004439 if (op != AppOpsManager::OP_CAMERA) {
4440 ALOGW("Unexpected app ops notification received: %d", op);
4441 return;
4442 }
4443
4444 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004445 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004446 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004447 ALOGV("checkOp returns: %d, %s ", res,
4448 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4449 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4450 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4451 "UNKNOWN");
4452
Shuzhen Wang64900852021-02-05 09:03:29 -08004453 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004454 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4455 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004456 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004457 } else if (res == AppOpsManager::MODE_IGNORED) {
4458 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004459
Austin Borgerca1e0062023-06-28 11:32:55 -07004460 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4461 // If not visible, but still active, then we want to block instead of muting the camera.
4462 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4463 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4464
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004465 bool isCameraPrivacyEnabled;
4466 if (flags::camera_privacy_allowlist()) {
4467 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4468 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4469 } else {
4470 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004471 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004472 }
4473
4474 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004475 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4476 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4477 isCameraPrivacyEnabled);
4478 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4479 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4480 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004481 if (!mUidIsTrusted) {
Austin Borger5755d9b2024-09-09 11:15:44 -07004482 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4483 setCameraMute(true);
Austin Borgerca1e0062023-06-28 11:32:55 -07004484 } else {
Austin Borger5755d9b2024-09-09 11:15:44 -07004485 block();
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004486 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004487 }
Evan Severson09ab4002021-02-10 14:15:19 -08004488 } else if (res == AppOpsManager::MODE_ALLOWED) {
4489 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004490 }
4491}
4492
Svet Ganova453d0d2018-01-11 15:37:58 -08004493void CameraService::BasicClient::block() {
4494 ATRACE_CALL();
4495
4496 // Reset the client PID to allow server-initiated disconnect,
4497 // and to prevent further calls by client.
Austin Borger22c5c852024-03-08 13:31:36 -08004498 mClientPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004499 CaptureResultExtras resultExtras; // a dummy result (invalid)
4500 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4501 disconnect();
4502}
4503
Mathias Agopian65ab4712010-07-14 17:59:35 -07004504// ----------------------------------------------------------------------------
4505
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004506void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004507 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004508 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004509 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4510 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4511 api1ErrorCode = CAMERA_ERROR_DISABLED;
4512 }
4513 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004514 } else {
4515 ALOGE("mRemoteCallback is NULL!!");
4516 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004517}
4518
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004519// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004520binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004521 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004522 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004523}
4524
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004525bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4526 return level == API_1;
4527}
4528
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004529CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4530 mClient(client) {
4531}
4532
4533void CameraService::Client::OpsCallback::opChanged(int32_t op,
4534 const String16& packageName) {
4535 sp<BasicClient> client = mClient.promote();
4536 if (client != NULL) {
4537 client->opChanged(op, packageName);
4538 }
4539}
4540
Mathias Agopian65ab4712010-07-14 17:59:35 -07004541// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004542// UidPolicy
4543// ----------------------------------------------------------------------------
4544
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004545void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004546 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004547 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004548
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004549 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004550 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004551 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004552 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004553 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4554 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004555 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004556 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004557 if (res == OK) {
4558 mRegistered = true;
4559 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004560 } else {
4561 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004562 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004563}
4564
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004565void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004566 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004567 return;
4568 }
4569
4570 registerWithActivityManager();
4571}
4572
4573void CameraService::UidPolicy::registerSelf() {
4574 // Use check service to see if the activity service is available
4575 // If not available then register for notifications, instead of blocking
4576 // till the service is ready
4577 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004578 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004579 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004580 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004581 } else {
4582 registerWithActivityManager();
4583 }
4584}
4585
Svet Ganova453d0d2018-01-11 15:37:58 -08004586void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004587 Mutex::Autolock _l(mUidLock);
4588
Steven Moreland2f348142019-07-02 15:59:07 -07004589 mAm.unregisterUidObserver(this);
4590 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004591 mRegistered = false;
4592 mActiveUids.clear();
4593 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004594}
4595
4596void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4597 onUidIdle(uid, disabled);
4598}
4599
4600void CameraService::UidPolicy::onUidActive(uid_t uid) {
4601 Mutex::Autolock _l(mUidLock);
4602 mActiveUids.insert(uid);
4603}
4604
4605void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4606 bool deleted = false;
4607 {
4608 Mutex::Autolock _l(mUidLock);
4609 if (mActiveUids.erase(uid) > 0) {
4610 deleted = true;
4611 }
4612 }
4613 if (deleted) {
4614 sp<CameraService> service = mService.promote();
4615 if (service != nullptr) {
4616 service->blockClientsForUid(uid);
4617 }
4618 }
4619}
4620
Emilian Peev53722fa2019-02-22 17:47:20 -08004621void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004622 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004623 bool procStateChange = false;
4624 {
4625 Mutex::Autolock _l(mUidLock);
4626 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4627 mMonitoredUids[uid].procState != procState) {
4628 mMonitoredUids[uid].procState = procState;
4629 procStateChange = true;
4630 }
4631 }
4632
4633 if (procStateChange) {
4634 sp<CameraService> service = mService.promote();
4635 if (service != nullptr) {
4636 service->notifyMonitoredUids();
4637 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004638 }
4639}
4640
Austin Borgerdddb7552023-03-30 17:53:01 -07004641/**
4642 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4643 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4644 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4645 * monitoredUids. If it is revised above some other monitoredUid, signal
4646 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4647 * foreground apps in split screen - state changes will capture all other cases.
4648 */
4649void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4650 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004651 {
4652 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004653 auto it = mMonitoredUids.find(uid);
4654
4655 if (it != mMonitoredUids.end()) {
4656 if (it->second.hasCamera) {
4657 for (auto &monitoredUid : mMonitoredUids) {
4658 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004659 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004660 notifyUidSet.emplace(monitoredUid.first);
4661 }
4662 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004663 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004664 notifyUidSet.emplace(uid);
4665 } else {
4666 for (auto &monitoredUid : mMonitoredUids) {
4667 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004668 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004669 notifyUidSet.emplace(uid);
4670 }
4671 }
4672 }
4673 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004674 }
4675 }
4676
Austin Borgerdddb7552023-03-30 17:53:01 -07004677 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004678 sp<CameraService> service = mService.promote();
4679 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004680 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004681 }
4682 }
4683}
4684
Austin Borgerdddb7552023-03-30 17:53:01 -07004685/**
4686 * Register a uid for monitoring, and note whether it owns a camera.
4687 */
4688void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004689 Mutex::Autolock _l(mUidLock);
4690 auto it = mMonitoredUids.find(uid);
4691 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004692 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004693 } else {
Austin Borger65577682022-02-17 00:25:43 +00004694 MonitoredUid monitoredUid;
4695 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004696 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004697 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004698 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004699 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004700 if (res != OK) {
4701 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4702 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004703 }
4704
4705 if (openCamera) {
4706 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004707 }
4708}
4709
Austin Borgerdddb7552023-03-30 17:53:01 -07004710/**
4711 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4712 */
4713void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004714 Mutex::Autolock _l(mUidLock);
4715 auto it = mMonitoredUids.find(uid);
4716 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004717 it->second.refCount--;
4718 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004719 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004720 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004721 if (res != OK) {
4722 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4723 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004724 } else if (closeCamera) {
4725 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004726 }
4727 } else {
4728 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4729 }
4730}
4731
Austin Borgered99f642023-06-01 16:51:35 -07004732bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004733 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004734 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004735}
4736
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004737static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4738static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004739
Austin Borgered99f642023-06-01 16:51:35 -07004740bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004741 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004742 // If activity manager is unreachable, assume everything is active
4743 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004744 return true;
4745 }
4746 auto it = mOverrideUids.find(uid);
4747 if (it != mOverrideUids.end()) {
4748 return it->second;
4749 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004750 bool active = mActiveUids.find(uid) != mActiveUids.end();
4751 if (!active) {
4752 // We want active UIDs to always access camera with their first attempt since
4753 // there is no guarantee the app is robustly written and would retry getting
4754 // the camera on failure. The inverse case is not a problem as we would take
4755 // camera away soon once we get the callback that the uid is no longer active.
4756 ActivityManager am;
4757 // Okay to access with a lock held as UID changes are dispatched without
4758 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004759 int64_t startTimeMillis = 0;
4760 do {
4761 // TODO: Fix this b/109950150!
4762 // Okay this is a hack. There is a race between the UID turning active and
4763 // activity being resumed. The proper fix is very risky, so we temporary add
4764 // some polling which should happen pretty rarely anyway as the race is hard
4765 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004766 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004767 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004768 if (active) {
4769 break;
4770 }
4771 if (startTimeMillis <= 0) {
4772 startTimeMillis = uptimeMillis();
4773 }
4774 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004775 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004776 if (remainingTimeMillis <= 0) {
4777 break;
4778 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004779 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4780
4781 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004782 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004783 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004784 } while (true);
4785
Svet Ganov7b4ab782018-03-25 12:48:10 -07004786 if (active) {
4787 // Now that we found out the UID is actually active, cache that
4788 mActiveUids.insert(uid);
4789 }
4790 }
4791 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004792}
4793
Varun Shahb42f1eb2019-04-16 14:45:13 -07004794int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4795 Mutex::Autolock _l(mUidLock);
4796 return getProcStateLocked(uid);
4797}
4798
4799int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4800 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4801 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004802 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004803 }
4804 return procState;
4805}
4806
Austin Borgered99f642023-06-01 16:51:35 -07004807void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4808 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004809 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004810}
4811
Austin Borgered99f642023-06-01 16:51:35 -07004812void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004813 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004814}
4815
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004816void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4817 Mutex::Autolock _l(mUidLock);
4818 ALOGV("UidPolicy: ActivityManager has died");
4819 mRegistered = false;
4820 mActiveUids.clear();
4821}
4822
Austin Borgered99f642023-06-01 16:51:35 -07004823void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004824 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004825 bool wasActive = false;
4826 bool isActive = false;
4827 {
4828 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004829 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004830 mOverrideUids.erase(uid);
4831 if (insert) {
4832 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4833 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004834 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004835 }
4836 if (wasActive != isActive && !isActive) {
4837 sp<CameraService> service = mService.promote();
4838 if (service != nullptr) {
4839 service->blockClientsForUid(uid);
4840 }
4841 }
4842}
4843
4844// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004845// SensorPrivacyPolicy
4846// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004847
4848void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4849{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004850 Mutex::Autolock _l(mSensorPrivacyLock);
4851 if (mRegistered) {
4852 return;
4853 }
Evan Severson09ab4002021-02-10 14:15:19 -08004854 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004855 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004856 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004857 mSpm.addToggleSensorPrivacyListener(this);
4858 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004859 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004860 if (flags::camera_privacy_allowlist()) {
4861 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
4862 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
4863 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4864 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004865 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004866 if (res == OK) {
4867 mRegistered = true;
4868 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4869 }
4870}
4871
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004872void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4873 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004874 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004875 return;
4876 }
4877
4878 registerWithSensorPrivacyManager();
4879}
4880
4881void CameraService::SensorPrivacyPolicy::registerSelf() {
4882 // Use checkservice to see if the sensor_privacy service is available
4883 // If service is not available then register for notification
4884 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004885 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004886 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004887 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004888 } else {
4889 registerWithSensorPrivacyManager();
4890 }
4891}
4892
Michael Grooverd1d435a2018-12-18 17:39:42 -08004893void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4894 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004895 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004896 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004897 mSpm.removeToggleSensorPrivacyListener(this);
4898 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004899 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004900 mRegistered = false;
4901 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4902}
4903
4904bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004905 if (!mRegistered) {
4906 registerWithSensorPrivacyManager();
4907 }
4908
Michael Grooverd1d435a2018-12-18 17:39:42 -08004909 Mutex::Autolock _l(mSensorPrivacyLock);
4910 return mSensorPrivacyEnabled;
4911}
4912
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004913int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
4914 if (!mRegistered) {
4915 registerWithSensorPrivacyManager();
4916 }
4917
4918 Mutex::Autolock _l(mSensorPrivacyLock);
4919 return mCameraPrivacyState;
4920}
4921
Evan Seversond0b69922022-01-27 10:47:34 -08004922bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004923 if (!hasCameraPrivacyFeature()) {
4924 return false;
4925 }
Evan Seversond0b69922022-01-27 10:47:34 -08004926 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004927}
4928
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004929bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
4930 if (!hasCameraPrivacyFeature()) {
Jyoti Bhayana5882b032024-04-26 11:18:58 -07004931 return false;
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004932 }
4933 return mSpm.isCameraPrivacyEnabled(packageName);
4934}
4935
Evan Seversond0b69922022-01-27 10:47:34 -08004936binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004937 int toggleType, int sensor, bool enabled) {
4938 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
4939 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
4940 {
4941 Mutex::Autolock _l(mSensorPrivacyLock);
4942 mSensorPrivacyEnabled = enabled;
4943 }
4944 // if sensor privacy is enabled then block all clients from accessing the camera
4945 if (enabled) {
4946 sp<CameraService> service = mService.promote();
4947 if (service != nullptr) {
4948 service->blockAllClients();
4949 }
4950 }
4951 }
4952 return binder::Status::ok();
4953}
4954
4955binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
4956 int, int sensor, int state) {
4957 if (!flags::camera_privacy_allowlist()
4958 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
4959 return binder::Status::ok();
4960 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08004961 {
4962 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004963 mCameraPrivacyState = state;
4964 }
4965 sp<CameraService> service = mService.promote();
4966 if (!service) {
4967 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004968 }
4969 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004970 if (state == SensorPrivacyManager::ENABLED) {
4971 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08004972 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004973 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004974 }
4975 return binder::Status::ok();
4976}
4977
4978void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4979 Mutex::Autolock _l(mSensorPrivacyLock);
4980 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
4981 mRegistered = false;
4982}
4983
Evan Severson09ab4002021-02-10 14:15:19 -08004984bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08004985 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
4986 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4987 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
4988 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4989 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08004990}
4991
Michael Grooverd1d435a2018-12-18 17:39:42 -08004992// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004993// CameraState
4994// ----------------------------------------------------------------------------
4995
Austin Borgered99f642023-06-01 16:51:35 -07004996CameraService::CameraState::CameraState(const std::string& id, int cost,
4997 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004998 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004999 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005000 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005001
5002CameraService::CameraState::~CameraState() {}
5003
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005004CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005005 Mutex::Autolock lock(mStatusLock);
5006 return mStatus;
5007}
5008
Austin Borgered99f642023-06-01 16:51:35 -07005009std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005010 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005011 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005012 return res;
5013}
5014
Ruben Brunkcc776712015-02-17 20:18:47 -08005015CameraParameters CameraService::CameraState::getShimParams() const {
5016 return mShimParams;
5017}
5018
5019void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5020 mShimParams = params;
5021}
5022
5023int CameraService::CameraState::getCost() const {
5024 return mCost;
5025}
5026
Austin Borgered99f642023-06-01 16:51:35 -07005027std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005028 return mConflicting;
5029}
5030
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005031SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5032 return mSystemCameraKind;
5033}
5034
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005035bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5036 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5037 != mPhysicalCameras.end();
5038}
5039
Austin Borgered99f642023-06-01 16:51:35 -07005040bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005041 Mutex::Autolock lock(mStatusLock);
5042 auto result = mUnavailablePhysicalIds.insert(physicalId);
5043 return result.second;
5044}
5045
Austin Borgered99f642023-06-01 16:51:35 -07005046bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005047 Mutex::Autolock lock(mStatusLock);
5048 auto count = mUnavailablePhysicalIds.erase(physicalId);
5049 return count > 0;
5050}
5051
Austin Borgered99f642023-06-01 16:51:35 -07005052void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005053 Mutex::Autolock lock(mStatusLock);
5054 mClientPackage = clientPackage;
5055}
5056
Austin Borgered99f642023-06-01 16:51:35 -07005057std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005058 Mutex::Autolock lock(mStatusLock);
5059 return mClientPackage;
5060}
5061
Ruben Brunkcc776712015-02-17 20:18:47 -08005062// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005063// ClientEventListener
5064// ----------------------------------------------------------------------------
5065
5066void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005067 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005068 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005069 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005070 if (basicClient.get() != nullptr) {
5071 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005072 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005073 static_cast<int>(basicClient->getClientUid()));
5074 }
5075}
5076
5077void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005078 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005079 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005080 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005081 if (basicClient.get() != nullptr) {
5082 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005083 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005084 static_cast<int>(basicClient->getClientUid()));
5085 }
5086}
5087
Ruben Brunk99e69712015-05-26 17:25:07 -07005088// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005089// CameraClientManager
5090// ----------------------------------------------------------------------------
5091
Ruben Brunk99e69712015-05-26 17:25:07 -07005092CameraService::CameraClientManager::CameraClientManager() {
5093 setListener(std::make_shared<ClientEventListener>());
5094}
5095
Ruben Brunkcc776712015-02-17 20:18:47 -08005096CameraService::CameraClientManager::~CameraClientManager() {}
5097
5098sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005099 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005100 auto descriptor = get(id);
5101 if (descriptor == nullptr) {
5102 return sp<BasicClient>{nullptr};
5103 }
5104 return descriptor->getValue();
5105}
5106
Austin Borgered99f642023-06-01 16:51:35 -07005107std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005108 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005109 std::ostringstream ret;
5110 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005111 bool hasAny = false;
5112 for (auto& i : all) {
5113 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005114 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005115 int32_t cost = i->getCost();
5116 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005117 int32_t score = i->getPriority().getScore();
5118 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005119 auto conflicting = i->getConflicting();
5120 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005121 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005122 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005123 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005124 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005125 uid_t clientUid = clientSp->getClientUid();
5126 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005127 }
Austin Borgered99f642023-06-01 16:51:35 -07005128 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5129 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005130
Ruben Brunk6267b532015-04-30 17:44:07 -07005131 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005132 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005133 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005134 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005135 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005136 }
5137
Austin Borgered99f642023-06-01 16:51:35 -07005138 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005139 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005140 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005141 }
Austin Borgered99f642023-06-01 16:51:35 -07005142 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005143 }
Austin Borgered99f642023-06-01 16:51:35 -07005144 if (hasAny) ret << "\n";
5145 ret << "]\n";
Yi Kong3ac211f2024-08-12 07:31:44 +08005146 return ret.str();
Ruben Brunkcc776712015-02-17 20:18:47 -08005147}
5148
5149CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005150 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5151 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005152 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005153
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005154 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005155 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005156
Austin Borgered99f642023-06-01 16:51:35 -07005157 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005158 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5159 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005160}
5161
5162CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005163 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005164 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005165 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005166 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005167 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5168 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005169}
5170
5171// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005172// InjectionStatusListener
5173// ----------------------------------------------------------------------------
5174
5175void CameraService::InjectionStatusListener::addListener(
5176 const sp<ICameraInjectionCallback>& callback) {
5177 Mutex::Autolock lock(mListenerLock);
5178 if (mCameraInjectionCallback) return;
5179 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5180 if (res == OK) {
5181 mCameraInjectionCallback = callback;
5182 }
5183}
5184
5185void CameraService::InjectionStatusListener::removeListener() {
5186 Mutex::Autolock lock(mListenerLock);
5187 if (mCameraInjectionCallback == nullptr) {
5188 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5189 return;
5190 }
5191 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5192 mCameraInjectionCallback = nullptr;
5193}
5194
5195void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005196 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005197 if (mCameraInjectionCallback == nullptr) {
5198 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5199 return;
5200 }
Cliff Wud3a05312021-04-26 23:07:31 +08005201
5202 switch (err) {
5203 case -ENODEV:
5204 mCameraInjectionCallback->onInjectionError(
5205 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5206 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005207 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005208 break;
5209 case -EBUSY:
5210 mCameraInjectionCallback->onInjectionError(
5211 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5212 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005213 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005214 break;
5215 case DEAD_OBJECT:
5216 mCameraInjectionCallback->onInjectionError(
5217 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5218 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005219 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005220 break;
5221 case INVALID_OPERATION:
5222 mCameraInjectionCallback->onInjectionError(
5223 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5224 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005225 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005226 break;
5227 case UNKNOWN_TRANSACTION:
5228 mCameraInjectionCallback->onInjectionError(
5229 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5230 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005231 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005232 break;
5233 default:
5234 mCameraInjectionCallback->onInjectionError(
5235 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5236 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005237 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005238 }
Cliff Wud8cae102021-03-11 01:37:42 +08005239}
5240
5241void CameraService::InjectionStatusListener::binderDied(
5242 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005243 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5244 auto parent = mParent.promote();
5245 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005246 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5247 if (clientDescriptor != nullptr) {
5248 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5249 baseClientPtr->stopInjection();
5250 }
Cliff Wu3b268182021-07-06 15:44:43 +08005251 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005252 }
5253}
5254
5255// ----------------------------------------------------------------------------
5256// CameraInjectionSession
5257// ----------------------------------------------------------------------------
5258
5259binder::Status CameraService::CameraInjectionSession::stopInjection() {
5260 Mutex::Autolock lock(mInjectionSessionLock);
5261 auto parent = mParent.promote();
5262 if (parent == nullptr) {
5263 ALOGE("CameraInjectionSession: Parent is gone");
5264 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5265 "Camera service encountered error");
5266 }
Cliff Wud3a05312021-04-26 23:07:31 +08005267
5268 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005269 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5270 if (clientDescriptor != nullptr) {
5271 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5272 res = baseClientPtr->stopInjection();
5273 if (res != OK) {
5274 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5275 " ret != NO_ERROR: %d", res);
5276 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5277 "Camera session encountered error");
5278 }
5279 }
Cliff Wu3b268182021-07-06 15:44:43 +08005280 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005281 return binder::Status::ok();
5282}
5283
5284// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005285
5286static const int kDumpLockRetries = 50;
5287static const int kDumpLockSleep = 60000;
5288
5289static bool tryLock(Mutex& mutex)
5290{
5291 bool locked = false;
5292 for (int i = 0; i < kDumpLockRetries; ++i) {
5293 if (mutex.tryLock() == NO_ERROR) {
5294 locked = true;
5295 break;
5296 }
5297 usleep(kDumpLockSleep);
5298 }
5299 return locked;
5300}
5301
Rucha Katakwardf223072021-06-15 10:21:00 -07005302void CameraService::cacheDump() {
5303 if (mMemFd != -1) {
5304 const Vector<String16> args;
5305 ATRACE_CALL();
5306 // Acquiring service lock here will avoid the deadlock since
5307 // cacheDump will not be called during the second disconnect.
5308 Mutex::Autolock lock(mServiceLock);
5309
5310 Mutex::Autolock l(mCameraStatesLock);
5311 // Start collecting the info for open sessions and store it in temp file.
5312 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005313 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005314 auto clientDescriptor = mActiveClientManager.get(cameraId);
5315 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005316 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005317 // Log the current open session info before device is disconnected.
5318 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5319 }
5320 }
5321 }
5322}
5323
Mathias Agopian65ab4712010-07-14 17:59:35 -07005324status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005325 ATRACE_CALL();
5326
Austin Borgered99f642023-06-01 16:51:35 -07005327 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005328 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005329 getCallingPid(),
5330 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005331 return NO_ERROR;
5332 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005333 bool locked = tryLock(mServiceLock);
5334 // failed to lock - CameraService is probably deadlocked
5335 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005336 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005337 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005338
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005339 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005340 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005341
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005342 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005343 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005344
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005345 if (locked) mServiceLock.unlock();
5346 return NO_ERROR;
5347 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005348 dprintf(fd, "\n== Service global info: ==\n\n");
5349 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005350 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005351 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5352 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005353 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5354 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5355 }
Austin Borgered99f642023-06-01 16:51:35 -07005356 std::string activeClientString = mActiveClientManager.toString();
5357 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5358 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005359 if (mStreamUseCaseOverrides.size() > 0) {
5360 dprintf(fd, "Active stream use case overrides:");
5361 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5362 dprintf(fd, " %" PRId64, useCaseOverride);
5363 }
5364 dprintf(fd, "\n");
5365 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005366
5367 dumpEventLog(fd);
5368
5369 bool stateLocked = tryLock(mCameraStatesLock);
5370 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005371 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005372 }
5373
Emilian Peevbd8c5032018-02-14 23:05:40 +00005374 int argSize = args.size();
5375 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005376 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005377 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005378 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005379 }
5380 break;
5381 }
5382 }
5383
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005384 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005385 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005386
Austin Borgered99f642023-06-01 16:51:35 -07005387 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005388
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005389 CameraParameters p = state.second->getShimParams();
5390 if (!p.isEmpty()) {
5391 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5392 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005393 }
5394
5395 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005396 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005397 // log the current open session info
5398 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005399 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005400 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005401 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005402
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005403 }
5404
5405 if (stateLocked) mCameraStatesLock.unlock();
5406
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005407 if (locked) mServiceLock.unlock();
5408
Emilian Peevf53f66e2017-04-11 14:29:43 +01005409 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005410
5411 dprintf(fd, "\n== Vendor tags: ==\n\n");
5412
5413 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5414 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005415 sp<VendorTagDescriptorCache> cache =
5416 VendorTagDescriptorCache::getGlobalVendorTagCache();
5417 if (cache == NULL) {
5418 dprintf(fd, "No vendor tags.\n");
5419 } else {
5420 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5421 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005422 } else {
5423 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5424 }
5425
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005426 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005427 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005428 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005429
5430 // Process dump arguments, if any
5431 int n = args.size();
5432 String16 verboseOption("-v");
5433 String16 unreachableOption("--unreachable");
5434 for (int i = 0; i < n; i++) {
5435 if (args[i] == verboseOption) {
5436 // change logging level
5437 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005438 std::string levelStr = toStdString(args[i+1]);
5439 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005440 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005441 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005442 } else if (args[i] == unreachableOption) {
5443 // Dump memory analysis
5444 // TODO - should limit be an argument parameter?
5445 UnreachableMemoryInfo info;
5446 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5447 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005448 dprintf(fd, "\n== Unable to dump unreachable memory. "
5449 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005450 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005451 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005452 std::string s = info.ToString(/*log_contents*/ true);
5453 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005454 }
5455 }
5456 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005457
5458 bool serviceLocked = tryLock(mServiceLock);
5459
5460 // Dump info from previous open sessions.
5461 // Reposition the offset to beginning of the file before reading
5462
5463 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5464 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5465 ssize_t size_read;
5466 char buf[4096];
5467 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5468 // Read data from file to a small buffer and write it to fd.
5469 write(fd, buf, size_read);
5470 if (size_read == -1) {
5471 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5472 break;
5473 }
5474 }
5475 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5476 } else {
5477 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5478 }
5479
5480 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005481 return NO_ERROR;
5482}
5483
Rucha Katakwardf223072021-06-15 10:21:00 -07005484void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005485 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005486 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005487 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005488 getFormattedCurrentTime().c_str(),
5489 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005490 dprintf(fd, " Client priority score: %d state: %d\n",
5491 clientDescriptor->getPriority().getScore(),
5492 clientDescriptor->getPriority().getState());
5493 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5494
5495 auto client = clientDescriptor->getValue();
5496 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005497 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005498
5499 client->dumpClient(fd, args);
5500}
5501
Austin Borgered99f642023-06-01 16:51:35 -07005502void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005503 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005504 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005505}
5506
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005507void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005508 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005509
5510 Mutex::Autolock l(mLogLock);
5511 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005512 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005513 }
5514
5515 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005516 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005517 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005518 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005519 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005520 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005521}
5522
Austin Borgered99f642023-06-01 16:51:35 -07005523void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005524 Mutex::Autolock lock(mLogLock);
5525 if (!isClientWatchedLocked(client)) { return; }
5526
5527 std::vector<std::string> dumpVector;
5528 client->dumpWatchedEventsToVector(dumpVector);
5529
5530 if (dumpVector.empty()) { return; }
5531
Austin Borgered99f642023-06-01 16:51:35 -07005532 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005533
Austin Borgered99f642023-06-01 16:51:35 -07005534 std::string currentTime = getFormattedCurrentTime();
5535 dumpString << "Cached @ ";
5536 dumpString << currentTime;
5537 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005538
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005539 size_t i = dumpVector.size();
5540
5541 // Store the string in reverse order (latest last)
5542 while (i > 0) {
5543 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005544 dumpString << cameraId;
5545 dumpString << ":";
5546 dumpString << client->getPackageName();
5547 dumpString << " ";
5548 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005549 }
5550
Austin Borgered99f642023-06-01 16:51:35 -07005551 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005552}
5553
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005554void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005555 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005556 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5557 if (mTorchClientMap[i] == who) {
5558 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005559 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005560 status_t res = mFlashlight->setTorchMode(cameraId, false);
5561 if (res) {
5562 ALOGE("%s: torch client died but couldn't turn off torch: "
5563 "%s (%d)", __FUNCTION__, strerror(-res), res);
5564 return;
5565 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005566 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005567 break;
5568 }
5569 }
5570}
5571
Ruben Brunkcc776712015-02-17 20:18:47 -08005572/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005573
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005574 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005575 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5576 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005577 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005578 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005579 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005580
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005581 // check torch client
5582 handleTorchClientBinderDied(who);
5583
5584 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005585 if(!evictClientIdByRemote(who)) {
5586 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005587 return;
5588 }
5589
Ruben Brunkcc776712015-02-17 20:18:47 -08005590 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5591 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005592}
5593
Austin Borgered99f642023-06-01 16:51:35 -07005594void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005595 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005596}
5597
Austin Borgered99f642023-06-01 16:51:35 -07005598void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005599 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005600 // Do not lock mServiceLock here or can get into a deadlock from
5601 // connect() -> disconnect -> updateStatus
5602
5603 auto state = getCameraState(cameraId);
5604
5605 if (state == nullptr) {
5606 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005607 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005608 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005609 }
5610
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005611 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5612 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5613 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005614 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005615 return;
5616 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005617
Biswarup Pal37a75182024-01-16 15:53:35 +00005618 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5619 CameraMetadata cameraInfo;
5620 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00005621 cameraId, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +00005622 if (res != OK) {
5623 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5624 __FUNCTION__, cameraId.c_str());
5625 } else {
5626 int32_t deviceId = getDeviceId(cameraInfo);
5627 if (deviceId != kDefaultDeviceId) {
5628 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5629 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5630 static_cast<camera_metadata_enum_android_lens_facing_t>(
5631 lensFacingEntry.data.u8[0]);
5632 std::string mappedCameraId;
5633 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5634 mappedCameraId = kVirtualDeviceBackCameraId;
5635 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5636 mappedCameraId = kVirtualDeviceFrontCameraId;
5637 } else {
5638 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5639 __func__);
5640 }
5641 if (!mappedCameraId.empty()) {
5642 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5643 }
5644 }
5645 }
5646 }
5647
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005648 // Collect the logical cameras without holding mStatusLock in updateStatus
5649 // as that can lead to a deadlock(b/162192331).
5650 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005651 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005652 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005653 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005654 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005655 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005656 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5657 auto [deviceId, mappedCameraId] =
5658 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005659
Biswarup Pal37a75182024-01-16 15:53:35 +00005660 if (status != StatusInternal::ENUMERATING) {
5661 // Update torch status if it has a flash unit.
5662 Mutex::Autolock al(mTorchStatusMutex);
5663 TorchModeStatus torchStatus;
5664 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5665 NAME_NOT_FOUND) {
5666 TorchModeStatus newTorchStatus =
5667 status == StatusInternal::PRESENT ?
5668 TorchModeStatus::AVAILABLE_OFF :
5669 TorchModeStatus::NOT_AVAILABLE;
5670 if (torchStatus != newTorchStatus) {
5671 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5672 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005673 }
5674 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005675
Biswarup Pal37a75182024-01-16 15:53:35 +00005676 Mutex::Autolock lock(mStatusListenerLock);
5677 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5678 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005679
Biswarup Pal37a75182024-01-16 15:53:35 +00005680 for (auto& listener : mListenerList) {
5681 bool isVendorListener = listener->isVendorListener();
5682 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5683 listener->getListenerPid(), listener->getListenerUid())) {
5684 ALOGV("Skipping discovery callback for system-only camera device %s",
5685 cameraId.c_str());
5686 continue;
5687 }
5688
5689 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5690 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005691 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005692 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005693 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5694 ret.exceptionCode());
5695 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005696 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005697}
5698
Austin Borgered99f642023-06-01 16:51:35 -07005699void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5700 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005701 auto state = getCameraState(cameraId);
5702 if (state == nullptr) {
5703 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005704 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005705 return;
5706 }
5707 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005708 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005709 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005710 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005711 }
5712
Biswarup Pal37a75182024-01-16 15:53:35 +00005713 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5714 auto [deviceId, mappedCameraId] =
5715 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5716
Shuzhen Wang695044d2020-03-06 09:02:23 -08005717 Mutex::Autolock lock(mStatusListenerLock);
5718
5719 for (const auto& it : mListenerList) {
5720 if (!it->isOpenCloseCallbackAllowed()) {
5721 continue;
5722 }
5723
5724 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005725 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005726 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5727 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005728 } else {
Biswarup Pal37a75182024-01-16 15:53:35 +00005729 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005730 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005731
5732 it->handleBinderStatus(ret,
5733 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5734 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005735 }
5736}
5737
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005738template<class Func>
5739void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005740 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005741 std::initializer_list<StatusInternal> rejectSourceStates,
5742 Func onStatusUpdatedLocked) {
5743 Mutex::Autolock lock(mStatusLock);
5744 StatusInternal oldStatus = mStatus;
5745 mStatus = status;
5746
5747 if (oldStatus == status) {
5748 return;
5749 }
5750
5751 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07005752 cameraId.c_str(), eToI(oldStatus), eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005753
5754 if (oldStatus == StatusInternal::NOT_PRESENT &&
5755 (status != StatusInternal::PRESENT &&
5756 status != StatusInternal::ENUMERATING)) {
5757
5758 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5759 __FUNCTION__);
5760 mStatus = oldStatus;
5761 return;
5762 }
5763
5764 /**
5765 * Sometimes we want to conditionally do a transition.
5766 * For example if a client disconnects, we want to go to PRESENT
5767 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5768 */
5769 for (auto& rejectStatus : rejectSourceStates) {
5770 if (oldStatus == rejectStatus) {
5771 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005772 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005773 mStatus = oldStatus;
5774 return;
5775 }
5776 }
5777
5778 onStatusUpdatedLocked(cameraId, status);
5779}
5780
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005781status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005782 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005783 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005784 if (!status) {
5785 return BAD_VALUE;
5786 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005787 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5788 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005789 // invalid camera ID or the camera doesn't have a flash unit
5790 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005791 }
5792
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005793 *status = mTorchStatusMap.valueAt(index);
5794 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005795}
5796
Austin Borgered99f642023-06-01 16:51:35 -07005797status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005798 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005799 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5800 if (index == NAME_NOT_FOUND) {
5801 return BAD_VALUE;
5802 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005803 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005804
5805 return OK;
5806}
5807
Austin Borgered99f642023-06-01 16:51:35 -07005808std::list<std::string> CameraService::getLogicalCameras(
5809 const std::string& physicalCameraId) {
5810 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005811 Mutex::Autolock lock(mCameraStatesLock);
5812 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005813 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5814 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005815 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005816 }
5817 return retList;
5818}
5819
5820void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005821 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00005822 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005823 // mStatusListenerLock is expected to be locked
5824 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005825 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005826 // Note: we check only the deviceKind of the physical camera id
5827 // since, logical camera ids and their physical camera ids are
5828 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005829 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5830 listener->getListenerPid(), listener->getListenerUid())) {
5831 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005832 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005833 continue;
5834 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005835 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00005836 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005837 listener->handleBinderStatus(ret,
5838 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5839 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5840 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005841 }
5842 }
5843}
5844
Svet Ganova453d0d2018-01-11 15:37:58 -08005845void CameraService::blockClientsForUid(uid_t uid) {
5846 const auto clients = mActiveClientManager.getAll();
5847 for (auto& current : clients) {
5848 if (current != nullptr) {
5849 const auto basicClient = current->getValue();
5850 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5851 basicClient->block();
5852 }
5853 }
5854 }
5855}
5856
Michael Grooverd1d435a2018-12-18 17:39:42 -08005857void CameraService::blockAllClients() {
5858 const auto clients = mActiveClientManager.getAll();
5859 for (auto& current : clients) {
5860 if (current != nullptr) {
5861 const auto basicClient = current->getValue();
5862 if (basicClient.get() != nullptr) {
5863 basicClient->block();
5864 }
5865 }
5866 }
5867}
5868
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005869void CameraService::blockPrivacyEnabledClients() {
5870 const auto clients = mActiveClientManager.getAll();
5871 for (auto& current : clients) {
5872 if (current != nullptr) {
5873 const auto basicClient = current->getValue();
5874 if (basicClient.get() != nullptr) {
5875 std::string pkgName = basicClient->getPackageName();
5876 bool cameraPrivacyEnabled =
5877 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
5878 if (cameraPrivacyEnabled) {
5879 basicClient->block();
5880 }
5881 }
5882 }
5883 }
5884}
5885
Svet Ganova453d0d2018-01-11 15:37:58 -08005886// NOTE: This is a remote API - make sure all args are validated
5887status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005888 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005889 return PERMISSION_DENIED;
5890 }
5891 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5892 return BAD_VALUE;
5893 }
Austin Borgered99f642023-06-01 16:51:35 -07005894 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005895 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005896 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005897 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005898 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005899 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005900 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005901 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005902 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005903 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005904 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005905 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005906 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005907 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005908 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005909 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005910 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005911 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005912 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005913 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005914 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005915 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005916 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005917 handleClearStreamUseCaseOverrides();
5918 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005919 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005920 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07005921 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005922 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07005923 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00005924 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07005925 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005926 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005927 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005928 }
5929 printHelp(err);
5930 return BAD_VALUE;
5931}
5932
5933status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005934 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005935
Svet Ganova453d0d2018-01-11 15:37:58 -08005936 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07005937 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005938 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07005939 } else if ((args[2] != toString16("idle"))) {
5940 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08005941 return BAD_VALUE;
5942 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005943
5944 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005945 if (args.size() >= 5 && args[3] == toString16("--user")) {
5946 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005947 }
5948
5949 uid_t uid;
5950 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5951 return BAD_VALUE;
5952 }
5953
5954 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005955 return NO_ERROR;
5956}
5957
5958status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005959 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005960
5961 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005962 if (args.size() >= 4 && args[2] == toString16("--user")) {
5963 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005964 }
5965
5966 uid_t uid;
5967 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005968 return BAD_VALUE;
5969 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005970
5971 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005972 return NO_ERROR;
5973}
5974
5975status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005976 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005977
5978 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005979 if (args.size() >= 4 && args[2] == toString16("--user")) {
5980 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005981 }
5982
5983 uid_t uid;
5984 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005985 return BAD_VALUE;
5986 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005987
5988 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005989 return dprintf(out, "active\n");
5990 } else {
5991 return dprintf(out, "idle\n");
5992 }
5993}
5994
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005995status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005996 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005997 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
5998 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
5999 Mutex::Autolock lock(mServiceLock);
6000
6001 mOverrideRotateAndCropMode = rotateValue;
6002
6003 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6004
6005 const auto clients = mActiveClientManager.getAll();
6006 for (auto& current : clients) {
6007 if (current != nullptr) {
6008 const auto basicClient = current->getValue();
6009 if (basicClient.get() != nullptr) {
6010 basicClient->setRotateAndCropOverride(rotateValue);
6011 }
6012 }
6013 }
6014
6015 return OK;
6016}
6017
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006018status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6019 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006020 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006021 if ((*end != '\0') ||
6022 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6023 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6024 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6025 return BAD_VALUE;
6026 }
6027
6028 Mutex::Autolock lock(mServiceLock);
6029 mOverrideAutoframingMode = autoframingValue;
6030
6031 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6032
6033 const auto clients = mActiveClientManager.getAll();
6034 for (auto& current : clients) {
6035 if (current != nullptr) {
6036 const auto basicClient = current->getValue();
6037 if (basicClient.get() != nullptr) {
6038 basicClient->setAutoframingOverride(autoframingValue);
6039 }
6040 }
6041 }
6042
6043 return OK;
6044}
6045
Ravneetaeb20dc2022-03-30 05:33:03 +00006046status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006047 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006048
6049 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6050
6051 Mutex::Autolock lock(mServiceLock);
6052
6053 mCameraServiceWatchdogEnabled = enableWatchdog;
6054
6055 const auto clients = mActiveClientManager.getAll();
6056 for (auto& current : clients) {
6057 if (current != nullptr) {
6058 const auto basicClient = current->getValue();
6059 if (basicClient.get() != nullptr) {
6060 basicClient->setCameraServiceWatchdog(enableWatchdog);
6061 }
6062 }
6063 }
6064
6065 return OK;
6066}
6067
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006068status_t CameraService::handleGetRotateAndCrop(int out) {
6069 Mutex::Autolock lock(mServiceLock);
6070
6071 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6072}
6073
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006074status_t CameraService::handleGetAutoframing(int out) {
6075 Mutex::Autolock lock(mServiceLock);
6076
6077 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6078}
6079
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006080status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6081 char *endPtr;
6082 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006083 std::string maskString = toStdString(args[1]);
6084 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006085
6086 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006087 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006088 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6089
6090 Mutex::Autolock lock(mServiceLock);
6091
6092 mImageDumpMask = maskValue;
6093
6094 return OK;
6095}
6096
6097status_t CameraService::handleGetImageDumpMask(int out) {
6098 Mutex::Autolock lock(mServiceLock);
6099
6100 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6101}
6102
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006103status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006104 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006105 if (errno != 0) return BAD_VALUE;
6106
6107 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6108 Mutex::Autolock lock(mServiceLock);
6109
6110 mOverrideCameraMuteMode = (muteValue == 1);
6111
6112 const auto clients = mActiveClientManager.getAll();
6113 for (auto& current : clients) {
6114 if (current != nullptr) {
6115 const auto basicClient = current->getValue();
6116 if (basicClient.get() != nullptr) {
6117 if (basicClient->supportsCameraMute()) {
6118 basicClient->setCameraMute(mOverrideCameraMuteMode);
6119 }
6120 }
6121 }
6122 }
6123
6124 return OK;
6125}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006126
Shuzhen Wang16610a62022-12-15 22:38:07 -08006127status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6128 std::vector<int64_t> useCasesOverride;
6129 for (size_t i = 1; i < args.size(); i++) {
6130 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006131 std::string arg = toStdString(args[i]);
6132 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006133 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006134 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006135 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006136 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006137 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006138 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006139 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006140 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006141 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006142 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006143 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006144 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006145 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6146 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006147 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006148 return BAD_VALUE;
6149 }
6150 useCasesOverride.push_back(useCase);
6151 }
6152
6153 Mutex::Autolock lock(mServiceLock);
6154 mStreamUseCaseOverrides = std::move(useCasesOverride);
6155
6156 return OK;
6157}
6158
6159void CameraService::handleClearStreamUseCaseOverrides() {
6160 Mutex::Autolock lock(mServiceLock);
6161 mStreamUseCaseOverrides.clear();
6162}
6163
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006164status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6165 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006166 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006167 if ((*end != '\0') ||
6168 (zoomOverrideValue != -1 &&
6169 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6170 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6171 return BAD_VALUE;
6172 }
6173
6174 Mutex::Autolock lock(mServiceLock);
6175 mZoomOverrideValue = zoomOverrideValue;
6176
6177 const auto clients = mActiveClientManager.getAll();
6178 for (auto& current : clients) {
6179 if (current != nullptr) {
6180 const auto basicClient = current->getValue();
6181 if (basicClient.get() != nullptr) {
6182 if (basicClient->supportsZoomOverride()) {
6183 basicClient->setZoomOverride(mZoomOverrideValue);
6184 }
6185 }
6186 }
6187 }
6188
6189 return OK;
6190}
6191
Avichal Rakesh84147132021-11-11 17:47:11 -08006192status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006193 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006194 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006195 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006196 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006197 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006198 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006199 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006200 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006201 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006202 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006203 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006204 dprintf(outFd, "Camera service watch commands:\n"
6205 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6206 " starts watching the provided tags for clients with provided package\n"
6207 " recognizes tag shorthands like '3a'\n"
6208 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006209 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006210 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006211 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006212 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006213 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006214 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006215 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006216}
6217
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006218status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6219 Mutex::Autolock lock(mLogLock);
6220 size_t tagsIdx; // index of '-m'
6221 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006222 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006223 if (tagsIdx < args.size() - 1) {
6224 tags = args[tagsIdx + 1];
6225 } else {
6226 dprintf(outFd, "No tags provided.\n");
6227 return BAD_VALUE;
6228 }
6229
6230 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006231 // watch all clients if no clients are provided
6232 String16 clients = toString16(kWatchAllClientsFlag);
6233 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006234 clientsIdx++);
6235 if (clientsIdx < args.size() - 1) {
6236 clients = args[clientsIdx + 1];
6237 }
Austin Borgered99f642023-06-01 16:51:35 -07006238 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006239
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006240 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006241 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006242
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006243 bool serviceLock = tryLock(mServiceLock);
6244 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006245 auto cameraClients = mActiveClientManager.getAll();
6246 for (const auto &clientDescriptor: cameraClients) {
6247 if (clientDescriptor == nullptr) { continue; }
6248 sp<BasicClient> client = clientDescriptor->getValue();
6249 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006250
6251 if (isClientWatchedLocked(client.get())) {
6252 client->startWatchingTags(mMonitorTags, outFd);
6253 numWatchedClients++;
6254 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006255 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006256 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6257
6258 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006259 return OK;
6260}
6261
6262status_t CameraService::stopWatchingTags(int outFd) {
6263 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006264 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006265 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006266
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006267 mWatchedClientPackages.clear();
6268 mWatchedClientsDumpCache.clear();
6269
6270 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006271 auto cameraClients = mActiveClientManager.getAll();
6272 for (const auto &clientDescriptor : cameraClients) {
6273 if (clientDescriptor == nullptr) { continue; }
6274 sp<BasicClient> client = clientDescriptor->getValue();
6275 if (client.get() == nullptr) { continue; }
6276 client->stopWatchingTags(outFd);
6277 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006278 dprintf(outFd, "Stopped watching all clients.\n");
6279 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006280 return OK;
6281}
6282
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006283status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6284 Mutex::Autolock lock(mLogLock);
6285 size_t clearedSize = mWatchedClientsDumpCache.size();
6286 mWatchedClientsDumpCache.clear();
6287 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6288 return OK;
6289}
6290
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006291status_t CameraService::printWatchedTags(int outFd) {
6292 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006293 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006294
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006295 bool printedSomething = false; // tracks if any monitoring information was printed
6296 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006297
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006298 bool serviceLock = tryLock(mServiceLock);
6299 // get all watched clients that are currently connected
6300 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6301 if (clientDescriptor == nullptr) { continue; }
6302
6303 sp<BasicClient> client = clientDescriptor->getValue();
6304 if (client.get() == nullptr) { continue; }
6305 if (!isClientWatchedLocked(client.get())) { continue; }
6306
6307 std::vector<std::string> dumpVector;
6308 client->dumpWatchedEventsToVector(dumpVector);
6309
6310 size_t printIdx = dumpVector.size();
6311 if (printIdx == 0) {
6312 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006313 }
6314
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006315 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006316 const std::string &cameraId = clientDescriptor->getKey();
6317 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006318 while(printIdx > 0) {
6319 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006320 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006321 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006322 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006323 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006324 printedSomething = true;
6325
6326 connectedMonitoredClients.emplace(client->getPackageName());
6327 }
6328 if (serviceLock) { mServiceLock.unlock(); }
6329
6330 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6331 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006332 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006333 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6334 continue;
6335 }
6336
Austin Borgered99f642023-06-01 16:51:35 -07006337 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006338 dprintf(outFd, "%s\n", kv.second.c_str());
6339 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006340 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006341
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006342 if (!printedSomething) {
6343 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006344 }
6345
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006346 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006347}
6348
Avichal Rakesh84147132021-11-11 17:47:11 -08006349// Print all events in vector `events' that came after lastPrintedEvent
6350void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006351 const std::string &cameraId,
6352 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006353 const std::vector<std::string> &events,
6354 const std::string &lastPrintedEvent) {
6355 if (events.empty()) { return; }
6356
6357 // index of lastPrintedEvent in events.
6358 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6359 size_t lastPrintedIdx;
6360 for (lastPrintedIdx = 0;
6361 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6362 lastPrintedIdx++);
6363
6364 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6365
Avichal Rakesh84147132021-11-11 17:47:11 -08006366 // print events in chronological order (latest event last)
6367 size_t idxToPrint = lastPrintedIdx;
6368 do {
6369 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006370 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6371 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006372 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006373}
6374
6375// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6376// command should be interrupted if the user presses the return key, or if user loses any way to
6377// signal interrupt.
6378// If timeoutMs == 0, this function will always return false
6379bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6380 struct timeval startTime;
6381 int startTimeError = gettimeofday(&startTime, nullptr);
6382 if (startTimeError) {
6383 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6384 return true;
6385 }
6386
6387 const nfds_t numFds = 1;
6388 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6389
6390 struct timeval currTime;
6391 char buffer[2];
6392 while(true) {
6393 int currTimeError = gettimeofday(&currTime, nullptr);
6394 if (currTimeError) {
6395 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6396 return true;
6397 }
6398
6399 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6400 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6401 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6402
6403 if (remainingTimeMs <= 0) {
6404 // No user interrupt within timeoutMs, don't interrupt watch command
6405 return false;
6406 }
6407
6408 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6409 if (numFdsUpdated < 0) {
6410 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6411 return true;
6412 }
6413
6414 if (numFdsUpdated == 0) {
6415 // No user input within timeoutMs, don't interrupt watch command
6416 return false;
6417 }
6418
6419 if (!(pollFd.revents & POLLIN)) {
6420 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6421 return true;
6422 }
6423
6424 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6425 if (sizeRead < 0) {
6426 dprintf(outFd, "Error reading user input. Exiting.\n");
6427 return true;
6428 }
6429
6430 if (sizeRead == 0) {
6431 // Reached end of input fd (can happen if input is piped)
6432 // User has no way to signal an interrupt, so interrupt here
6433 return true;
6434 }
6435
6436 if (buffer[0] == '\n') {
6437 // User pressed return, interrupt watch command.
6438 return true;
6439 }
6440 }
6441}
6442
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006443status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6444 int inFd, int outFd) {
6445 // Figure out refresh interval, if present in args
6446 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006447 if (args.size() > 2) {
6448 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006449 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006450 intervalIdx++);
6451
6452 size_t intervalValIdx = intervalIdx + 1;
6453 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006454 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006455 if (errno) { return BAD_VALUE; }
6456 }
6457 }
6458
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006459 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6460 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006461
Avichal Rakesh84147132021-11-11 17:47:11 -08006462 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006463 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006464
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006465 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006466 bool serviceLock = tryLock(mServiceLock);
6467 auto cameraClients = mActiveClientManager.getAll();
6468 if (serviceLock) { mServiceLock.unlock(); }
6469
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006470 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006471 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006472 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006473
6474 sp<BasicClient> client = clientDescriptor->getValue();
6475 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006476 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006477
Austin Borgered99f642023-06-01 16:51:35 -07006478 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006479 // This also initializes the map entries with an empty string
6480 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6481
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006482 std::vector<std::string> latestEvents;
6483 client->dumpWatchedEventsToVector(latestEvents);
6484
6485 if (!latestEvents.empty()) {
6486 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006487 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006488 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006489 latestEvents,
6490 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006491 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006492 }
6493 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006494 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006495 break;
6496 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006497 }
6498 return OK;
6499}
6500
Austin Borgered99f642023-06-01 16:51:35 -07006501void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006502 mWatchedClientPackages.clear();
6503
Austin Borgered99f642023-06-01 16:51:35 -07006504 std::istringstream iss(clients);
6505 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006506
Austin Borgered99f642023-06-01 16:51:35 -07006507 while (std::getline(iss, nextClient, ',')) {
6508 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006509 // Don't need to track any other package if 'all' is present
6510 mWatchedClientPackages.clear();
6511 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6512 break;
6513 }
6514
6515 // track package names
6516 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006517 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006518}
6519
Svet Ganova453d0d2018-01-11 15:37:58 -08006520status_t CameraService::printHelp(int out) {
6521 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006522 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6523 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6524 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006525 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6526 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6527 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006528 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6529 " Valid values 0=false, 1=true, 2=auto\n"
6530 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006531 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6532 " Valid values 0=OFF, 1=ON for JPEG\n"
6533 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006534 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006535 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6536 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6537 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6538 " on. In case the number of usecases is smaller than the number of streams, the\n"
6539 " last use case is assigned to all the remaining streams. In case of multiple\n"
6540 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6541 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6542 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6543 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006544 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6545 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006546 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6547 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006548 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006549 " help print this message\n");
6550}
6551
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006552bool CameraService::isClientWatched(const BasicClient *client) {
6553 Mutex::Autolock lock(mLogLock);
6554 return isClientWatchedLocked(client);
6555}
6556
6557bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6558 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6559 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6560}
6561
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006562int32_t CameraService::updateAudioRestriction() {
6563 Mutex::Autolock lock(mServiceLock);
6564 return updateAudioRestrictionLocked();
6565}
6566
6567int32_t CameraService::updateAudioRestrictionLocked() {
6568 int32_t mode = 0;
6569 // iterate through all active client
6570 for (const auto& i : mActiveClientManager.getAll()) {
6571 const auto clientSp = i->getValue();
6572 mode |= clientSp->getAudioRestriction();
6573 }
6574
6575 bool modeChanged = (mAudioRestriction != mode);
6576 mAudioRestriction = mode;
6577 if (modeChanged) {
6578 mAppOps.setCameraAudioRestriction(mode);
6579 }
6580 return mode;
6581}
6582
Austin Borgered99f642023-06-01 16:51:35 -07006583status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006584 sp<BasicClient> clientSp) {
6585 std::unique_ptr<AutoConditionLock> lock =
6586 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6587 status_t res = NO_ERROR;
6588 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006589 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006590 mInjectionStatusListener->notifyInjectionError(
6591 externalCamId, UNKNOWN_TRANSACTION);
6592 clientSp->notifyError(
6593 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6594 CaptureResultExtras());
6595
6596 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6597 // other clients from connecting in mServiceLockWrapper if held
6598 mServiceLock.unlock();
6599
6600 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006601 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006602 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006603 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006604
6605 // Reacquire mServiceLock
6606 mServiceLock.lock();
6607 }
6608
6609 return res;
6610}
6611
Cliff Wud3a05312021-04-26 23:07:31 +08006612void CameraService::clearInjectionParameters() {
6613 {
6614 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006615 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006616 mInjectionInternalCamId = "";
6617 }
6618 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006619 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006620}
6621
Biswarup Pal37a75182024-01-16 15:53:35 +00006622} // namespace android