blob: acc3b32813d71b950ed9d9142391dcc5085ffdf3 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080024#include <cstdlib>
Ruben Brunkcc776712015-02-17 20:18:47 -080025#include <cstring>
26#include <ctime>
Austin Borgered99f642023-06-01 16:51:35 -070027#include <iostream>
28#include <sstream>
Ruben Brunkcc776712015-02-17 20:18:47 -080029#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080031#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <pthread.h>
Avichal Rakesh84147132021-11-11 17:47:11 -080033#include <poll.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070034
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080035#include <android/hardware/ICamera.h>
36#include <android/hardware/ICameraClient.h>
37
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -070038#include <aidl/AidlCameraService.h>
Alex Deymo9c2a2c22016-08-25 11:59:14 -070039#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080040#include <android-base/parseint.h>
Biswarup Pal37a75182024-01-16 15:53:35 +000041#include <android_companion_virtualdevice_flags.h>
42#include <android/companion/virtualnative/IVirtualDeviceManagerNative.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080043#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080044#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046#include <binder/MemoryBase.h>
47#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080048#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080049#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080050#include <binderthreadstate/CallerUtils.h>
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -070051#include <com_android_internal_camera_flags.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070052#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070053#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080054#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080055#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070057#include "hidl/HidlCameraService.h"
58#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080059#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070060#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080062#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070063#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070064#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000065#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070066#include <utils/Errors.h>
67#include <utils/Log.h>
68#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070069#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080070#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080071#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080072#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080073#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070074#include <system/camera_metadata.h>
Kunal Malhotrabfc96052023-02-28 23:25:34 +000075#include <binder/IServiceManager.h>
76#include <binder/IActivityManager.h>
Biswarup Pal37a75182024-01-16 15:53:35 +000077#include <camera/CameraUtils.h>
Austin Borgered99f642023-06-01 16:51:35 -070078#include <camera/StringUtils.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080079
Ruben Brunkb2119af2014-05-09 19:57:56 -070080#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070081
82#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070083#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070084#include "api2/CameraDeviceClient.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070085#include "utils/CameraServiceProxyWrapper.h"
Emilian Peev31bd2422024-04-23 22:24:09 +000086#include "utils/CameraTraces.h"
Shuzhen Wang045be6c2023-10-12 10:01:10 -070087#include "utils/SessionConfigurationUtils.h"
Emilian Peev31bd2422024-04-23 22:24:09 +000088#include "utils/TagMonitor.h"
89#include "utils/Utils.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070090
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080091namespace {
92 const char* kPermissionServiceName = "permission";
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080093 const char* kActivityServiceName = "activity";
94 const char* kSensorPrivacyServiceName = "sensor_privacy";
95 const char* kAppopsServiceName = "appops";
Jyoti Bhayanada519ab2023-05-15 15:49:15 -070096 const char* kProcessInfoServiceName = "processinfo";
Biswarup Pal37a75182024-01-16 15:53:35 +000097 const char* kVirtualDeviceBackCameraId = "0";
98 const char* kVirtualDeviceFrontCameraId = "1";
99
100 int32_t getDeviceId(const android::CameraMetadata& cameraInfo) {
101 if (!cameraInfo.exists(ANDROID_INFO_DEVICE_ID)) {
102 return android::kDefaultDeviceId;
103 }
104
105 const auto &deviceIdEntry = cameraInfo.find(ANDROID_INFO_DEVICE_ID);
106 return deviceIdEntry.data.i32[0];
107 }
108} // namespace anonymous
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -0800109
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110namespace android {
111
Austin Borgerea931242021-12-13 23:10:41 +0000112using namespace camera3;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700113using namespace camera3::SessionConfigurationUtils;
114
115using binder::Status;
Biswarup Pal37a75182024-01-16 15:53:35 +0000116using companion::virtualnative::IVirtualDeviceManagerNative;
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700117using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700118using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800119using hardware::ICamera;
120using hardware::ICameraClient;
121using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800122using hardware::camera2::ICameraInjectionCallback;
123using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800124using hardware::camera2::utils::CameraIdAndSessionConfiguration;
125using hardware::camera2::utils::ConcurrentCameraIdCombination;
Biswarup Pal37a75182024-01-16 15:53:35 +0000126
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -0700127namespace flags = com::android::internal::camera::flags;
Biswarup Pal37a75182024-01-16 15:53:35 +0000128namespace vd_flags = android::companion::virtualdevice::flags;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800129
Mathias Agopian65ab4712010-07-14 17:59:35 -0700130// ----------------------------------------------------------------------------
131// Logging support -- this is for debugging only
132// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700133volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700134
Steve Blockb8a80522011-12-20 16:23:08 +0000135#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
136#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700137
138static void setLogLevel(int level) {
139 android_atomic_write(level, &gLogLevel);
140}
141
Henri Chataingbcb99452023-11-01 17:40:30 +0000142int32_t format_as(CameraService::StatusInternal s) {
143 return fmt::underlying(s);
144}
145
Mathias Agopian65ab4712010-07-14 17:59:35 -0700146// ----------------------------------------------------------------------------
147
Austin Borger249e6592024-03-10 22:28:11 -0700148// Permission strings (references to AttributionAndPermissionUtils for brevity)
149static const std::string &sDumpPermission =
150 AttributionAndPermissionUtils::sDumpPermission;
151static const std::string &sManageCameraPermission =
152 AttributionAndPermissionUtils::sManageCameraPermission;
153static const std::string &sCameraSendSystemEventsPermission =
154 AttributionAndPermissionUtils::sCameraSendSystemEventsPermission;
155static const std::string &sCameraInjectExternalCameraPermission =
156 AttributionAndPermissionUtils::sCameraInjectExternalCameraPermission;
157
Kunal Malhotrabfc96052023-02-28 23:25:34 +0000158// Constant integer for FGS Logging, used to denote the API type for logger
159static const int LOG_FGS_CAMERA_API = 1;
Rucha Katakwardf223072021-06-15 10:21:00 -0700160const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800161static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
162static constexpr int32_t kSystemNativeClientState =
163 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Austin Borgered99f642023-06-01 16:51:35 -0700164static const std::string kServiceName("cameraserver");
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700165
Austin Borgered99f642023-06-01 16:51:35 -0700166const std::string CameraService::kOfflineDevice("offline-");
167const std::string CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700168
Biswarup Pal7d072862024-04-17 15:24:47 +0000169constexpr int32_t kInvalidDeviceId = -1;
170
Rucha Katakward9ea6452021-05-06 11:57:16 -0700171// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700172static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700173
Austin Borger74fca042022-05-23 12:41:21 -0700174CameraService::CameraService(
Austin Borger249e6592024-03-10 22:28:11 -0700175 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,
176 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils) :
177 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils == nullptr ?
178 std::make_shared<AttributionAndPermissionUtils>()\
179 : attributionAndPermissionUtils),
Austin Borger74fca042022-05-23 12:41:21 -0700180 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
181 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800182 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800183 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700184 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700185 mSoundRef(0), mInitialized(false),
186 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000187 ALOGI("CameraService started (pid=%d)", getpid());
Austin Borger249e6592024-03-10 22:28:11 -0700188 mAttributionAndPermissionUtils->setCameraService(this);
Ruben Brunkcc776712015-02-17 20:18:47 -0800189 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700190 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
191 if (mMemFd == -1) {
192 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
193 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700194}
195
Charles Chena7b613c2023-01-24 21:57:33 +0000196// Enable processes with isolated AID to request the binder
197void CameraService::instantiate() {
198 CameraService::publish(true);
199}
200
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800201void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700202 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800203 return;
204 }
205
206 ALOGV("appops service registered. setting camera audio restriction");
207 mAppOps.setCameraAudioRestriction(mAudioRestriction);
208}
209
Iliyan Malchev8951a972011-04-14 16:55:59 -0700210void CameraService::onFirstRef()
211{
Ruben Brunkcc776712015-02-17 20:18:47 -0800212 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800213
Iliyan Malchev8951a972011-04-14 16:55:59 -0700214 BnCameraService::onFirstRef();
215
Ruben Brunk99e69712015-05-26 17:25:07 -0700216 // Update battery life tracking if service is restarting
217 BatteryNotifier& notifier(BatteryNotifier::getInstance());
218 notifier.noteResetCamera();
219 notifier.noteResetFlashlight();
220
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800221 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800222
Emilian Peevf53f66e2017-04-11 14:29:43 +0100223 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800224 if (res == OK) {
225 mInitialized = true;
226 }
227
Svet Ganova453d0d2018-01-11 15:37:58 -0800228 mUidPolicy = new UidPolicy(this);
229 mUidPolicy->registerSelf();
Austin Borger249e6592024-03-10 22:28:11 -0700230 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this, mAttributionAndPermissionUtils);
Michael Grooverd1d435a2018-12-18 17:39:42 -0800231 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800232 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800233
234 // appops function setCamerAudioRestriction uses getService which
235 // is blocking till the appops service is ready. To enable early
236 // boot availability for cameraservice, use checkService which is
237 // non blocking and register for notifications
238 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700239 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800240 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700241 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800242 } else {
243 mAppOps.setCameraAudioRestriction(mAudioRestriction);
244 }
245
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700246 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
247 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000248 // Deprecated, so it will fail to register on newer devices
249 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700250 __FUNCTION__);
251 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700252
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700253 if (!AidlCameraService::registerService(this)) {
254 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
255 }
256
Shuzhen Wang24b44152019-09-20 10:38:11 -0700257 // This needs to be last call in this function, so that it's as close to
258 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700259 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700260 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800261}
262
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800263status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800264 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100265
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800266 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000267 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800268 {
269 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800270
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800271 if (nullptr == mCameraProviderManager.get()) {
272 mCameraProviderManager = new CameraProviderManager();
273 res = mCameraProviderManager->initialize(this);
274 if (res != OK) {
275 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
276 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700277 logServiceError("Unable to initialize camera provider manager",
278 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800279 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100280 }
281 }
282
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800283 // Setup vendor tags before we call get_camera_info the first time
284 // because HAL might need to setup static vendor keys in get_camera_info
285 // TODO: maybe put this into CameraProviderManager::initialize()?
286 mCameraProviderManager->setUpVendorTags();
287
288 if (nullptr == mFlashlight.get()) {
289 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700290 }
291
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800292 res = mFlashlight->findFlashUnits();
293 if (res != OK) {
294 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
295 }
296
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000297 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800298 }
299
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800300 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700301 if (getCameraState(cameraId) == nullptr) {
302 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800303 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000304 if (unavailPhysicalIds.count(cameraId) > 0) {
305 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700306 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000307 }
308 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800309 }
310
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700311 // Derive primary rear/front cameras, and filter their charactierstics.
312 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700313 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700314 // Assume internal cameras are advertised from the same
315 // provider. If multiple providers are registered at different time,
316 // and each provider contains multiple internal color cameras, the current
317 // logic may filter the characteristics of more than one front/rear color
318 // cameras.
319 Mutex::Autolock l(mServiceLock);
320 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700321 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700322
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800323 return OK;
324}
325
Austin Borgered99f642023-06-01 16:51:35 -0700326void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700327 SystemCameraKind systemCameraKind) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000328 // Get the device id and app-visible camera id for the given HAL-visible camera id.
329 auto [deviceId, mappedCameraId] =
330 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
331
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800332 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800333 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700334 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
335 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000336 ALOGV("%s: Skipping torch callback for system-only camera device %s",
337 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700338 continue;
339 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000340
Austin Borgere8e2c422022-05-12 13:45:24 -0700341 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Biswarup Pal37a75182024-01-16 15:53:35 +0000342 mappedCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700343 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
344 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800345 }
346}
347
Mathias Agopian65ab4712010-07-14 17:59:35 -0700348CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800349 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800350 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800351 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800352 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700353}
354
Emilian Peevaee727d2017-05-04 16:35:48 +0100355void CameraService::onNewProviderRegistered() {
356 enumerateProviders();
357}
358
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700359void CameraService::filterAPI1SystemCameraLocked(
360 const std::vector<std::string> &normalDeviceIds) {
361 mNormalDeviceIdsWithoutSystemCamera.clear();
Biswarup Pal37a75182024-01-16 15:53:35 +0000362 for (auto &cameraId : normalDeviceIds) {
363 if (vd_flags::camera_device_awareness()) {
364 CameraMetadata cameraInfo;
365 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000366 cameraId, false, &cameraInfo,
367 hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +0000368 int32_t deviceId = kDefaultDeviceId;
369 if (res != OK) {
370 ALOGW("%s: Not able to get camera characteristics for camera id %s",
371 __FUNCTION__, cameraId.c_str());
372 } else {
373 deviceId = getDeviceId(cameraInfo);
374 }
375 // Cameras associated with non-default device id's (i.e., virtual cameras) can never be
376 // system cameras, so skip for non-default device id's.
377 if (deviceId != kDefaultDeviceId) {
378 continue;
379 }
380 }
381
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700382 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Biswarup Pal37a75182024-01-16 15:53:35 +0000383 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
384 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700385 continue;
386 }
387 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700388 // All system camera ids will necessarily come after public camera
389 // device ids as per the HAL interface contract.
390 break;
391 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000392 mNormalDeviceIdsWithoutSystemCamera.push_back(cameraId);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700393 }
394 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
395 mNormalDeviceIdsWithoutSystemCamera.size());
396}
397
Austin Borgered99f642023-06-01 16:51:35 -0700398status_t CameraService::getSystemCameraKind(const std::string& cameraId,
399 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700400 auto state = getCameraState(cameraId);
401 if (state != nullptr) {
402 *kind = state->getSystemCameraKind();
403 return OK;
404 }
405 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700406 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700407}
408
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800409void CameraService::updateCameraNumAndIds() {
410 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700411 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
412 // Excludes hidden secure cameras
413 mNumberOfCameras =
414 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
415 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800416 mNormalDeviceIds =
417 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700418 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800419}
420
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700421void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700422 // To claim to be S Performance primary cameras, the cameras must be
423 // backward compatible. So performance class primary camera Ids must be API1
424 // compatible.
425 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
426 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
427 int facing = -1;
428 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800429 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000430 getDeviceVersion(cameraId,
431 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
432 /*out*/&portraitRotation, /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700433 if (facing == -1) {
434 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
435 return;
436 }
437
438 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
439 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700440 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
441 if (res == OK) {
442 mPerfClassPrimaryCameraIds.insert(cameraId);
443 } else {
444 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
445 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
446 break;
447 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700448
449 if (facing == hardware::CAMERA_FACING_BACK) {
450 firstRearCameraSeen = true;
451 }
452 if (facing == hardware::CAMERA_FACING_FRONT) {
453 firstFrontCameraSeen = true;
454 }
455 }
456
457 if (firstRearCameraSeen && firstFrontCameraSeen) {
458 break;
459 }
460 }
461}
462
Austin Borgered99f642023-06-01 16:51:35 -0700463void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700464 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100465 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
466 if (res != OK) {
467 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
468 return;
469 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000470 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700471 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
472 if (res != OK) {
473 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
474 return;
475 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000476 std::vector<std::string> physicalCameraIds;
477 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700478 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100479 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700480 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100481 }
482
483 {
484 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700485 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000486 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100487 }
488
Austin Borgered99f642023-06-01 16:51:35 -0700489 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100490 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700491 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800492
Austin Borgered99f642023-06-01 16:51:35 -0700493 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100494 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800495
496 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700497 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100498}
499
Austin Borgered99f642023-06-01 16:51:35 -0700500void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800501 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700502 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100503 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700504 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100505 }
506
507 {
508 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700509 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100510 }
511}
512
Austin Borgered99f642023-06-01 16:51:35 -0700513void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800514 CameraDeviceStatus newHalStatus) {
515 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700516 cameraId.c_str(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700517
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800518 StatusInternal newStatus = mapToInternal(newHalStatus);
519
Austin Borgered99f642023-06-01 16:51:35 -0700520 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800521
522 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700523 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100524 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700525 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100526
527 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700528 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100529
Austin Borgered99f642023-06-01 16:51:35 -0700530 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700531 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700532 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700533 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700534 return;
535 }
536
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800537 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800538
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800539 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800540 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, 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",
Austin Borgered99f642023-06-01 16:51:35 -0700583 __FUNCTION__, id.c_str(), physicalId.c_str(), 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",
Austin Borgered99f642023-06-01 16:51:35 -0700599 __FUNCTION__, physicalId.c_str(), newHalStatus, 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",
Austin Borgered99f642023-06-01 16:51:35 -0700691 __FUNCTION__, cameraId.c_str(), 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
Biswarup Pal37a75182024-01-16 15:53:35 +0000786Status CameraService::getNumberOfCameras(int32_t type, int32_t deviceId, int32_t devicePolicy,
787 int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700788 ATRACE_CALL();
Biswarup Pal37a75182024-01-16 15:53:35 +0000789 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
790 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
791 *numCameras = mVirtualDeviceCameraIdMapper.getNumberOfCameras(deviceId);
792 return Status::ok();
793 }
794
Emilian Peevaee727d2017-05-04 16:35:48 +0100795 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700796 bool hasSystemCameraPermissions =
Austin Borger22c5c852024-03-08 13:31:36 -0800797 hasPermissionsForSystemCamera(std::string(), getCallingPid(),
798 getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700799 switch (type) {
800 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700801 if (hasSystemCameraPermissions) {
802 *numCameras = static_cast<int>(mNormalDeviceIds.size());
803 } else {
804 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
805 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800806 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700807 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700808 if (hasSystemCameraPermissions) {
809 *numCameras = mNumberOfCameras;
810 } else {
811 *numCameras = mNumberOfCamerasWithoutSystemCamera;
812 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800813 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700814 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800815 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700816 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800817 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
818 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700819 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800820 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821}
822
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700823Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
Biswarup Pal37a75182024-01-16 15:53:35 +0000824 int32_t deviceId, int32_t devicePolicy,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700825 /* out */
826 hardware::camera2::impl::CameraMetadataNative* request) {
827 ATRACE_CALL();
828
829 if (!flags::feature_combination_query()) {
830 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
831 "Camera subsystem doesn't support this method!");
832 }
833 if (!mInitialized) {
834 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
835 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
836 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
837 }
838
Biswarup Pal37a75182024-01-16 15:53:35 +0000839 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
malikakash98260df2024-05-10 23:33:57 +0000840 devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000841 if (!cameraIdOptional.has_value()) {
842 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
843 unresolvedCameraId.c_str(), deviceId);
844 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
845 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
846 }
847 std::string cameraId = cameraIdOptional.value();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700848
849 binder::Status res;
850 if (request == nullptr) {
851 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
852 "Camera %s: Error creating default request", cameraId.c_str());
853 return res;
854 }
855 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
856 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
857 cameraId, templateId, &tempId);
858 if (!res.isOk()) {
859 ALOGE("%s: Camera %s: failed to map request Template %d",
860 __FUNCTION__, cameraId.c_str(), templateId);
861 return res;
862 }
863
864 if (shouldRejectSystemCameraConnection(cameraId)) {
865 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
866 "request for system only device %s: ", cameraId.c_str());
867 }
868
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700869 CameraMetadata metadata;
870 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
871 if (err == OK) {
872 request->swap(metadata);
873 } else if (err == BAD_VALUE) {
874 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
875 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
876 cameraId.c_str(), templateId, strerror(-err), err);
877 } else {
878 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
879 "Camera %s: Error creating default request for template %d: %s (%d)",
880 cameraId.c_str(), templateId, strerror(-err), err);
881 }
882 return res;
883}
884
885Status CameraService::isSessionConfigurationWithParametersSupported(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700886 const std::string& unresolvedCameraId, int targetSdkVersion,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700887 const SessionConfiguration& sessionConfiguration,
Biswarup Pal37a75182024-01-16 15:53:35 +0000888 int32_t deviceId, int32_t devicePolicy,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700889 /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700890 ATRACE_CALL();
891
892 if (!flags::feature_combination_query()) {
893 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
894 "Camera subsystem doesn't support this method!");
895 }
896 if (!mInitialized) {
897 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
898 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
899 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
900 }
901
Biswarup Pal37a75182024-01-16 15:53:35 +0000902 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
malikakash98260df2024-05-10 23:33:57 +0000903 devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000904 if (!cameraIdOptional.has_value()) {
905 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
906 unresolvedCameraId.c_str(), deviceId);
907 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
908 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
909 }
910 std::string cameraId = cameraIdOptional.value();
911
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700912 if (supported == nullptr) {
913 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
914 unresolvedCameraId.c_str());
915 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
916 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
917 }
918
919 if (shouldRejectSystemCameraConnection(cameraId)) {
920 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
921 "session configuration with parameters support for system only device %s: ",
922 cameraId.c_str());
923 }
924
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700925 bool overrideForPerfClass = flags::calculate_perf_override_during_session_support() &&
926 SessionConfigurationUtils::targetPerfClassPrimaryCamera(
927 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
928
Shuzhen Wange3e8e732024-05-22 17:48:01 -0700929 auto ret = isSessionConfigurationWithParametersSupportedUnsafe(cameraId,
930 sessionConfiguration, overrideForPerfClass, supported);
931 if (flags::analytics_24q3()) {
932 mCameraServiceProxyWrapper->logFeatureCombinationQuery(cameraId,
933 getCallingUid(), sessionConfiguration, ret);
934 }
935 return ret;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700936}
937
938Status CameraService::isSessionConfigurationWithParametersSupportedUnsafe(
939 const std::string& cameraId, const SessionConfiguration& sessionConfiguration,
940 bool overrideForPerfClass, /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700941 *supported = false;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700942 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(
943 cameraId, sessionConfiguration, overrideForPerfClass,
944 /*checkSessionParams=*/true, supported);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700945 binder::Status res;
946 switch (ret) {
947 case OK:
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700948 // Expected. Do Nothing.
949 return Status::ok();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700950 case INVALID_OPERATION: {
951 std::string msg = fmt::sprintf(
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700952 "Camera %s: Session configuration with parameters supported query not "
953 "supported!",
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700954 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700955 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
956 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
957 *supported = false;
958 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700959 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700960 break;
961 case NAME_NOT_FOUND: {
962 std::string msg = fmt::sprintf("Camera %s: Unknown camera ID.", cameraId.c_str());
963 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
964 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
965 *supported = false;
966 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
967 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700968 break;
969 default: {
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700970 std::string msg = fmt::sprintf(
971 "Unable to retrieve session configuration support for camera "
972 "device %s: Error: %s (%d)",
973 cameraId.c_str(), strerror(-ret), ret);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700974 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700975 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
976 *supported = false;
977 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700978 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700979 break;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700980 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700981}
982
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800983Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000984 int targetSdkVersion, int rotationOverride,
Biswarup Pal37a75182024-01-16 15:53:35 +0000985 const SessionConfiguration& sessionConfiguration, int32_t deviceId, int32_t devicePolicy,
986 /*out*/ CameraMetadata* outMetadata) {
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800987 ATRACE_CALL();
988
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800989 if (outMetadata == nullptr) {
990 std::string msg =
991 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
992 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
993 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
994 }
995
Avichal Rakesh4baf7262024-03-20 19:16:04 -0700996 if (!mInitialized) {
997 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
998 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
999 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
1000 }
1001
Biswarup Pal37a75182024-01-16 15:53:35 +00001002 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
malikakash98260df2024-05-10 23:33:57 +00001003 devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001004 if (!cameraIdOptional.has_value()) {
1005 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001006 unresolvedCameraId.c_str(), deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001007 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1008 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1009 }
1010 std::string cameraId = cameraIdOptional.value();
1011
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001012 if (shouldRejectSystemCameraConnection(cameraId)) {
1013 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1014 "Unable to retrieve camera"
1015 "characteristics for system only device %s: ",
1016 cameraId.c_str());
1017 }
1018
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001019 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1020 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001021 if (flags::check_session_support_before_session_char()) {
1022 bool sessionConfigSupported;
1023 Status res = isSessionConfigurationWithParametersSupportedUnsafe(
1024 cameraId, sessionConfiguration, overrideForPerfClass, &sessionConfigSupported);
1025 if (!res.isOk()) {
1026 // isSessionConfigurationWithParametersSupportedUnsafe should log what went wrong and
1027 // report the correct Status to send to the client. Simply forward the error to
1028 // the client.
1029 outMetadata->clear();
1030 return res;
1031 }
1032 if (!sessionConfigSupported) {
1033 std::string msg = fmt::sprintf(
1034 "Session configuration not supported for camera device %s.", cameraId.c_str());
1035 outMetadata->clear();
1036 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1037 }
1038 }
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001039
1040 status_t ret = mCameraProviderManager->getSessionCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001041 cameraId, sessionConfiguration, overrideForPerfClass, rotationOverride, outMetadata);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001042
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001043 switch (ret) {
1044 case OK:
1045 // Expected, no handling needed.
1046 break;
1047 case INVALID_OPERATION: {
1048 std::string msg = fmt::sprintf(
1049 "Camera %s: Session characteristics query not supported!",
1050 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001051 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001052 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1053 outMetadata->clear();
1054 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1055 }
1056 break;
1057 case NAME_NOT_FOUND: {
1058 std::string msg = fmt::sprintf(
1059 "Camera %s: Unknown camera ID.",
1060 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001061 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001062 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1063 outMetadata->clear();
1064 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001065 }
1066 break;
1067 default: {
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001068 std::string msg = fmt::sprintf(
1069 "Unable to retrieve session characteristics for camera device %s: "
1070 "Error: %s (%d)",
1071 cameraId.c_str(), strerror(-ret), ret);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001072 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001073 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1074 outMetadata->clear();
1075 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001076 }
1077 }
1078
Shuzhen Wange3e8e732024-05-22 17:48:01 -07001079 Status res = filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
1080 if (flags::analytics_24q3()) {
1081 mCameraServiceProxyWrapper->logSessionCharacteristicsQuery(cameraId,
1082 getCallingUid(), sessionConfiguration, res);
1083 }
1084 return res;
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001085}
1086
1087Status CameraService::filterSensitiveMetadataIfNeeded(
1088 const std::string& cameraId, CameraMetadata* metadata) {
1089 int callingPid = getCallingPid();
1090 int callingUid = getCallingUid();
1091
1092 if (callingPid == getpid()) {
1093 // Caller is cameraserver; no need to remove keys
1094 return Status::ok();
1095 }
1096
1097 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1098 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1099 ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
1100 metadata->clear();
1101 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1102 "Unable to retrieve camera kind for device %s", cameraId.c_str());
1103 }
1104 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
1105 // Attempting to query system only camera without system camera permission would have
1106 // failed the shouldRejectSystemCameraConnection in the caller. So if we get here
1107 // for a system only camera, then the caller has the required permission.
1108 // No need to remove keys
1109 return Status::ok();
1110 }
1111
1112 std::vector<int32_t> tagsRemoved;
Biswarup Pale506e732024-03-27 13:46:20 +00001113 // Get the device id that owns this camera.
1114 auto [cameraOwnerDeviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1115 cameraId);
1116 bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid,
1117 cameraOwnerDeviceId);
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001118 if (hasCameraPermission) {
1119 // Caller has camera permission; no need to remove keys
1120 return Status::ok();
1121 }
1122
1123 status_t ret = metadata->removePermissionEntries(
1124 mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1125 if (ret != OK) {
1126 metadata->clear();
1127 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1128 "Failed to remove camera characteristics needing camera permission "
1129 "for device %s:%s (%d)",
1130 cameraId.c_str(), strerror(-ret), ret);
1131 }
1132
1133 if (!tagsRemoved.empty()) {
1134 ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1135 tagsRemoved.data(), tagsRemoved.size());
1136 if (ret != OK) {
1137 metadata->clear();
1138 return STATUS_ERROR_FMT(
1139 ERROR_INVALID_OPERATION,
1140 "Failed to insert camera keys needing permission for device %s: %s (%d)",
1141 cameraId.c_str(), strerror(-ret), ret);
1142 }
1143 }
1144 return Status::ok();
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001145}
1146
malikakash22af94c2023-12-04 18:13:14 +00001147Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001148 const std::string& cameraId,
1149 const CameraMetadata& sessionParams) {
1150 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001151 const int pid = getCallingPid();
1152 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001153 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1154 __FUNCTION__, pid, uid);
1155 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1156 "Permission Denial: no permission to inject session params");
1157 }
1158
Biswarup Pal37a75182024-01-16 15:53:35 +00001159 // Do not allow session params injection for a virtual camera.
1160 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1161 if (deviceId != kDefaultDeviceId) {
1162 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1163 "Cannot inject session params for a virtual camera");
1164 }
1165
malikakash22af94c2023-12-04 18:13:14 +00001166 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1167 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1168
1169 auto clientDescriptor = mActiveClientManager.get(cameraId);
1170 if (clientDescriptor == nullptr) {
1171 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1172 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1173 "No active client for camera id %s", cameraId.c_str());
1174 }
1175
1176 sp<BasicClient> clientSp = clientDescriptor->getValue();
1177 status_t res = clientSp->injectSessionParams(sessionParams);
1178
1179 if (res != OK) {
1180 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1181 "Error injecting session params into camera \"%s\": %s (%d)",
1182 cameraId.c_str(), strerror(-res), res);
1183 }
1184 return Status::ok();
1185}
1186
Biswarup Pal37a75182024-01-16 15:53:35 +00001187std::optional<std::string> CameraService::resolveCameraId(
1188 const std::string& inputCameraId,
1189 int32_t deviceId,
malikakash98260df2024-05-10 23:33:57 +00001190 int32_t devicePolicy) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001191 if ((deviceId == kDefaultDeviceId)
1192 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1193 auto [storedDeviceId, _] =
1194 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1195 if (storedDeviceId != kDefaultDeviceId) {
1196 // Trying to access a virtual camera from default-policy device context, we should fail.
1197 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1198 inputCameraId.c_str(), deviceId);
1199 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1200 return std::nullopt;
1201 }
malikakash98260df2024-05-10 23:33:57 +00001202 return inputCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001203 }
1204
1205 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1206}
1207
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001208Status CameraService::getCameraInfo(int cameraId, int rotationOverride, int32_t deviceId,
Biswarup Pal37a75182024-01-16 15:53:35 +00001209 int32_t devicePolicy, CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001210 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001211 Mutex::Autolock l(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001212 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId, deviceId, devicePolicy);
1213 if (cameraIdStr.empty()) {
1214 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
1215 cameraId, deviceId);
1216 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1217 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1218 }
malikakashedb38962023-09-06 00:03:35 +00001219
Austin Borgered99f642023-06-01 16:51:35 -07001220 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001221 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1222 "characteristics for system only device %s: ", cameraIdStr.c_str());
1223 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001224
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001225 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001226 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001227 return STATUS_ERROR(ERROR_DISCONNECTED,
1228 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001229 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001230 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001231 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001232 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1233 if (hasSystemCameraPermissions) {
1234 cameraIdBound = mNumberOfCameras;
1235 }
1236 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001237 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1238 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001239 }
1240
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001241 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001242 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001243 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001244 cameraIdStr, rotationOverride, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001245 if (err != OK) {
1246 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1247 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1248 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001249 logServiceError(std::string("Error retrieving camera info from device ")
1250 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001251 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001252
Ruben Brunkcc776712015-02-17 20:18:47 -08001253 return ret;
1254}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001255
Biswarup Pal37a75182024-01-16 15:53:35 +00001256std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1257 int32_t deviceId, int32_t devicePolicy) {
1258 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1259 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1260 std::optional<std::string> cameraIdOptional =
1261 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1262 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1263 }
1264
1265 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001266 auto callingPid = getCallingPid();
1267 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001268 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1269 callingPid, callingUid, /* checkCameraPermissions= */ false);
1270 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001271 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001272 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001273 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1274 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1275 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001276 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001277 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001278
malikakash98260df2024-05-10 23:33:57 +00001279 return (*cameraIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001280}
1281
Biswarup Pal37a75182024-01-16 15:53:35 +00001282std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1283 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001284 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001285 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001286}
1287
Austin Borgered99f642023-06-01 16:51:35 -07001288Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001289 int targetSdkVersion, int rotationOverride, int32_t deviceId, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +00001290 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001291 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001292
Zhijun He2b59be82013-09-25 10:14:30 -07001293 if (!cameraInfo) {
1294 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001295 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001296 }
1297
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001298 if (!mInitialized) {
1299 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001300 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001301 return STATUS_ERROR(ERROR_DISCONNECTED,
1302 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001303 }
1304
Biswarup Pal37a75182024-01-16 15:53:35 +00001305 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
malikakash98260df2024-05-10 23:33:57 +00001306 devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001307 if (!cameraIdOptional.has_value()) {
1308 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1309 unresolvedCameraId.c_str(), deviceId);
1310 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1311 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1312 }
1313 std::string cameraId = cameraIdOptional.value();
1314
Austin Borgered99f642023-06-01 16:51:35 -07001315 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001316 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001317 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001318 }
1319
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001320 bool overrideForPerfClass =
1321 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001322 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001323 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001324 cameraId, overrideForPerfClass, cameraInfo, rotationOverride);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001325 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001326 if (res == NAME_NOT_FOUND) {
1327 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001328 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001329 strerror(-res), res);
1330 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001331 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1332 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001333 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001334 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001335 strerror(-res), res);
1336 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001337 }
Emilian Peeve20c6372018-08-14 18:45:53 +01001338
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001339 return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -07001340}
1341
Biswarup Pal37a75182024-01-16 15:53:35 +00001342Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId, int32_t deviceId,
1343 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001344 ATRACE_CALL();
1345 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001346
Biswarup Pal37a75182024-01-16 15:53:35 +00001347 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
malikakash98260df2024-05-10 23:33:57 +00001348 devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001349 if (!cameraIdOptional.has_value()) {
1350 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1351 unresolvedCameraId.c_str(), deviceId);
1352 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1353 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1354 }
1355 std::string cameraId = cameraIdOptional.value();
1356
Rucha Katakwar38284522021-11-10 11:25:21 -08001357 if (!mInitialized) {
1358 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1359 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1360 }
1361
Biswarup Pal37a75182024-01-16 15:53:35 +00001362 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001363 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1364 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1365 }
1366
Austin Borgered99f642023-06-01 16:51:35 -07001367 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001368 if (res != OK) {
1369 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001370 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001371 strerror(-res), res);
1372 }
1373 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1374 return Status::ok();
1375}
1376
Austin Borgered99f642023-06-01 16:51:35 -07001377std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001378 time_t now = time(nullptr);
1379 char formattedTime[64];
1380 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001381 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001382}
1383
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001384Status CameraService::getCameraVendorTagDescriptor(
1385 /*out*/
1386 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001387 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001388 if (!mInitialized) {
1389 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001390 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001391 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001392 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1393 if (globalDescriptor != nullptr) {
1394 *desc = *(globalDescriptor.get());
1395 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001396 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001397}
1398
Emilian Peev71c73a22017-03-21 16:35:51 +00001399Status CameraService::getCameraVendorTagCache(
1400 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1401 ATRACE_CALL();
1402 if (!mInitialized) {
1403 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1404 return STATUS_ERROR(ERROR_DISCONNECTED,
1405 "Camera subsystem not available");
1406 }
1407 sp<VendorTagDescriptorCache> globalCache =
1408 VendorTagDescriptorCache::getGlobalVendorTagCache();
1409 if (globalCache != nullptr) {
1410 *cache = *(globalCache.get());
1411 }
1412 return Status::ok();
1413}
1414
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001415void CameraService::clearCachedVariables() {
1416 BasicClient::BasicClient::sCameraService = nullptr;
1417}
1418
Austin Borgered99f642023-06-01 16:51:35 -07001419std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001420 int rotationOverride, int* portraitRotation, int* facing,
1421 int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001422 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001423
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001424 int deviceVersion = 0;
1425
Emilian Peevf53f66e2017-04-11 14:29:43 +01001426 status_t res;
1427 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001428 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001429 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001430 if (res != OK || transport == IPCTransport::INVALID) {
1431 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001432 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001433 return std::make_pair(-1, IPCTransport::INVALID) ;
1434 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001435 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001436
Emilian Peevf53f66e2017-04-11 14:29:43 +01001437 hardware::CameraInfo info;
1438 if (facing) {
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001439 res = mCameraProviderManager->getCameraInfo(cameraId, rotationOverride,
Austin Borger18b30a72022-10-27 12:20:29 -07001440 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001441 if (res != OK) {
1442 return std::make_pair(-1, IPCTransport::INVALID);
1443 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001444 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001445 if (orientation) {
1446 *orientation = info.orientation;
1447 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001448 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001449
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001450 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001451}
1452
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001453Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001454 switch(err) {
1455 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001456 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001457 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001458 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1459 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001460 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001461 return STATUS_ERROR(ERROR_DISCONNECTED,
1462 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001463 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001464 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1465 "Camera HAL encountered error %d: %s",
1466 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001467 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001468}
1469
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001470Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001471 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1472 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001473 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001474 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001475 apiLevel effectiveApiLevel, bool overrideForPerfClass, int rotationOverride,
malikakash73125c62023-07-21 22:44:34 +00001476 bool forceSlowJpegMode, const std::string& originalCameraId,
1477 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001478 // For HIDL devices
1479 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1480 // Create CameraClient based on device version reported by the HAL.
1481 int deviceVersion = deviceVersionAndTransport.first;
1482 switch(deviceVersion) {
1483 case CAMERA_DEVICE_API_VERSION_1_0:
1484 ALOGE("Camera using old HAL version: %d", deviceVersion);
1485 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1486 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001487 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001488 break;
1489 case CAMERA_DEVICE_API_VERSION_3_0:
1490 case CAMERA_DEVICE_API_VERSION_3_1:
1491 case CAMERA_DEVICE_API_VERSION_3_2:
1492 case CAMERA_DEVICE_API_VERSION_3_3:
1493 case CAMERA_DEVICE_API_VERSION_3_4:
1494 case CAMERA_DEVICE_API_VERSION_3_5:
1495 case CAMERA_DEVICE_API_VERSION_3_6:
1496 case CAMERA_DEVICE_API_VERSION_3_7:
1497 break;
1498 default:
1499 // Should not be reachable
1500 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1501 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1502 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001503 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001504 }
1505 }
1506 if (effectiveApiLevel == API_1) { // Camera1 API route
1507 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001508 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001509 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001510 api1CameraId, facing, sensorOrientation,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001511 clientPid, clientUid, servicePid, overrideForPerfClass, rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00001512 forceSlowJpegMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001513 ALOGI("%s: Camera1 API (legacy), rotationOverride %d, forceSlowJpegMode %d",
1514 __FUNCTION__, rotationOverride, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001515 } else { // Camera2 API route
1516 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1517 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001518 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001519 cameraService->mCameraServiceProxyWrapper,
1520 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001521 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001522 overrideForPerfClass, rotationOverride, originalCameraId);
1523 ALOGI("%s: Camera2 API, rotationOverride %d", __FUNCTION__, rotationOverride);
Ruben Brunkcc776712015-02-17 20:18:47 -08001524 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001525 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001526}
1527
Austin Borgered99f642023-06-01 16:51:35 -07001528std::string CameraService::toString(std::set<userid_t> intSet) {
1529 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001530 bool first = true;
1531 for (userid_t i : intSet) {
1532 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001533 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001534 first = false;
1535 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001536 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001537 }
1538 }
Austin Borgered99f642023-06-01 16:51:35 -07001539 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001540}
1541
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001542int32_t CameraService::mapToInterface(TorchModeStatus status) {
1543 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1544 switch (status) {
1545 case TorchModeStatus::NOT_AVAILABLE:
1546 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1547 break;
1548 case TorchModeStatus::AVAILABLE_OFF:
1549 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1550 break;
1551 case TorchModeStatus::AVAILABLE_ON:
1552 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1553 break;
1554 default:
1555 ALOGW("Unknown new flash status: %d", status);
1556 }
1557 return serviceStatus;
1558}
1559
1560CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1561 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1562 switch (status) {
1563 case CameraDeviceStatus::NOT_PRESENT:
1564 serviceStatus = StatusInternal::NOT_PRESENT;
1565 break;
1566 case CameraDeviceStatus::PRESENT:
1567 serviceStatus = StatusInternal::PRESENT;
1568 break;
1569 case CameraDeviceStatus::ENUMERATING:
1570 serviceStatus = StatusInternal::ENUMERATING;
1571 break;
1572 default:
1573 ALOGW("Unknown new HAL device status: %d", status);
1574 }
1575 return serviceStatus;
1576}
1577
1578int32_t CameraService::mapToInterface(StatusInternal status) {
1579 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1580 switch (status) {
1581 case StatusInternal::NOT_PRESENT:
1582 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1583 break;
1584 case StatusInternal::PRESENT:
1585 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1586 break;
1587 case StatusInternal::ENUMERATING:
1588 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1589 break;
1590 case StatusInternal::NOT_AVAILABLE:
1591 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1592 break;
1593 case StatusInternal::UNKNOWN:
1594 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1595 break;
1596 default:
1597 ALOGW("Unknown new internal device status: %d", status);
1598 }
1599 return serviceStatus;
1600}
1601
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001602Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001603 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001604
Austin Borgered99f642023-06-01 16:51:35 -07001605 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001606 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001607 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001608 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001609 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1610 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001611 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001612 /*targetSdkVersion*/ __ANDROID_API_FUTURE__,
1613 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_OVERRIDE_TO_PORTRAIT,
Austin Borgered99f642023-06-01 16:51:35 -07001614 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001615 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001616 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001617 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001618 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001619}
1620
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001621Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001622 /*out*/
1623 CameraParameters* parameters) {
1624
1625 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1626
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001627 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001628
1629 if (parameters == NULL) {
1630 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001631 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001632 }
1633
malikakash98260df2024-05-10 23:33:57 +00001634 std::string cameraIdStr = std::to_string(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001635
1636 // Check if we already have parameters
1637 {
1638 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001639 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001640 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001641 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001642 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001643 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001644 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001645 }
1646 CameraParameters p = cameraState->getShimParams();
1647 if (!p.isEmpty()) {
1648 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001649 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001650 }
1651 }
1652
Austin Borger22c5c852024-03-08 13:31:36 -08001653 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001654 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001655 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001656 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001657 // Error already logged by callee
1658 return ret;
1659 }
1660
1661 // Check for parameters again
1662 {
1663 // Scope for service lock
1664 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001665 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001666 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001667 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001668 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001669 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001670 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001671 CameraParameters p = cameraState->getShimParams();
1672 if (!p.isEmpty()) {
1673 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001674 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001675 }
1676 }
1677
Ruben Brunkcc776712015-02-17 20:18:47 -08001678 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1679 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001680 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001681}
1682
Austin Borgered99f642023-06-01 16:51:35 -07001683Status CameraService::validateConnectLocked(const std::string& cameraId,
1684 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001685 /*out*/int& originalClientPid) 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);
1691 UNUSED(originalClientPid);
1692#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001693 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1694 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001695 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001696 return allowed;
1697 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001698#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001699
Austin Borger22c5c852024-03-08 13:31:36 -08001700 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001701
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001702 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001703 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1704 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001705 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001706 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001707 }
1708
Ruben Brunkcc776712015-02-17 20:18:47 -08001709 if (getCameraState(cameraId) == nullptr) {
1710 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001711 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001712 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001713 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001714 }
1715
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001716 status_t err = checkIfDeviceIsUsable(cameraId);
1717 if (err != NO_ERROR) {
1718 switch(err) {
1719 case -ENODEV:
1720 case -EBUSY:
1721 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001722 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001723 default:
1724 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001725 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001726 }
1727 }
1728 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001729}
1730
Austin Borgered99f642023-06-01 16:51:35 -07001731Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1732 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001733 /*out*/int& originalClientPid) const {
Austin Borger22c5c852024-03-08 13:31:36 -08001734 int callingPid = getCallingPid();
1735 int callingUid = getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001736
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001737 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001738 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001739 clientUid = callingUid;
1740 } else if (!isTrustedCallingUid(callingUid)) {
1741 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1742 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001743 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1744 "Untrusted caller (calling PID %d, UID %d) trying to "
1745 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001746 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001747 clientName.c_str(), clientPid, clientUid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001748 }
1749
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001750 // Check if we can trust clientPid
1751 if (clientPid == USE_CALLING_PID) {
1752 clientPid = callingPid;
1753 } else if (!isTrustedCallingUid(callingUid)) {
1754 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1755 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001756 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1757 "Untrusted caller (calling PID %d, UID %d) trying to "
1758 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001759 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001760 clientName.c_str(), clientPid, clientUid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001761 }
1762
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001763 if (shouldRejectSystemCameraConnection(cameraId)) {
1764 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1765 cameraId.c_str());
1766 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001767 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001768 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001769 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1770 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001771 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001772 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001773 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001774 }
1775
Biswarup Pale506e732024-03-27 13:46:20 +00001776 // Get the device id that owns this camera.
1777 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1778
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001779 // If it's not calling from cameraserver, check the permission if the
1780 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1781 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001782 bool checkPermissionForCamera =
Biswarup Pale506e732024-03-27 13:46:20 +00001783 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName, deviceId);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001784 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001785 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001786 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001787 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1788 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001789 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001790 }
1791
Svet Ganova453d0d2018-01-11 15:37:58 -08001792 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001793 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001794 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001795 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1796 clientPid, clientUid);
1797 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001798 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1799 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001800 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001801 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001802 }
1803
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001804 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1805 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1806 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1807 if ((!isAutomotivePrivilegedClient(callingUid) ||
1808 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1809 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001810 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1811 return STATUS_ERROR_FMT(ERROR_DISABLED,
1812 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001813 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001814 }
1815
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001816 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1817 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001818 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001819 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001820
Ruben Brunk6267b532015-04-30 17:44:07 -07001821 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001822
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001823 // For non-system clients : Only allow clients who are being used by the current foreground
1824 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08001825 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001826 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001827 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1828 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001829 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001830 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1831 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001832 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001833 }
1834
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001835 if (flags::camera_hsum_permission()) {
1836 // If the System User tries to access the camera when the device is running in
1837 // headless system user mode, ensure that client has the required permission
1838 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07001839 if (isHeadlessSystemUserMode()
1840 && (clientUserId == USER_SYSTEM)
1841 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001842 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
1843 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1844 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1845 User without camera headless system user permission",
Austin Borger249e6592024-03-10 22:28:11 -07001846 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001847 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001848 }
1849
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001850 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001851}
1852
Austin Borgered99f642023-06-01 16:51:35 -07001853status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001854 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001855 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001856 if (cameraState == nullptr) {
1857 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001858 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001859 return -ENODEV;
1860 }
1861
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001862 StatusInternal currentStatus = cameraState->getStatus();
1863 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001864 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001865 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001866 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001867 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001868 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001869 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001870 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001871 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001872
Ruben Brunkcc776712015-02-17 20:18:47 -08001873 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001874}
1875
Ruben Brunkcc776712015-02-17 20:18:47 -08001876void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001877 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001878
Ruben Brunkcc776712015-02-17 20:18:47 -08001879 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001880 auto clientDescriptor =
1881 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001882 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001883 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1884
1885 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001886 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001887
1888 if (evicted.size() > 0) {
1889 // This should never happen - clients should already have been removed in disconnect
1890 for (auto& i : evicted) {
1891 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001892 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001893 }
1894
1895 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1896 __FUNCTION__);
1897 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001898
1899 // And register a death notification for the client callback. Do
1900 // this last to avoid Binder policy where a nested Binder
1901 // transaction might be pre-empted to service the client death
1902 // notification if the client process dies before linkToDeath is
1903 // invoked.
1904 sp<IBinder> remoteCallback = client->getRemote();
1905 if (remoteCallback != nullptr) {
1906 remoteCallback->linkToDeath(this);
1907 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001908}
1909
Austin Borgered99f642023-06-01 16:51:35 -07001910status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1911 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1912 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001913 /*out*/
1914 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001915 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001916 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001917 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001918 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001919 DescriptorPtr clientDescriptor;
1920 {
1921 if (effectiveApiLevel == API_1) {
1922 // If we are using API1, any existing client for this camera ID with the same remote
1923 // should be returned rather than evicted to allow MediaRecorder to work properly.
1924
1925 auto current = mActiveClientManager.get(cameraId);
1926 if (current != nullptr) {
1927 auto clientSp = current->getValue();
1928 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001929 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001930 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001931 " API level, evicting prior client...");
1932 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001933 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001934 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001935 *client = clientSp;
1936 return NO_ERROR;
1937 }
1938 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001939 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001940 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001941
Ruben Brunkcc776712015-02-17 20:18:47 -08001942 // Get state for the given cameraId
1943 auto state = getCameraState(cameraId);
1944 if (state == nullptr) {
1945 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001946 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001947 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001948 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001949 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001950
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001951 sp<IServiceManager> sm = defaultServiceManager();
1952 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08001953 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001954 // If processinfo service is not available and the client is automotive privileged
1955 // client used for safety critical uses cases such as rear-view and surround-view which
1956 // needs to be available before android boot completes, then use the hardcoded values
1957 // for the process state and priority score. As this scenario is before android system
1958 // services are up and client is native client, hence using NATIVE_ADJ as the priority
1959 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
1960 // visible on the top.
1961 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1962 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1963 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
1964 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
1965 } else {
1966 // Get current active client PIDs
1967 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1968 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001969
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001970 std::vector<int> priorityScores(ownerPids.size());
1971 std::vector<int> states(ownerPids.size());
1972
1973 // Get priority scores of all active PIDs
1974 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
1975 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
1976 if (err != OK) {
1977 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
1978 return err;
1979 }
1980
1981 // Update all active clients' priorities
1982 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
1983 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1984 pidToPriorityMap.emplace(ownerPids[i],
1985 resource_policy::ClientPriority(priorityScores[i], states[i],
1986 /* isVendorClient won't get copied over*/ false,
1987 /* oomScoreOffset won't get copied over*/ 0));
1988 }
1989 mActiveClientManager.updatePriorities(pidToPriorityMap);
1990
1991 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1992 int32_t actualState = states[states.size() - 1];
1993
1994 // Make descriptor for incoming client. We store the oomScoreOffset
1995 // since we might need it later on new handleEvictionsLocked and
1996 // ProcessInfoService would not take that into account.
1997 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1998 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1999 state->getConflicting(), actualScore, clientPid, actualState,
2000 oomScoreOffset, systemNativeClient);
2001 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002002
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002003 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
2004
Ruben Brunkcc776712015-02-17 20:18:47 -08002005 // Find clients that would be evicted
2006 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
2007
2008 // If the incoming client was 'evicted,' higher priority clients have the camera in the
2009 // background, so we cannot do evictions
2010 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2011 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2012 " priority).", clientPid);
2013
2014 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002015 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002016 auto incompatibleClients =
2017 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2018
Austin Borgered99f642023-06-01 16:51:35 -07002019 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2020 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2021 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002022 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002023
2024 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002025 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002026 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002027 i->getKey().c_str(),
2028 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002029 i->getOwnerId(), i->getPriority().getScore(),
2030 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002031 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002032 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2033 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002034 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002035 }
2036
2037 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002038 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002039 mEventLog.add(msg);
2040
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002041 auto current = mActiveClientManager.get(cameraId);
2042 if (current != nullptr) {
2043 return -EBUSY; // CAMERA_IN_USE
2044 } else {
2045 return -EUSERS; // MAX_CAMERAS_IN_USE
2046 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002047 }
2048
2049 for (auto& i : evicted) {
2050 sp<BasicClient> clientSp = i->getValue();
2051 if (clientSp.get() == nullptr) {
2052 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2053
2054 // TODO: Remove this
2055 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2056 __FUNCTION__);
2057 mActiveClientManager.remove(i);
2058 continue;
2059 }
2060
2061 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002062 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002063 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002064
Ruben Brunkcc776712015-02-17 20:18:47 -08002065 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002066 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002067 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2068 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002069 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002070 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002071 i->getPriority().getState(), cameraId.c_str(),
2072 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002073 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002074
2075 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002076 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002077 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002078 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002079 }
2080
Ruben Brunkcc776712015-02-17 20:18:47 -08002081 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2082 // other clients from connecting in mServiceLockWrapper if held
2083 mServiceLock.unlock();
2084
2085 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002086 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002087
2088 // Destroy evicted clients
2089 for (auto& i : evictedClients) {
2090 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002091 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002092 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002093
Austin Borger22c5c852024-03-08 13:31:36 -08002094 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002095
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002096 for (const auto& i : evictedClients) {
2097 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002098 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002099 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2100 if (ret == TIMED_OUT) {
2101 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002102 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2103 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002104 return -EBUSY;
2105 }
2106 if (ret != NO_ERROR) {
2107 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002108 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2109 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002110 return ret;
2111 }
2112 }
2113
2114 evictedClients.clear();
2115
Ruben Brunkcc776712015-02-17 20:18:47 -08002116 // Once clients have been disconnected, relock
2117 mServiceLock.lock();
2118
2119 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2120 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2121 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002122 }
2123
Ruben Brunkcc776712015-02-17 20:18:47 -08002124 *partial = clientDescriptor;
2125 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002126}
2127
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002128Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002129 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002130 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07002131 const std::string& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002132 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08002133 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002134 int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002135 int rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00002136 bool forceSlowJpegMode,
Biswarup Pal37a75182024-01-16 15:53:35 +00002137 int32_t deviceId,
2138 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002139 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002140 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002141 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002142 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002143
Biswarup Pal37a75182024-01-16 15:53:35 +00002144 std::string cameraIdStr = cameraIdIntToStr(api1CameraId, deviceId, devicePolicy);
2145 if (cameraIdStr.empty()) {
2146 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
2147 api1CameraId, deviceId);
2148 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2149 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2150 }
malikakashedb38962023-09-06 00:03:35 +00002151
Ruben Brunkcc776712015-02-17 20:18:47 -08002152 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002153 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
2154 clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002155 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002156 rotationOverride, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002157
Biswarup Pal37a75182024-01-16 15:53:35 +00002158 if (!ret.isOk()) {
2159 logRejected(cameraIdStr, getCallingPid(), clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002160 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002161 }
2162
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002163 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002164
2165 const sp<IServiceManager> sm(defaultServiceManager());
2166 const auto& mActivityManager = getActivityManager();
2167 if (mActivityManager) {
2168 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002169 getCallingUid(),
2170 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002171 }
2172
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002173 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002174}
2175
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002176bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2177 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002178 // If the client is not a vendor client, don't add listener if
2179 // a) the camera is a publicly hidden secure camera OR
2180 // b) the camera is a system only camera and the client doesn't
2181 // have android.permission.SYSTEM_CAMERA permissions.
2182 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2183 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002184 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002185 return true;
2186 }
2187 return false;
2188}
2189
Austin Borgered99f642023-06-01 16:51:35 -07002190bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002191 // Rules for rejection:
2192 // 1) If cameraserver tries to access this camera device, accept the
2193 // connection.
2194 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002195 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002196 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2197 // and the serving thread is a non hwbinder thread, the client must have
2198 // android.permission.SYSTEM_CAMERA permissions to connect.
2199
Austin Borger22c5c852024-03-08 13:31:36 -08002200 int cPid = getCallingPid();
2201 int cUid = getCallingUid();
2202 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002203 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2204 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002205 // This isn't a known camera ID, so it's not a system camera
2206 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2207 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002208 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002209
2210 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002211 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002212 return false;
2213 }
2214 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002215 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002216 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2217 return true;
2218 }
2219 // (3) Here we only check for permissions if it is a system only camera device. This is since
2220 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2221 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2222 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002223 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002224 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002225 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2226 cameraId.c_str());
2227 return true;
2228 }
2229
2230 return false;
2231}
2232
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002233Status CameraService::connectDevice(
2234 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002235 const std::string& unresolvedCameraId,
2236 const std::string& clientPackageName,
2237 const std::optional<std::string>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002238 int clientUid, int oomScoreOffset, int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002239 int rotationOverride, int32_t deviceId, int32_t devicePolicy,
Ruben Brunkcc776712015-02-17 20:18:47 -08002240 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002241 sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002242 ATRACE_CALL();
Emilian Peev31bd2422024-04-23 22:24:09 +00002243 RunThreadWithRealtimePriority priorityBump;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002244 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002245 sp<CameraDeviceClient> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002246 std::string clientPackageNameAdj = clientPackageName;
Austin Borger22c5c852024-03-08 13:31:36 -08002247 int callingPid = getCallingPid();
2248 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002249 bool systemNativeClient = false;
Austin Borger22c5c852024-03-08 13:31:36 -08002250 if (callerHasSystemUid() && (clientPackageNameAdj.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002251 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borgered99f642023-06-01 16:51:35 -07002252 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002253 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002254 }
Austin Borger249e6592024-03-10 22:28:11 -07002255
Biswarup Pal37a75182024-01-16 15:53:35 +00002256 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
malikakash98260df2024-05-10 23:33:57 +00002257 devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002258 if (!cameraIdOptional.has_value()) {
2259 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
2260 unresolvedCameraId.c_str(), deviceId);
2261 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2262 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2263 }
2264 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002265
2266 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002267 std::string msg =
2268 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
2269 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
2270 cameraId.c_str());
2271 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2272 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002273 }
2274
Austin Borger9bfa0a72022-08-03 17:50:40 -07002275 userid_t clientUserId = multiuser_get_user_id(clientUid);
Austin Borger9bfa0a72022-08-03 17:50:40 -07002276 if (clientUid == USE_CALLING_UID) {
2277 clientUserId = multiuser_get_user_id(callingUid);
2278 }
2279
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002280 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2281 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002282 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2283 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002284 std::string msg = "Camera disabled by device policy";
2285 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2286 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002287 }
2288
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002289 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002290 if (oomScoreOffset > 0
2291 && !hasPermissionsForSystemCamera(cameraId, callingPid,
Austin Borger249e6592024-03-10 22:28:11 -07002292 callingUid)
2293 && !isTrustedCallingUid(callingUid)) {
Austin Borgered99f642023-06-01 16:51:35 -07002294 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002295 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07002296 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2297 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2298 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002299 }
2300
Austin Borgered99f642023-06-01 16:51:35 -07002301 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
2302 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002303 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002304 targetSdkVersion, rotationOverride, /*forceSlowJpegMode*/false, unresolvedCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002305 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002306
Biswarup Pal37a75182024-01-16 15:53:35 +00002307 if (!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002308 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002309 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002310 }
2311
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002312 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002313 Mutex::Autolock lock(mServiceLock);
2314
2315 // Clear the previous cached logs and reposition the
2316 // file offset to beginning of the file to log new data.
2317 // If either truncate or lseek fails, close the previous file and create a new one.
2318 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2319 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2320 // Close the previous memfd.
2321 close(mMemFd);
2322 // If failure to wipe the data, then create a new file and
2323 // assign the new value to mMemFd.
2324 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2325 if (mMemFd == -1) {
2326 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2327 }
2328 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002329 const sp<IServiceManager> sm(defaultServiceManager());
2330 const auto& mActivityManager = getActivityManager();
2331 if (mActivityManager) {
2332 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002333 callingUid,
2334 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002335 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002336 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002337}
2338
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002339bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2340 int callingPid, int callingUid) {
2341 if (!isAutomotiveDevice()) {
2342 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2343 }
2344
2345 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2346 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2347 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2348 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2349 "using camera %s", callingUid, cam_id.c_str());
2350 return false;
2351 }
2352
2353 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2354 return true;
2355 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2356 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002357 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2358 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002359 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2360 return false;
2361 } else {
2362 return true;
2363 }
2364 }
2365 return false;
2366}
2367
Austin Borgered99f642023-06-01 16:51:35 -07002368std::string CameraService::getPackageNameFromUid(int clientUid) {
2369 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002370
Avichal Rakesh5788fec2024-03-15 14:39:20 -07002371 sp<IPermissionController> permCtrl;
2372 if (flags::cache_permission_services()) {
2373 permCtrl = getPermissionController();
2374 } else {
2375 sp<IServiceManager> sm = defaultServiceManager();
2376#pragma clang diagnostic push
2377#pragma clang diagnostic ignored "-Wdeprecated-declarations"
2378 // Using deprecated function to preserve functionality until the
2379 // cache_permission_services flag is removed.
2380 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
2381#pragma clang diagnostic pop
2382 if (binder == 0) {
2383 ALOGE("Cannot get permission service");
2384 permCtrl = nullptr;
2385 } else {
2386 permCtrl = interface_cast<IPermissionController>(binder);
2387 }
2388 }
2389
2390 if (permCtrl == nullptr) {
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002391 // Return empty package name and the further interaction
2392 // with camera will likely fail
2393 return packageName;
2394 }
2395
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002396 Vector<String16> packages;
2397
2398 permCtrl->getPackagesForUid(clientUid, packages);
2399
2400 if (packages.isEmpty()) {
2401 ALOGE("No packages for calling UID %d", clientUid);
2402 // Return empty package name and the further interaction
2403 // with camera will likely fail
2404 return packageName;
2405 }
2406
2407 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002408 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002409
2410 return packageName;
2411}
2412
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002413template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002414Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2415 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2416 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002417 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002418 int rotationOverride, bool forceSlowJpegMode,
2419 const std::string& originalCameraId, /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002420 binder::Status ret = binder::Status::ok();
2421
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002422 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002423 std::string clientPackageName;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002424 int packageUid = (clientUid == USE_CALLING_UID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002425 getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002426 if (clientPackageNameMaybe.size() <= 0) {
2427 // NDK calls don't come with package names, but we need one for various cases.
2428 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2429 // do exist. For all authentication cases, all packages under the same UID get the
2430 // same permissions, so picking any associated package name is sufficient. For some
2431 // other cases, this may give inaccurate names for clients in logs.
2432 isNonSystemNdk = true;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002433 clientPackageName = getPackageNameFromUid(packageUid);
2434 } else {
2435 clientPackageName = clientPackageNameMaybe;
2436 }
2437
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002438 int originalClientPid = 0;
2439
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002440 int packagePid = (clientPid == USE_CALLING_PID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002441 getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002442 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002443 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002444 static_cast<int>(effectiveApiLevel));
2445
Shuzhen Wang316781a2020-08-18 18:11:01 -07002446 nsecs_t openTimeNs = systemTime();
2447
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002448 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002449 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002450 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002451
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002452 {
2453 // Acquire mServiceLock and prevent other clients from connecting
2454 std::unique_ptr<AutoConditionLock> lock =
2455 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2456
2457 if (lock == nullptr) {
2458 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2459 , clientPid);
2460 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2461 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002462 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002463 }
2464
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002465 // Enforce client permissions and do basic validity checks
Biswarup Pal37a75182024-01-16 15:53:35 +00002466 if (!(ret = validateConnectLocked(cameraId, clientPackageName,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002467 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2468 return ret;
2469 }
2470
2471 // Check the shim parameters after acquiring lock, if they have already been updated and
2472 // we were doing a shim update, return immediately
2473 if (shimUpdateOnly) {
2474 auto cameraState = getCameraState(cameraId);
2475 if (cameraState != nullptr) {
2476 if (!cameraState->getShimParams().isEmpty()) return ret;
2477 }
2478 }
2479
2480 status_t err;
2481
2482 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002483 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002484 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002485 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2486 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002487 switch (err) {
2488 case -ENODEV:
2489 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2490 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002491 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002492 case -EBUSY:
2493 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2494 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002495 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002496 case -EUSERS:
2497 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2498 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002499 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002500 default:
2501 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2502 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002503 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002504 }
2505 }
2506
2507 if (clientTmp.get() != nullptr) {
2508 // Handle special case for API1 MediaRecorder where the existing client is returned
2509 device = static_cast<CLIENT*>(clientTmp.get());
2510 return ret;
2511 }
2512
2513 // give flashlight a chance to close devices if necessary.
2514 mFlashlight->prepareDeviceOpen(cameraId);
2515
Austin Borger18b30a72022-10-27 12:20:29 -07002516 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002517 auto deviceVersionAndTransport =
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002518 getDeviceVersion(cameraId, rotationOverride, /*out*/&portraitRotation,
Austin Borger18b30a72022-10-27 12:20:29 -07002519 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002520 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002521 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002522 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002523 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002524 }
2525
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002526 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002527 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002528 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002529
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002530 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002531 clientFeatureId, cameraId, api1CameraId, facing,
2532 orientation, clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002533 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002534 rotationOverride, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002535 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002536 return ret;
2537 }
2538 client = static_cast<CLIENT*>(tmp.get());
2539
2540 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2541 __FUNCTION__);
2542
Austin Borgered99f642023-06-01 16:51:35 -07002543 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002544 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002545 if (err != OK) {
2546 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002547 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002548 mServiceLock.unlock();
2549 client->disconnect();
2550 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002551 switch(err) {
2552 case BAD_VALUE:
2553 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002554 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002555 case -EBUSY:
2556 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002557 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002558 case -EUSERS:
2559 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2560 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002561 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002562 case PERMISSION_DENIED:
2563 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002564 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002565 case -EACCES:
2566 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002567 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002568 case -ENODEV:
2569 default:
2570 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002571 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002572 strerror(-err), err);
2573 }
2574 }
2575
2576 // Update shim paremeters for legacy clients
2577 if (effectiveApiLevel == API_1) {
2578 // Assume we have always received a Client subclass for API1
2579 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2580 String8 rawParams = shimClient->getParameters();
2581 CameraParameters params(rawParams);
2582
2583 auto cameraState = getCameraState(cameraId);
2584 if (cameraState != nullptr) {
2585 cameraState->setShimParams(params);
2586 } else {
2587 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002588 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002589 }
2590 }
2591
Ravneetaeb20dc2022-03-30 05:33:03 +00002592 // Enable/disable camera service watchdog
2593 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2594
Emilian Peev6d45db82024-01-18 20:11:54 +00002595 CameraMetadata chars;
2596 bool rotateAndCropSupported = true;
2597 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002598 &chars, rotationOverride);
Emilian Peev6d45db82024-01-18 20:11:54 +00002599 if (err == OK) {
2600 auto availableRotateCropEntry = chars.find(
2601 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2602 if (availableRotateCropEntry.count <= 1) {
2603 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002604 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002605 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002606 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2607 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002608 }
2609
Emilian Peev6d45db82024-01-18 20:11:54 +00002610 if (rotateAndCropSupported) {
2611 // Set rotate-and-crop override behavior
2612 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2613 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002614 } else if (rotationOverride != hardware::ICameraService::ROTATION_OVERRIDE_NONE &&
2615 portraitRotation != 0) {
Emilian Peev6d45db82024-01-18 20:11:54 +00002616 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2617 switch (portraitRotation) {
2618 case 90:
2619 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2620 break;
2621 case 180:
2622 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2623 break;
2624 case 270:
2625 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2626 break;
2627 default:
2628 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2629 break;
2630 }
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002631 // Here we're communicating to the client the chosen rotate
2632 // and crop mode to send to the HAL
Emilian Peev6d45db82024-01-18 20:11:54 +00002633 client->setRotateAndCropOverride(rotateAndCropMode);
2634 } else {
2635 client->setRotateAndCropOverride(
2636 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2637 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2638 }
2639 }
2640
2641 bool autoframingSupported = true;
2642 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2643 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2644 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2645 autoframingSupported = false;
2646 }
2647
2648 if (autoframingSupported) {
2649 // Set autoframing override behaviour
2650 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2651 client->setAutoframingOverride(mOverrideAutoframingMode);
2652 } else {
2653 client->setAutoframingOverride(
2654 mCameraServiceProxyWrapper->getAutoframingOverride(
2655 clientPackageName));
2656 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002657 }
2658
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002659 bool isCameraPrivacyEnabled;
2660 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002661 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002662 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2663 toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2664 } else {
2665 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002666 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002667 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002668
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002669 if (client->supportsCameraMute()) {
2670 client->setCameraMute(
2671 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2672 } else if (isCameraPrivacyEnabled) {
2673 // no camera mute supported, but privacy is on! => disconnect
2674 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2675 client->getPackageName().c_str(), cameraId.c_str());
2676 // Do not hold mServiceLock while disconnecting clients, but
2677 // retain the condition blocking other clients from connecting
2678 // in mServiceLockWrapper if held.
2679 mServiceLock.unlock();
2680 // Clear caller identity temporarily so client disconnect PID
2681 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002682 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002683 // Note AppOp to trigger the "Unblock" dialog
2684 client->noteAppOp();
2685 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002686 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002687 // Reacquire mServiceLock
2688 mServiceLock.lock();
2689
2690 return STATUS_ERROR_FMT(ERROR_DISABLED,
2691 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002692 }
2693
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002694 if (shimUpdateOnly) {
2695 // If only updating legacy shim parameters, immediately disconnect client
2696 mServiceLock.unlock();
2697 client->disconnect();
2698 mServiceLock.lock();
2699 } else {
2700 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002701 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002702 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002703
2704 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002705 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002706 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002707 } // lock is destroyed, allow further connect calls
2708
2709 // Important: release the mutex here so the client can call back into the service from its
2710 // destructor (can be at the end of the call)
2711 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002712
2713 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002714 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002715 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002716
Cliff Wud3a05312021-04-26 23:07:31 +08002717 {
2718 Mutex::Autolock lock(mInjectionParametersLock);
2719 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2720 mInjectionInitPending = false;
2721 status_t res = NO_ERROR;
2722 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2723 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002724 sp<BasicClient> clientSp = clientDescriptor->getValue();
2725 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2726 if(res != OK) {
2727 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2728 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002729 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002730 }
2731 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002732 if (res != OK) {
2733 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2734 }
2735 } else {
2736 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002737 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002738 res = NO_INIT;
2739 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2740 }
2741 }
2742 }
2743
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002744 return ret;
2745}
2746
Austin Borgered99f642023-06-01 16:51:35 -07002747status_t CameraService::addOfflineClient(const std::string &cameraId,
2748 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002749 if (offlineClient.get() == nullptr) {
2750 return BAD_VALUE;
2751 }
2752
2753 {
2754 // Acquire mServiceLock and prevent other clients from connecting
2755 std::unique_ptr<AutoConditionLock> lock =
2756 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2757
2758 if (lock == nullptr) {
2759 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2760 , __FUNCTION__, offlineClient->getClientPid());
2761 return TIMED_OUT;
2762 }
2763
2764 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2765 if (onlineClientDesc.get() == nullptr) {
2766 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2767 cameraId.c_str());
2768 return BAD_VALUE;
2769 }
2770
2771 // Offline clients do not evict or conflict with other online devices. Resource sharing
2772 // conflicts are handled by the camera provider which will either succeed or fail before
2773 // reaching this method.
2774 const auto& onlinePriority = onlineClientDesc->getPriority();
2775 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2776 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002777 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002778 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002779 // native clients don't have offline processing support.
2780 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002781 if (offlineClientDesc == nullptr) {
2782 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2783 return BAD_VALUE;
2784 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002785
2786 // Allow only one offline device per camera
2787 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2788 if (!incompatibleClients.empty()) {
2789 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2790 return BAD_VALUE;
2791 }
2792
Austin Borgered99f642023-06-01 16:51:35 -07002793 std::string monitorTags = isClientWatched(offlineClient.get())
2794 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002795 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002796 if (err != OK) {
2797 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2798 return err;
2799 }
2800
2801 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2802 if (evicted.size() > 0) {
2803 for (auto& i : evicted) {
2804 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002805 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002806 }
2807
2808 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2809 "properly", __FUNCTION__);
2810
2811 return BAD_VALUE;
2812 }
2813
2814 logConnectedOffline(offlineClientDesc->getKey(),
2815 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002816 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002817
2818 sp<IBinder> remoteCallback = offlineClient->getRemote();
2819 if (remoteCallback != nullptr) {
2820 remoteCallback->linkToDeath(this);
2821 }
2822 } // lock is destroyed, allow further connect calls
2823
2824 return OK;
2825}
2826
Austin Borgered99f642023-06-01 16:51:35 -07002827Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +00002828 int32_t torchStrength, const sp<IBinder>& clientBinder, int32_t deviceId,
2829 int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002830 Mutex::Autolock lock(mServiceLock);
2831
2832 ATRACE_CALL();
2833 if (clientBinder == nullptr) {
2834 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2835 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2836 "Torch client binder in null.");
2837 }
2838
Austin Borger22c5c852024-03-08 13:31:36 -08002839 int uid = getCallingUid();
Biswarup Pal37a75182024-01-16 15:53:35 +00002840 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
malikakash98260df2024-05-10 23:33:57 +00002841 devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002842 if (!cameraIdOptional.has_value()) {
2843 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
2844 unresolvedCameraId.c_str(), deviceId);
2845 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2846 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2847 }
2848 std::string cameraId = cameraIdOptional.value();
2849
Austin Borgered99f642023-06-01 16:51:35 -07002850 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002851 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002852 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002853 }
2854
2855 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002856 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002857 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002858 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002859 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002860 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002861 }
2862
2863 StatusInternal cameraStatus = state->getStatus();
2864 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2865 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002866 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002867 (int)cameraStatus);
2868 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002869 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002870 }
2871
2872 {
2873 Mutex::Autolock al(mTorchStatusMutex);
2874 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002875 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002876 if (err != OK) {
2877 if (err == NAME_NOT_FOUND) {
2878 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002879 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002880 }
2881 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002882 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002883 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2884 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002885 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002886 }
2887
2888 if (status == TorchModeStatus::NOT_AVAILABLE) {
2889 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2890 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002891 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002892 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2893 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002894 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002895 } else {
2896 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002897 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002898 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2899 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002900 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002901 }
2902 }
2903 }
2904
2905 {
2906 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002907 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002908 }
2909 // Check if the current torch strength level is same as the new one.
2910 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002911 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002912
Austin Borgered99f642023-06-01 16:51:35 -07002913 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002914
2915 if (err != OK) {
2916 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002917 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002918 switch (err) {
2919 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002920 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2921 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002922 errorCode = ERROR_ILLEGAL_ARGUMENT;
2923 break;
2924 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002925 msg = fmt::sprintf("Camera \"%s\" is in use",
2926 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002927 errorCode = ERROR_CAMERA_IN_USE;
2928 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002929 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002930 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002931 "valid range.", torchStrength);
2932 errorCode = ERROR_ILLEGAL_ARGUMENT;
2933 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002934 default:
Austin Borgered99f642023-06-01 16:51:35 -07002935 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002936 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002937 }
Austin Borgered99f642023-06-01 16:51:35 -07002938 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2939 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002940 }
2941
2942 {
2943 // update the link to client's death
2944 // Store the last client that turns on each camera's torch mode.
2945 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002946 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002947 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002948 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002949 } else {
2950 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2951 mTorchClientMap.replaceValueAt(index, clientBinder);
2952 }
2953 clientBinder->linkToDeath(this);
2954 }
2955
Austin Borger22c5c852024-03-08 13:31:36 -08002956 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002957 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002958 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002959 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002960 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002961 }
2962 return Status::ok();
2963}
2964
malikakash73125c62023-07-21 22:44:34 +00002965Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Biswarup Pal37a75182024-01-16 15:53:35 +00002966 const sp<IBinder>& clientBinder, int32_t deviceId, int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002967 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002968
2969 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002970 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002971 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002972 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2973 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002974 }
2975
Austin Borger22c5c852024-03-08 13:31:36 -08002976 int uid = getCallingUid();
Biswarup Pal37a75182024-01-16 15:53:35 +00002977 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
malikakash98260df2024-05-10 23:33:57 +00002978 devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002979 if (!cameraIdOptional.has_value()) {
2980 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
2981 unresolvedCameraId.c_str(), deviceId);
2982 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2983 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2984 }
2985 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002986
Austin Borgered99f642023-06-01 16:51:35 -07002987 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002988 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07002989 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002990 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002991 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07002992 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08002993 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002994 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002995 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002996 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002997 }
2998
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002999 StatusInternal cameraStatus = state->getStatus();
3000 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003001 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07003002 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
3003 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003004 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003005 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003006 }
3007
3008 {
3009 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003010 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003011 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003012 if (err != OK) {
3013 if (err == NAME_NOT_FOUND) {
3014 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003015 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003016 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003017 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003018 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003019 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07003020 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003021 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003022 }
3023
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003024 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003025 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003026 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003027 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003028 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3029 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003030 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003031 } else {
3032 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003033 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003034 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3035 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003036 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003037 }
3038 }
3039 }
3040
Ruben Brunk99e69712015-05-26 17:25:07 -07003041 {
3042 // Update UID map - this is used in the torch status changed callbacks, so must be done
3043 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003044 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003045 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003046 }
3047
Austin Borgered99f642023-06-01 16:51:35 -07003048 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003049
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003050 if (err != OK) {
3051 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003052 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003053 switch (err) {
3054 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003055 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3056 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003057 errorCode = ERROR_ILLEGAL_ARGUMENT;
3058 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003059 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003060 msg = fmt::sprintf("Camera \"%s\" is in use",
3061 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003062 errorCode = ERROR_CAMERA_IN_USE;
3063 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003064 default:
Austin Borgered99f642023-06-01 16:51:35 -07003065 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003066 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003067 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003068 errorCode = ERROR_INVALID_OPERATION;
3069 }
Austin Borgered99f642023-06-01 16:51:35 -07003070 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3071 logServiceError(msg, errorCode);
3072 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003073 }
3074
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003075 {
3076 // update the link to client's death
3077 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003078 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003079 if (enabled) {
3080 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003081 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003082 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003083 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003084 mTorchClientMap.replaceValueAt(index, clientBinder);
3085 }
3086 clientBinder->linkToDeath(this);
3087 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003088 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003089 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003090 }
3091
Austin Borger22c5c852024-03-08 13:31:36 -08003092 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003093 std::string torchState = enabled ? "on" : "off";
3094 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3095 torchState.c_str(), clientPid);
3096 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003097 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003098}
3099
Austin Borgered99f642023-06-01 16:51:35 -07003100void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3101 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3102 mTorchUidMap[cameraId].first = uid;
3103 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003104 } else {
3105 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003106 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003107 }
3108}
3109
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003110Status CameraService::notifySystemEvent(int32_t eventId,
3111 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003112 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003113 const int selfPid = getpid();
3114
3115 // Permission checks
3116 if (pid != selfPid) {
3117 // Ensure we're being called by system_server, or similar process with
3118 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003119 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003120 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003121 ALOGE("Permission Denial: cannot send updates to camera service about system"
3122 " events from pid=%d, uid=%d", pid, uid);
3123 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003124 "No permission to send updates to camera service about system events"
3125 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003126 }
3127 }
3128
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003129 ATRACE_CALL();
3130
Ruben Brunk36597b22015-03-20 22:15:57 -07003131 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003132 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003133 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003134 // from a system server crash
3135 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003136 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003137 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003138 break;
3139 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003140 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3141 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003142 if (args.size() != 1) {
3143 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3144 "USB Device Event requires 1 argument");
3145 }
3146
Valentin Iftime29e2e152021-08-13 15:17:33 +02003147 // Notify CameraProviderManager for lazy HALs
3148 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3149 std::to_string(args[0]));
3150 break;
3151 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003152 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003153 default: {
3154 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3155 eventId);
3156 break;
3157 }
3158 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003159 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003160}
3161
Emilian Peev53722fa2019-02-22 17:47:20 -08003162void CameraService::notifyMonitoredUids() {
3163 Mutex::Autolock lock(mStatusListenerLock);
3164
3165 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003166 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003167 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3168 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003169 }
3170}
3171
Austin Borgerdddb7552023-03-30 17:53:01 -07003172void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3173 Mutex::Autolock lock(mStatusListenerLock);
3174
3175 for (const auto& it : mListenerList) {
3176 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3177 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3178 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3179 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3180 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3181 }
3182 }
3183}
3184
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003185Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003186 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003187 const int selfPid = getpid();
3188
3189 // Permission checks
3190 if (pid != selfPid) {
3191 // Ensure we're being called by system_server, or similar process with
3192 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003193 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003194 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003195 ALOGE("Permission Denial: cannot send updates to camera service about device"
3196 " state changes from pid=%d, uid=%d", pid, uid);
3197 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3198 "No permission to send updates to camera service about device state"
3199 " changes from pid=%d, uid=%d", pid, uid);
3200 }
3201 }
3202
3203 ATRACE_CALL();
3204
Austin Borger18b30a72022-10-27 12:20:29 -07003205 {
3206 Mutex::Autolock lock(mServiceLock);
3207 mDeviceState = newState;
3208 }
3209
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003210 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003211
3212 return Status::ok();
3213}
3214
Emilian Peev8b64f282021-03-25 16:49:57 -07003215Status CameraService::notifyDisplayConfigurationChange() {
3216 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003217 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003218 const int selfPid = getpid();
3219
3220 // Permission checks
3221 if (callingPid != selfPid) {
3222 // Ensure we're being called by system_server, or similar process with
3223 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003224 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003225 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003226 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3227 " changes from pid=%d, uid=%d", callingPid, uid);
3228 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3229 "No permission to send updates to camera service about orientation"
3230 " changes from pid=%d, uid=%d", callingPid, uid);
3231 }
3232 }
3233
3234 Mutex::Autolock lock(mServiceLock);
3235
3236 // Don't do anything if rotate-and-crop override via cmd is active
3237 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3238
3239 const auto clients = mActiveClientManager.getAll();
3240 for (auto& current : clients) {
3241 if (current != nullptr) {
3242 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003243 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3244 basicClient->setRotateAndCropOverride(
3245 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3246 basicClient->getPackageName(),
3247 basicClient->getCameraFacing(),
3248 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003249 }
3250 }
3251 }
3252
3253 return Status::ok();
3254}
3255
3256Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003257 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3258 ATRACE_CALL();
3259 if (!concurrentCameraIds) {
3260 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3261 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3262 }
3263
3264 if (!mInitialized) {
3265 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003266 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003267 return STATUS_ERROR(ERROR_DISCONNECTED,
3268 "Camera subsystem is not available");
3269 }
3270 // First call into the provider and get the set of concurrent camera
3271 // combinations
3272 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003273 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003274 for (auto &combination : concurrentCameraCombinations) {
Biswarup Pal7d072862024-04-17 15:24:47 +00003275 std::vector<std::pair<std::string, int32_t>> validCombination;
3276 int32_t firstDeviceId = kInvalidDeviceId;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003277 for (auto &cameraId : combination) {
3278 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003279 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003280 if (state == nullptr) {
3281 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3282 continue;
3283 }
3284 StatusInternal status = state->getStatus();
3285 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3286 continue;
3287 }
Austin Borgered99f642023-06-01 16:51:35 -07003288 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003289 continue;
3290 }
Biswarup Pal7d072862024-04-17 15:24:47 +00003291 auto [cameraOwnerDeviceId, mappedCameraId] =
3292 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
3293 if (firstDeviceId == kInvalidDeviceId) {
3294 firstDeviceId = cameraOwnerDeviceId;
3295 } else if (firstDeviceId != cameraOwnerDeviceId) {
3296 // Found an invalid combination which contains cameras with different device id's,
3297 // hence discard it.
3298 validCombination.clear();
3299 break;
3300 }
3301 validCombination.push_back({mappedCameraId, cameraOwnerDeviceId});
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003302 }
3303 if (validCombination.size() != 0) {
3304 concurrentCameraIds->push_back(std::move(validCombination));
3305 }
3306 }
3307 return Status::ok();
3308}
3309
3310Status CameraService::isConcurrentSessionConfigurationSupported(
3311 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Biswarup Pal7d072862024-04-17 15:24:47 +00003312 int targetSdkVersion, int32_t deviceId, int32_t devicePolicy,
3313 /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003314 if (!isSupported) {
3315 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3316 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3317 }
3318
3319 if (!mInitialized) {
3320 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3321 return STATUS_ERROR(ERROR_DISCONNECTED,
3322 "Camera subsystem is not available");
3323 }
3324
Biswarup Pal7d072862024-04-17 15:24:47 +00003325 for (auto cameraIdAndSessionConfiguration : cameraIdsAndSessionConfigurations) {
3326 std::optional<std::string> cameraIdOptional =
malikakash98260df2024-05-10 23:33:57 +00003327 resolveCameraId(cameraIdAndSessionConfiguration.mCameraId, deviceId, devicePolicy);
Biswarup Pal7d072862024-04-17 15:24:47 +00003328 if (!cameraIdOptional.has_value()) {
3329 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
3330 cameraIdAndSessionConfiguration.mCameraId.c_str(), deviceId);
3331 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3332 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3333 }
3334 cameraIdAndSessionConfiguration.mCameraId = cameraIdOptional.value();
3335 }
3336
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003337 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003338 int callingPid = getCallingPid();
3339 int callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003340 bool hasCameraPermission = ((callingPid == getpid()) ||
Biswarup Pal7d072862024-04-17 15:24:47 +00003341 hasPermissionsForCamera(callingPid, callingUid,
3342 devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT
3343 ? kDefaultDeviceId : deviceId));
Austin Borger249e6592024-03-10 22:28:11 -07003344 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003345 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3346 "android.permission.CAMERA needed to call"
3347 "isConcurrentSessionConfigurationSupported");
3348 }
3349
3350 status_t res =
3351 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003352 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3353 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003354 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003355 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003356 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003357 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3358 "support %s (%d)", strerror(-res), res);
3359 }
3360 return Status::ok();
3361}
3362
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003363Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3364 /*out*/
3365 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003366 return addListenerHelper(listener, cameraStatuses);
3367}
3368
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003369binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3370 std::vector<hardware::CameraStatus>* cameraStatuses) {
3371 return addListenerHelper(listener, cameraStatuses, false, true);
3372}
3373
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003374Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3375 /*out*/
3376 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003377 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003378 ATRACE_CALL();
3379
Igor Murashkinbfc99152013-02-27 12:55:20 -08003380 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003381
Ruben Brunk3450ba72015-06-16 11:00:37 -07003382 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003383 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003384 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003385 }
3386
Austin Borger22c5c852024-03-08 13:31:36 -08003387 auto clientPid = getCallingPid();
3388 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003389 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003390
Igor Murashkinbfc99152013-02-27 12:55:20 -08003391 Mutex::Autolock lock(mServiceLock);
3392
Ruben Brunkcc776712015-02-17 20:18:47 -08003393 {
3394 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003395 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003396 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003397 ALOGW("%s: Tried to add listener %p which was already subscribed",
3398 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003399 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003400 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003401 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003402
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003403 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003404 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3405 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003406 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003407 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003408 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003409 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003410 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3411 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3412 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003413 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003414 // The listener still needs to be added to the list of listeners, regardless of what
3415 // permissions the listener process has / whether it is a vendor listener. Since it might be
3416 // eligible to listen to other camera ids.
3417 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003418 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003419 }
3420
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003421 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003422 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003423 Mutex::Autolock lock(mCameraStatesLock);
3424 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003425 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3426 auto [deviceId, mappedCameraId] =
3427 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3428
3429 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003430 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003431 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3432 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003433 }
3434 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003435 // Remove the camera statuses that should be hidden from the client, we do
3436 // this after collecting the states in order to avoid holding
3437 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3438 // the same time.
3439 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3440 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003441 std::string cameraId = s.cameraId;
3442 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
malikakash98260df2024-05-10 23:33:57 +00003443 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM);
Biswarup Pal37a75182024-01-16 15:53:35 +00003444 if (!cameraIdOptional.has_value()) {
3445 std::string msg =
3446 fmt::sprintf(
3447 "Camera %s: Invalid camera id for device id %d",
3448 s.cameraId.c_str(), s.deviceId);
3449 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3450 return true;
3451 }
3452 cameraId = cameraIdOptional.value();
3453 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3454 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3455 ALOGE("%s: Invalid camera id %s, skipping status update",
3456 __FUNCTION__, s.cameraId.c_str());
3457 return true;
3458 }
3459 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3460 clientUid);
3461 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003462
Biswarup Pal37a75182024-01-16 15:53:35 +00003463 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003464 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003465 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003466 // Add only default device cameras here, as virtual cameras currently don't support torch
3467 // anyway. Note that this is a simplification of the implementation here, and we should
3468 // change this when virtual cameras support torch.
3469 if (s.deviceId == kDefaultDeviceId) {
3470 idsChosenForCallback.insert(s.cameraId);
3471 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003472 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003473
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003474 /*
3475 * Immediately signal current torch status to this listener only
3476 * This may be a subset of all the devices, so don't include it in the response directly
3477 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003478 {
3479 Mutex::Autolock al(mTorchStatusMutex);
3480 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003481 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003482 // The camera id is visible to the client. Fine to send torch
3483 // callback.
3484 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003485 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3486 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003487 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003488 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003489 }
3490
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003491 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003492}
Ruben Brunkcc776712015-02-17 20:18:47 -08003493
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003494Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003495 ATRACE_CALL();
3496
Igor Murashkinbfc99152013-02-27 12:55:20 -08003497 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3498
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003499 if (listener == 0) {
3500 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003501 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003502 }
3503
Igor Murashkinbfc99152013-02-27 12:55:20 -08003504 Mutex::Autolock lock(mServiceLock);
3505
Ruben Brunkcc776712015-02-17 20:18:47 -08003506 {
3507 Mutex::Autolock lock(mStatusListenerLock);
3508 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003509 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003510 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003511 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003512 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003513 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003514 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003515 }
3516 }
3517
3518 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3519 __FUNCTION__, listener.get());
3520
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003521 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003522}
3523
Austin Borgered99f642023-06-01 16:51:35 -07003524Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003525
3526 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003527 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3528
3529 if (parameters == NULL) {
3530 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003531 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003532 }
3533
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003534 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003535
3536 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003537 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003538 // Error logged by caller
3539 return ret;
3540 }
3541
3542 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003543
Austin Borgered99f642023-06-01 16:51:35 -07003544 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003545
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003546 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003547}
3548
malikakash98260df2024-05-10 23:33:57 +00003549Status CameraService::supportsCameraApi(const std::string& cameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003550 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003551 ATRACE_CALL();
3552
Austin Borgered99f642023-06-01 16:51:35 -07003553 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003554
3555 switch (apiVersion) {
3556 case API_VERSION_1:
3557 case API_VERSION_2:
3558 break;
3559 default:
Austin Borgered99f642023-06-01 16:51:35 -07003560 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3561 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3562 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003563 }
3564
Austin Borger18b30a72022-10-27 12:20:29 -07003565 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00003566 auto deviceVersionAndTransport =
3567 getDeviceVersion(cameraId,
3568 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
3569 &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003570 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003571 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3572 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3573 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003574 }
3575 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3576 int deviceVersion = deviceVersionAndTransport.first;
3577 switch (deviceVersion) {
3578 case CAMERA_DEVICE_API_VERSION_1_0:
3579 case CAMERA_DEVICE_API_VERSION_3_0:
3580 case CAMERA_DEVICE_API_VERSION_3_1:
3581 if (apiVersion == API_VERSION_2) {
3582 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003583 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003584 *isSupported = false;
3585 } else { // if (apiVersion == API_VERSION_1) {
3586 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003587 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003588 *isSupported = true;
3589 }
3590 break;
3591 case CAMERA_DEVICE_API_VERSION_3_2:
3592 case CAMERA_DEVICE_API_VERSION_3_3:
3593 case CAMERA_DEVICE_API_VERSION_3_4:
3594 case CAMERA_DEVICE_API_VERSION_3_5:
3595 case CAMERA_DEVICE_API_VERSION_3_6:
3596 case CAMERA_DEVICE_API_VERSION_3_7:
3597 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003598 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003599 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003600 break;
3601 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003602 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3603 deviceVersion, cameraId.c_str());
3604 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3605 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003606 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003607 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003608 } else {
3609 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003610 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003611 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003612}
3613
malikakash98260df2024-05-10 23:33:57 +00003614Status CameraService::isHiddenPhysicalCamera(const std::string& cameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003615 /*out*/ bool *isSupported) {
3616 ATRACE_CALL();
3617
Austin Borgered99f642023-06-01 16:51:35 -07003618 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3619 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003620
3621 return Status::ok();
3622}
3623
Cliff Wud8cae102021-03-11 01:37:42 +08003624Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003625 const std::string& packageName, const std::string& internalCamId,
3626 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003627 const sp<ICameraInjectionCallback>& callback,
3628 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003629 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003630 ATRACE_CALL();
3631
Austin Borgered99f642023-06-01 16:51:35 -07003632 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003633 const int pid = getCallingPid();
3634 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003635 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3636 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003637 "Permission Denial: no permission to inject camera");
3638 }
3639
3640 // Do not allow any camera injection that injects or replaces a virtual camera.
3641 auto [deviceIdForInternalCamera, _] =
3642 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3643 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3644 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3645 "Cannot replace a virtual camera");
3646 }
3647 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3648 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3649 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3650 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3651 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003652 }
3653
3654 ALOGV(
3655 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3656 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003657 __FUNCTION__, packageName.c_str(),
3658 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003659
Cliff Wud3a05312021-04-26 23:07:31 +08003660 {
3661 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003662 mInjectionInternalCamId = internalCamId;
3663 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003664 mInjectionStatusListener->addListener(callback);
3665 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003666 status_t res = NO_ERROR;
3667 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3668 // If the client already exists, we can directly connect to the camera device through the
3669 // client's injectCamera(), otherwise we need to wait until the client is established
3670 // (execute connectHelper()) before injecting the camera to the camera device.
3671 if (clientDescriptor != nullptr) {
3672 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003673 sp<BasicClient> clientSp = clientDescriptor->getValue();
3674 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3675 if(res != OK) {
3676 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3677 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003678 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003679 }
3680 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003681 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003682 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3683 }
3684 } else {
3685 mInjectionInitPending = true;
3686 }
3687 }
Cliff Wud8cae102021-03-11 01:37:42 +08003688
Cliff Wud3a05312021-04-26 23:07:31 +08003689 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003690}
3691
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003692Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003693 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003694 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3695 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3696 return Status::ok();
3697}
3698
Ruben Brunkcc776712015-02-17 20:18:47 -08003699void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003700 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003701 for (auto& i : mActiveClientManager.getAll()) {
3702 auto clientSp = i->getValue();
3703 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003704 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003705 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003706 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003707 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003708 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003709}
3710
Ruben Brunkcc776712015-02-17 20:18:47 -08003711bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003712 bool ret = false;
3713 {
3714 // Acquire mServiceLock and prevent other clients from connecting
3715 std::unique_ptr<AutoConditionLock> lock =
3716 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003717
Ruben Brunkcc776712015-02-17 20:18:47 -08003718 std::vector<sp<BasicClient>> evicted;
3719 for (auto& i : mActiveClientManager.getAll()) {
3720 auto clientSp = i->getValue();
3721 if (clientSp.get() == nullptr) {
3722 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3723 mActiveClientManager.remove(i);
3724 continue;
3725 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003726 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003727 mActiveClientManager.remove(i);
3728 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003729
Ruben Brunkcc776712015-02-17 20:18:47 -08003730 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003731 clientSp->notifyError(
3732 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003733 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003734 }
3735 }
3736
Ruben Brunkcc776712015-02-17 20:18:47 -08003737 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3738 // other clients from connecting in mServiceLockWrapper if held
3739 mServiceLock.unlock();
3740
Ruben Brunk36597b22015-03-20 22:15:57 -07003741 // Do not clear caller identity, remote caller should be client proccess
3742
Ruben Brunkcc776712015-02-17 20:18:47 -08003743 for (auto& i : evicted) {
3744 if (i.get() != nullptr) {
3745 i->disconnect();
3746 ret = true;
3747 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003748 }
3749
Ruben Brunkcc776712015-02-17 20:18:47 -08003750 // Reacquire mServiceLock
3751 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003752
Ruben Brunkcc776712015-02-17 20:18:47 -08003753 } // lock is destroyed, allow further connect calls
3754
3755 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003756}
3757
Ruben Brunkcc776712015-02-17 20:18:47 -08003758std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003759 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003760 std::shared_ptr<CameraState> state;
3761 {
3762 Mutex::Autolock lock(mCameraStatesLock);
3763 auto iter = mCameraStates.find(cameraId);
3764 if (iter != mCameraStates.end()) {
3765 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003766 }
3767 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003768 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003769}
3770
Austin Borgered99f642023-06-01 16:51:35 -07003771sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003772 // Remove from active clients list
3773 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3774 if (clientDescriptorPtr == nullptr) {
3775 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003776 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003777 return sp<BasicClient>{nullptr};
3778 }
3779
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003780 sp<BasicClient> client = clientDescriptorPtr->getValue();
3781 if (client.get() != nullptr) {
3782 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3783 }
3784 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003785}
3786
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003787void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003788 // Acquire mServiceLock and prevent other clients from connecting
3789 std::unique_ptr<AutoConditionLock> lock =
3790 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3791
Ruben Brunk6267b532015-04-30 17:44:07 -07003792 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003793 for (size_t i = 0; i < newUserIds.size(); i++) {
3794 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003795 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003796 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003797 return;
3798 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003799 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003800 }
3801
Ruben Brunka8ca9152015-04-07 14:23:40 -07003802
Ruben Brunk6267b532015-04-30 17:44:07 -07003803 if (newAllowedUsers == mAllowedUsers) {
3804 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3805 return;
3806 }
3807
3808 logUserSwitch(mAllowedUsers, newAllowedUsers);
3809
3810 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003811
3812 // Current user has switched, evict all current clients.
3813 std::vector<sp<BasicClient>> evicted;
3814 for (auto& i : mActiveClientManager.getAll()) {
3815 auto clientSp = i->getValue();
3816
3817 if (clientSp.get() == nullptr) {
3818 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3819 continue;
3820 }
3821
Ruben Brunk6267b532015-04-30 17:44:07 -07003822 // Don't evict clients that are still allowed.
3823 uid_t clientUid = clientSp->getClientUid();
3824 userid_t clientUserId = multiuser_get_user_id(clientUid);
3825 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3826 continue;
3827 }
3828
Ruben Brunk36597b22015-03-20 22:15:57 -07003829 evicted.push_back(clientSp);
3830
Ruben Brunk36597b22015-03-20 22:15:57 -07003831 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003832 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003833
Ruben Brunk36597b22015-03-20 22:15:57 -07003834 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003835 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003836 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003837 " to user switch.", i->getKey().c_str(),
3838 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003839 i->getOwnerId(), i->getPriority().getScore(),
3840 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003841
3842 }
3843
3844 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3845 // blocking other clients from connecting in mServiceLockWrapper if held.
3846 mServiceLock.unlock();
3847
3848 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08003849 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003850
3851 for (auto& i : evicted) {
3852 i->disconnect();
3853 }
3854
Austin Borger22c5c852024-03-08 13:31:36 -08003855 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003856
3857 // Reacquire mServiceLock
3858 mServiceLock.lock();
3859}
Ruben Brunkcc776712015-02-17 20:18:47 -08003860
Austin Borgered99f642023-06-01 16:51:35 -07003861void CameraService::logEvent(const std::string &event) {
3862 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003863 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003864 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003865 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003866 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003867 mEventLog.add(msg);
3868 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3869 // Error event not added to the dumpsys log before
3870 mEventLog.add(msg);
3871 sServiceErrorEventSet.insert(msg);
3872 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003873}
3874
Austin Borgered99f642023-06-01 16:51:35 -07003875void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3876 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003877 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003878 logEvent(fmt::sprintf("DISCONNECT 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::logDisconnectedOffline(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("DISCONNECT 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::logConnected(const std::string &cameraId, int clientPid,
3890 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003891 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003892 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3893 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003894}
3895
Austin Borgered99f642023-06-01 16:51:35 -07003896void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3897 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003898 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003899 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3900 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003901}
3902
Austin Borgered99f642023-06-01 16:51:35 -07003903void CameraService::logRejected(const std::string &cameraId, int clientPid,
3904 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003905 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003906 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3907 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003908}
3909
Austin Borgered99f642023-06-01 16:51:35 -07003910void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3911 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003912 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003913 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3914 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003915}
3916
Ruben Brunk6267b532015-04-30 17:44:07 -07003917void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3918 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003919 std::string newUsers = toString(newUserIds);
3920 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003921 if (oldUsers.size() == 0) {
3922 oldUsers = "<None>";
3923 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003924 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003925 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3926 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003927}
3928
Austin Borgered99f642023-06-01 16:51:35 -07003929void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003930 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003931 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003932}
3933
Austin Borgered99f642023-06-01 16:51:35 -07003934void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003935 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003936 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003937}
3938
Austin Borgered99f642023-06-01 16:51:35 -07003939void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003940 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003941 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003942}
3943
Austin Borgered99f642023-06-01 16:51:35 -07003944void CameraService::logServiceError(const std::string &msg, int errorCode) {
3945 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3946 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003947}
3948
Ruben Brunk36597b22015-03-20 22:15:57 -07003949status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3950 uint32_t flags) {
3951
Mathias Agopian65ab4712010-07-14 17:59:35 -07003952 // Permission checks
3953 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003954 case SHELL_COMMAND_TRANSACTION: {
3955 int in = data.readFileDescriptor();
3956 int out = data.readFileDescriptor();
3957 int err = data.readFileDescriptor();
3958 int argc = data.readInt32();
3959 Vector<String16> args;
3960 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3961 args.add(data.readString16());
3962 }
3963 sp<IBinder> unusedCallback;
3964 sp<IResultReceiver> resultReceiver;
3965 status_t status;
3966 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3967 return status;
3968 }
3969 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3970 return status;
3971 }
3972 status = shellCommand(in, out, err, args);
3973 if (resultReceiver != nullptr) {
3974 resultReceiver->send(status);
3975 }
3976 return NO_ERROR;
3977 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003978 }
3979
3980 return BnCameraService::onTransact(code, data, reply, flags);
3981}
3982
Mathias Agopian65ab4712010-07-14 17:59:35 -07003983// We share the media players for shutter and recording sound for all clients.
3984// A reference count is kept to determine when we will actually release the
3985// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09003986sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3987 sp<MediaPlayer> mp = new MediaPlayer();
3988 status_t error;
3989 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003990 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003991 error = mp->prepare();
3992 }
3993 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003994 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003995 mp->disconnect();
3996 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003997 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003998 }
3999 return mp;
4000}
4001
username5755fea2018-12-27 09:48:08 +08004002void CameraService::increaseSoundRef() {
4003 Mutex::Autolock lock(mSoundLock);
4004 mSoundRef++;
4005}
4006
4007void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004008 ATRACE_CALL();
4009
username5755fea2018-12-27 09:48:08 +08004010 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
4011 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
4012 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
4013 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
4014 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4015 }
4016 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
4017 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4018 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4019 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004020 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08004021 }
4022 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4023 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4024 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4025 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4026 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004027 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004028}
4029
username5755fea2018-12-27 09:48:08 +08004030void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004031 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004032 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004033 if (--mSoundRef) return;
4034
4035 for (int i = 0; i < NUM_SOUNDS; i++) {
4036 if (mSoundPlayer[i] != 0) {
4037 mSoundPlayer[i]->disconnect();
4038 mSoundPlayer[i].clear();
4039 }
4040 }
4041}
4042
4043void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004044 ATRACE_CALL();
4045
Mathias Agopian65ab4712010-07-14 17:59:35 -07004046 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004047 if (kind < 0 || kind >= NUM_SOUNDS) {
4048 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4049 return;
4050 }
4051
Mathias Agopian65ab4712010-07-14 17:59:35 -07004052 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004053 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004054 sp<MediaPlayer> player = mSoundPlayer[kind];
4055 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004056 player->seekTo(0);
4057 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004058 }
4059}
4060
4061// ----------------------------------------------------------------------------
4062
4063CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004064 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004065 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004066 const std::string& clientPackageName, bool systemNativeClient,
4067 const std::optional<std::string>& clientFeatureId,
4068 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004069 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004070 int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004071 int servicePid, int rotationOverride) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004072 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004073 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07004074 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004075 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004076 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004077 clientPid, clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004078 servicePid, rotationOverride),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004079 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004080{
Austin Borger22c5c852024-03-08 13:31:36 -08004081 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004082 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004083
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004084 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004085
username5755fea2018-12-27 09:48:08 +08004086 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004087
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004088 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004089}
4090
Mathias Agopian65ab4712010-07-14 17:59:35 -07004091// tear down the client
4092CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004093 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004094 mDestructionStarted = true;
4095
username5755fea2018-12-27 09:48:08 +08004096 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004097 // unconditionally disconnect. function is idempotent
4098 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004099}
4100
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004101sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4102
Igor Murashkin634a5152013-02-20 17:15:11 -08004103CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004104 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004105 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004106 const std::string& clientPackageName, bool nativeClient,
4107 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004108 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004109 int servicePid, int rotationOverride):
Austin Borger249e6592024-03-10 22:28:11 -07004110 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004111 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004112 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004113 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4114 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004115 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004116 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004117 mDisconnected(false), mUidIsTrusted(false),
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004118 mRotationOverride(rotationOverride),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004119 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004120 mRemoteBinder(remoteCallback),
4121 mOpsActive(false),
4122 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004123{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004124 if (sCameraService == nullptr) {
4125 sCameraService = cameraService;
4126 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004127
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004128 // There are 2 scenarios in which a client won't have AppOps operations
4129 // (both scenarios : native clients)
4130 // 1) It's an system native client*, the package name will be empty
4131 // and it will return from this function in the previous if condition
4132 // (This is the same as the previously existing behavior).
4133 // 2) It is a system native client, but its package name has been
4134 // modified for debugging, however it still must not use AppOps since
4135 // the package name is not a real one.
4136 //
4137 // * system native client - native client with UID < AID_APP_START. It
4138 // doesn't exclude clients not on the system partition.
4139 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004140 mAppOpsManager = std::make_unique<AppOpsManager>();
4141 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004142
Charles Chenf075f082024-03-04 23:32:55 +00004143 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004144}
4145
4146CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004147 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004148 mDestructionStarted = true;
4149}
4150
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004151binder::Status CameraService::BasicClient::disconnect() {
4152 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004153 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004154 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004155 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004156 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004157
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004158 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004159 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004160 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004161 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004162
4163 sp<IBinder> remote = getRemote();
4164 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004165 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004166 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004167
4168 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004169 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004170 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004171 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004172 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004173
Igor Murashkincba2c162013-03-20 15:56:31 -07004174 // client shouldn't be able to call into us anymore
4175 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004176
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004177 const auto& mActivityManager = getActivityManager();
4178 if (mActivityManager) {
4179 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004180 getCallingUid(),
4181 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004182 }
4183
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004184 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004185}
4186
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004187status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4188 // No dumping of clients directly over Binder,
4189 // must go through CameraService::dump
4190 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004191 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004192 return OK;
4193}
4194
Austin Borgered99f642023-06-01 16:51:35 -07004195status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004196 // Can't watch tags directly, must go through CameraService::startWatchingTags
4197 return OK;
4198}
4199
4200status_t CameraService::BasicClient::stopWatchingTags(int) {
4201 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4202 return OK;
4203}
4204
4205status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4206 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4207 return OK;
4208}
4209
Austin Borgered99f642023-06-01 16:51:35 -07004210std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004211 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004212}
4213
Emilian Peev8b64f282021-03-25 16:49:57 -07004214int CameraService::BasicClient::getCameraFacing() const {
4215 return mCameraFacing;
4216}
4217
4218int CameraService::BasicClient::getCameraOrientation() const {
4219 return mOrientation;
4220}
Ruben Brunkcc776712015-02-17 20:18:47 -08004221
4222int CameraService::BasicClient::getClientPid() const {
4223 return mClientPid;
4224}
4225
Ruben Brunk6267b532015-04-30 17:44:07 -07004226uid_t CameraService::BasicClient::getClientUid() const {
4227 return mClientUid;
4228}
4229
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004230bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4231 // Defaults to API2.
4232 return level == API_2;
4233}
4234
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004235status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004236 {
4237 Mutex::Autolock l(mAudioRestrictionLock);
4238 mAudioRestriction = mode;
4239 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004240 sCameraService->updateAudioRestriction();
4241 return OK;
4242}
4243
4244int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004245 return sCameraService->updateAudioRestriction();
4246}
4247
4248int32_t CameraService::BasicClient::getAudioRestriction() const {
4249 Mutex::Autolock l(mAudioRestrictionLock);
4250 return mAudioRestriction;
4251}
4252
4253bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4254 switch (mode) {
4255 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4256 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4257 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4258 return true;
4259 default:
4260 return false;
4261 }
4262}
4263
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004264status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4265 if (mode == AppOpsManager::MODE_ERRORED) {
4266 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004267 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004268 return PERMISSION_DENIED;
4269 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4270 // If the calling Uid is trusted (a native service), the AppOpsManager could
4271 // return MODE_IGNORED. Do not treat such case as error.
4272 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4273 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004274
4275 bool isCameraPrivacyEnabled;
4276 if (flags::camera_privacy_allowlist()) {
4277 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4278 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4279 } else {
4280 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004281 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004282 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004283 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4284 // We prefer to successfully open the camera and perform camera muting
4285 // or blocking in connectHelper as handleAppOpMode can be called before the
4286 // connection has been fully established and at that time camera muting
4287 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004288 if (!isUidActive || !isCameraPrivacyEnabled) {
Austin Borgerfd05d982024-04-22 15:54:50 -07004289 ALOGI("Camera %s: Access for \"%s\" has been restricted."
4290 "uid active: %s, privacy enabled: %s", mCameraIdStr.c_str(),
4291 mClientPackageName.c_str(), isUidActive ? "true" : "false",
4292 isCameraPrivacyEnabled ? "true" : "false");
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004293 // Return the same error as for device policy manager rejection
4294 return -EACCES;
4295 }
4296 }
4297 return OK;
4298}
4299
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004300status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004301 ATRACE_CALL();
4302
Igor Murashkine6800ce2013-03-04 17:25:57 -08004303 {
4304 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004305 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004306 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004307 if (mAppOpsManager != nullptr) {
4308 // Notify app ops that the camera is not available
4309 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004310
4311 if (flags::watch_foreground_changes()) {
4312 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4313 toString16(mClientPackageName),
4314 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4315 } else {
4316 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004317 toString16(mClientPackageName), mOpsCallback);
Austin Borgerca1e0062023-06-28 11:32:55 -07004318 }
Igor Murashkine6800ce2013-03-04 17:25:57 -08004319
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004320 // Just check for camera acccess here on open - delay startOp until
4321 // camera frames start streaming in startCameraStreamingOps
4322 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004323 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004324 status_t res = handleAppOpMode(mode);
4325 if (res != OK) {
4326 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004327 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004328 }
4329
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004330 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004331
4332 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004333 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004334
Austin Borgerdddb7552023-03-30 17:53:01 -07004335 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004336
Shuzhen Wang695044d2020-03-06 09:02:23 -08004337 // Notify listeners of camera open/close status
4338 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4339
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004340 return OK;
4341}
4342
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004343status_t CameraService::BasicClient::startCameraStreamingOps() {
4344 ATRACE_CALL();
4345
4346 if (!mOpsActive) {
4347 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4348 return INVALID_OPERATION;
4349 }
4350 if (mOpsStreaming) {
4351 ALOGV("%s: Streaming already active!", __FUNCTION__);
4352 return OK;
4353 }
4354
4355 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004356 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004357
4358 if (mAppOpsManager != nullptr) {
4359 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004360 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4361 toString16(mClientFeatureId),
4362 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004363 status_t res = handleAppOpMode(mode);
4364 if (res != OK) {
4365 return res;
4366 }
4367 }
4368
4369 mOpsStreaming = true;
4370
4371 return OK;
4372}
4373
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004374status_t CameraService::BasicClient::noteAppOp() {
4375 ATRACE_CALL();
4376
4377 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004378 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004379
4380 // noteAppOp is only used for when camera mute is not supported, in order
4381 // to trigger the sensor privacy "Unblock" dialog
4382 if (mAppOpsManager != nullptr) {
4383 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004384 toString16(mClientPackageName), toString16(mClientFeatureId),
4385 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004386 status_t res = handleAppOpMode(mode);
4387 if (res != OK) {
4388 return res;
4389 }
4390 }
4391
4392 return OK;
4393}
4394
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004395status_t CameraService::BasicClient::finishCameraStreamingOps() {
4396 ATRACE_CALL();
4397
4398 if (!mOpsActive) {
4399 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4400 return INVALID_OPERATION;
4401 }
4402 if (!mOpsStreaming) {
4403 ALOGV("%s: Streaming not active!", __FUNCTION__);
4404 return OK;
4405 }
4406
4407 if (mAppOpsManager != nullptr) {
4408 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004409 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004410 mOpsStreaming = false;
4411 }
4412
4413 return OK;
4414}
4415
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004416status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004417 ATRACE_CALL();
4418
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004419 if (mOpsStreaming) {
4420 // Make sure we've notified everyone about camera stopping
4421 finishCameraStreamingOps();
4422 }
4423
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004424 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004425 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004426 mOpsActive = false;
4427
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004428 // This function is called when a client disconnects. This should
4429 // release the camera, but actually only if it was in a proper
4430 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004431 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004432 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004433
Ruben Brunkcc776712015-02-17 20:18:47 -08004434 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004435 sCameraService->updateStatus(StatusInternal::PRESENT,
4436 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004437 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004438 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004439 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4440 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004441 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004442 mOpsCallback.clear();
4443
Austin Borgerdddb7552023-03-30 17:53:01 -07004444 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004445
Shuzhen Wang695044d2020-03-06 09:02:23 -08004446 // Notify listeners of camera open/close status
4447 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4448
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004449 return OK;
4450}
4451
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004452void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004453 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004454 if (mAppOpsManager == nullptr) {
4455 return;
4456 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004457 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004458 if (op != AppOpsManager::OP_CAMERA) {
4459 ALOGW("Unexpected app ops notification received: %d", op);
4460 return;
4461 }
4462
4463 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004464 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004465 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004466 ALOGV("checkOp returns: %d, %s ", res,
4467 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4468 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4469 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4470 "UNKNOWN");
4471
Shuzhen Wang64900852021-02-05 09:03:29 -08004472 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004473 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4474 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004475 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004476 } else if (res == AppOpsManager::MODE_IGNORED) {
4477 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004478
Austin Borgerca1e0062023-06-28 11:32:55 -07004479 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4480 // If not visible, but still active, then we want to block instead of muting the camera.
4481 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4482 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4483
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004484 bool isCameraPrivacyEnabled;
4485 if (flags::camera_privacy_allowlist()) {
4486 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4487 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4488 } else {
4489 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004490 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004491 }
4492
4493 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004494 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4495 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4496 isCameraPrivacyEnabled);
4497 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4498 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4499 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004500 if (!mUidIsTrusted) {
Austin Borgerca1e0062023-06-28 11:32:55 -07004501 if (flags::watch_foreground_changes()) {
4502 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4503 setCameraMute(true);
4504 } else {
4505 block();
4506 }
4507 } else {
4508 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4509 setCameraMute(true);
4510 } else if (!isUidActive
4511 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4512 block();
4513 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004514 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004515 }
Evan Severson09ab4002021-02-10 14:15:19 -08004516 } else if (res == AppOpsManager::MODE_ALLOWED) {
4517 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004518 }
4519}
4520
Svet Ganova453d0d2018-01-11 15:37:58 -08004521void CameraService::BasicClient::block() {
4522 ATRACE_CALL();
4523
4524 // Reset the client PID to allow server-initiated disconnect,
4525 // and to prevent further calls by client.
Austin Borger22c5c852024-03-08 13:31:36 -08004526 mClientPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004527 CaptureResultExtras resultExtras; // a dummy result (invalid)
4528 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4529 disconnect();
4530}
4531
Mathias Agopian65ab4712010-07-14 17:59:35 -07004532// ----------------------------------------------------------------------------
4533
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004534void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004535 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004536 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004537 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4538 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4539 api1ErrorCode = CAMERA_ERROR_DISABLED;
4540 }
4541 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004542 } else {
4543 ALOGE("mRemoteCallback is NULL!!");
4544 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004545}
4546
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004547// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004548binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004549 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004550 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004551}
4552
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004553bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4554 return level == API_1;
4555}
4556
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004557CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4558 mClient(client) {
4559}
4560
4561void CameraService::Client::OpsCallback::opChanged(int32_t op,
4562 const String16& packageName) {
4563 sp<BasicClient> client = mClient.promote();
4564 if (client != NULL) {
4565 client->opChanged(op, packageName);
4566 }
4567}
4568
Mathias Agopian65ab4712010-07-14 17:59:35 -07004569// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004570// UidPolicy
4571// ----------------------------------------------------------------------------
4572
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004573void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004574 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004575 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004576
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004577 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004578 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004579 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004580 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004581 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4582 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004583 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004584 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004585 if (res == OK) {
4586 mRegistered = true;
4587 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004588 } else {
4589 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004590 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004591}
4592
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004593void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004594 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004595 return;
4596 }
4597
4598 registerWithActivityManager();
4599}
4600
4601void CameraService::UidPolicy::registerSelf() {
4602 // Use check service to see if the activity service is available
4603 // If not available then register for notifications, instead of blocking
4604 // till the service is ready
4605 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004606 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004607 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004608 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004609 } else {
4610 registerWithActivityManager();
4611 }
4612}
4613
Svet Ganova453d0d2018-01-11 15:37:58 -08004614void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004615 Mutex::Autolock _l(mUidLock);
4616
Steven Moreland2f348142019-07-02 15:59:07 -07004617 mAm.unregisterUidObserver(this);
4618 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004619 mRegistered = false;
4620 mActiveUids.clear();
4621 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004622}
4623
4624void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4625 onUidIdle(uid, disabled);
4626}
4627
4628void CameraService::UidPolicy::onUidActive(uid_t uid) {
4629 Mutex::Autolock _l(mUidLock);
4630 mActiveUids.insert(uid);
4631}
4632
4633void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4634 bool deleted = false;
4635 {
4636 Mutex::Autolock _l(mUidLock);
4637 if (mActiveUids.erase(uid) > 0) {
4638 deleted = true;
4639 }
4640 }
4641 if (deleted) {
4642 sp<CameraService> service = mService.promote();
4643 if (service != nullptr) {
4644 service->blockClientsForUid(uid);
4645 }
4646 }
4647}
4648
Emilian Peev53722fa2019-02-22 17:47:20 -08004649void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004650 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004651 bool procStateChange = false;
4652 {
4653 Mutex::Autolock _l(mUidLock);
4654 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4655 mMonitoredUids[uid].procState != procState) {
4656 mMonitoredUids[uid].procState = procState;
4657 procStateChange = true;
4658 }
4659 }
4660
4661 if (procStateChange) {
4662 sp<CameraService> service = mService.promote();
4663 if (service != nullptr) {
4664 service->notifyMonitoredUids();
4665 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004666 }
4667}
4668
Austin Borgerdddb7552023-03-30 17:53:01 -07004669/**
4670 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4671 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4672 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4673 * monitoredUids. If it is revised above some other monitoredUid, signal
4674 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4675 * foreground apps in split screen - state changes will capture all other cases.
4676 */
4677void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4678 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004679 {
4680 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004681 auto it = mMonitoredUids.find(uid);
4682
4683 if (it != mMonitoredUids.end()) {
4684 if (it->second.hasCamera) {
4685 for (auto &monitoredUid : mMonitoredUids) {
4686 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004687 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004688 notifyUidSet.emplace(monitoredUid.first);
4689 }
4690 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004691 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004692 notifyUidSet.emplace(uid);
4693 } else {
4694 for (auto &monitoredUid : mMonitoredUids) {
4695 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004696 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004697 notifyUidSet.emplace(uid);
4698 }
4699 }
4700 }
4701 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004702 }
4703 }
4704
Austin Borgerdddb7552023-03-30 17:53:01 -07004705 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004706 sp<CameraService> service = mService.promote();
4707 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004708 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004709 }
4710 }
4711}
4712
Austin Borgerdddb7552023-03-30 17:53:01 -07004713/**
4714 * Register a uid for monitoring, and note whether it owns a camera.
4715 */
4716void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004717 Mutex::Autolock _l(mUidLock);
4718 auto it = mMonitoredUids.find(uid);
4719 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004720 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004721 } else {
Austin Borger65577682022-02-17 00:25:43 +00004722 MonitoredUid monitoredUid;
4723 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004724 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004725 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004726 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004727 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004728 if (res != OK) {
4729 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4730 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004731 }
4732
4733 if (openCamera) {
4734 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004735 }
4736}
4737
Austin Borgerdddb7552023-03-30 17:53:01 -07004738/**
4739 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4740 */
4741void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004742 Mutex::Autolock _l(mUidLock);
4743 auto it = mMonitoredUids.find(uid);
4744 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004745 it->second.refCount--;
4746 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004747 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004748 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004749 if (res != OK) {
4750 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4751 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004752 } else if (closeCamera) {
4753 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004754 }
4755 } else {
4756 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4757 }
4758}
4759
Austin Borgered99f642023-06-01 16:51:35 -07004760bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004761 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004762 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004763}
4764
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004765static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4766static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004767
Austin Borgered99f642023-06-01 16:51:35 -07004768bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004769 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004770 // If activity manager is unreachable, assume everything is active
4771 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004772 return true;
4773 }
4774 auto it = mOverrideUids.find(uid);
4775 if (it != mOverrideUids.end()) {
4776 return it->second;
4777 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004778 bool active = mActiveUids.find(uid) != mActiveUids.end();
4779 if (!active) {
4780 // We want active UIDs to always access camera with their first attempt since
4781 // there is no guarantee the app is robustly written and would retry getting
4782 // the camera on failure. The inverse case is not a problem as we would take
4783 // camera away soon once we get the callback that the uid is no longer active.
4784 ActivityManager am;
4785 // Okay to access with a lock held as UID changes are dispatched without
4786 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004787 int64_t startTimeMillis = 0;
4788 do {
4789 // TODO: Fix this b/109950150!
4790 // Okay this is a hack. There is a race between the UID turning active and
4791 // activity being resumed. The proper fix is very risky, so we temporary add
4792 // some polling which should happen pretty rarely anyway as the race is hard
4793 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004794 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004795 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004796 if (active) {
4797 break;
4798 }
4799 if (startTimeMillis <= 0) {
4800 startTimeMillis = uptimeMillis();
4801 }
4802 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004803 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004804 if (remainingTimeMillis <= 0) {
4805 break;
4806 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004807 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4808
4809 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004810 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004811 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004812 } while (true);
4813
Svet Ganov7b4ab782018-03-25 12:48:10 -07004814 if (active) {
4815 // Now that we found out the UID is actually active, cache that
4816 mActiveUids.insert(uid);
4817 }
4818 }
4819 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004820}
4821
Varun Shahb42f1eb2019-04-16 14:45:13 -07004822int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4823 Mutex::Autolock _l(mUidLock);
4824 return getProcStateLocked(uid);
4825}
4826
4827int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4828 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4829 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004830 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004831 }
4832 return procState;
4833}
4834
Austin Borgered99f642023-06-01 16:51:35 -07004835void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4836 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004837 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004838}
4839
Austin Borgered99f642023-06-01 16:51:35 -07004840void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004841 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004842}
4843
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004844void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4845 Mutex::Autolock _l(mUidLock);
4846 ALOGV("UidPolicy: ActivityManager has died");
4847 mRegistered = false;
4848 mActiveUids.clear();
4849}
4850
Austin Borgered99f642023-06-01 16:51:35 -07004851void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004852 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004853 bool wasActive = false;
4854 bool isActive = false;
4855 {
4856 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004857 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004858 mOverrideUids.erase(uid);
4859 if (insert) {
4860 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4861 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004862 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004863 }
4864 if (wasActive != isActive && !isActive) {
4865 sp<CameraService> service = mService.promote();
4866 if (service != nullptr) {
4867 service->blockClientsForUid(uid);
4868 }
4869 }
4870}
4871
4872// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004873// SensorPrivacyPolicy
4874// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004875
4876void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4877{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004878 Mutex::Autolock _l(mSensorPrivacyLock);
4879 if (mRegistered) {
4880 return;
4881 }
Evan Severson09ab4002021-02-10 14:15:19 -08004882 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004883 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004884 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004885 mSpm.addToggleSensorPrivacyListener(this);
4886 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004887 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004888 if (flags::camera_privacy_allowlist()) {
4889 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
4890 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
4891 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4892 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004893 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004894 if (res == OK) {
4895 mRegistered = true;
4896 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4897 }
4898}
4899
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004900void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4901 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004902 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004903 return;
4904 }
4905
4906 registerWithSensorPrivacyManager();
4907}
4908
4909void CameraService::SensorPrivacyPolicy::registerSelf() {
4910 // Use checkservice to see if the sensor_privacy service is available
4911 // If service is not available then register for notification
4912 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004913 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004914 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004915 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004916 } else {
4917 registerWithSensorPrivacyManager();
4918 }
4919}
4920
Michael Grooverd1d435a2018-12-18 17:39:42 -08004921void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4922 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004923 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004924 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004925 mSpm.removeToggleSensorPrivacyListener(this);
4926 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004927 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004928 mRegistered = false;
4929 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4930}
4931
4932bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004933 if (!mRegistered) {
4934 registerWithSensorPrivacyManager();
4935 }
4936
Michael Grooverd1d435a2018-12-18 17:39:42 -08004937 Mutex::Autolock _l(mSensorPrivacyLock);
4938 return mSensorPrivacyEnabled;
4939}
4940
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004941int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
4942 if (!mRegistered) {
4943 registerWithSensorPrivacyManager();
4944 }
4945
4946 Mutex::Autolock _l(mSensorPrivacyLock);
4947 return mCameraPrivacyState;
4948}
4949
Evan Seversond0b69922022-01-27 10:47:34 -08004950bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004951 if (!hasCameraPrivacyFeature()) {
4952 return false;
4953 }
Evan Seversond0b69922022-01-27 10:47:34 -08004954 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004955}
4956
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004957bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
4958 if (!hasCameraPrivacyFeature()) {
Jyoti Bhayana5882b032024-04-26 11:18:58 -07004959 return false;
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004960 }
4961 return mSpm.isCameraPrivacyEnabled(packageName);
4962}
4963
Evan Seversond0b69922022-01-27 10:47:34 -08004964binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004965 int toggleType, int sensor, bool enabled) {
4966 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
4967 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
4968 {
4969 Mutex::Autolock _l(mSensorPrivacyLock);
4970 mSensorPrivacyEnabled = enabled;
4971 }
4972 // if sensor privacy is enabled then block all clients from accessing the camera
4973 if (enabled) {
4974 sp<CameraService> service = mService.promote();
4975 if (service != nullptr) {
4976 service->blockAllClients();
4977 }
4978 }
4979 }
4980 return binder::Status::ok();
4981}
4982
4983binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
4984 int, int sensor, int state) {
4985 if (!flags::camera_privacy_allowlist()
4986 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
4987 return binder::Status::ok();
4988 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08004989 {
4990 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004991 mCameraPrivacyState = state;
4992 }
4993 sp<CameraService> service = mService.promote();
4994 if (!service) {
4995 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004996 }
4997 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004998 if (state == SensorPrivacyManager::ENABLED) {
4999 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08005000 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005001 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005002 }
5003 return binder::Status::ok();
5004}
5005
5006void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
5007 Mutex::Autolock _l(mSensorPrivacyLock);
5008 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
5009 mRegistered = false;
5010}
5011
Evan Severson09ab4002021-02-10 14:15:19 -08005012bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08005013 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
5014 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5015 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
5016 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5017 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08005018}
5019
Michael Grooverd1d435a2018-12-18 17:39:42 -08005020// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005021// CameraState
5022// ----------------------------------------------------------------------------
5023
Austin Borgered99f642023-06-01 16:51:35 -07005024CameraService::CameraState::CameraState(const std::string& id, int cost,
5025 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005026 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005027 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005028 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005029
5030CameraService::CameraState::~CameraState() {}
5031
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005032CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005033 Mutex::Autolock lock(mStatusLock);
5034 return mStatus;
5035}
5036
Austin Borgered99f642023-06-01 16:51:35 -07005037std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005038 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005039 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005040 return res;
5041}
5042
Ruben Brunkcc776712015-02-17 20:18:47 -08005043CameraParameters CameraService::CameraState::getShimParams() const {
5044 return mShimParams;
5045}
5046
5047void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5048 mShimParams = params;
5049}
5050
5051int CameraService::CameraState::getCost() const {
5052 return mCost;
5053}
5054
Austin Borgered99f642023-06-01 16:51:35 -07005055std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005056 return mConflicting;
5057}
5058
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005059SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5060 return mSystemCameraKind;
5061}
5062
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005063bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5064 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5065 != mPhysicalCameras.end();
5066}
5067
Austin Borgered99f642023-06-01 16:51:35 -07005068bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005069 Mutex::Autolock lock(mStatusLock);
5070 auto result = mUnavailablePhysicalIds.insert(physicalId);
5071 return result.second;
5072}
5073
Austin Borgered99f642023-06-01 16:51:35 -07005074bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005075 Mutex::Autolock lock(mStatusLock);
5076 auto count = mUnavailablePhysicalIds.erase(physicalId);
5077 return count > 0;
5078}
5079
Austin Borgered99f642023-06-01 16:51:35 -07005080void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005081 Mutex::Autolock lock(mStatusLock);
5082 mClientPackage = clientPackage;
5083}
5084
Austin Borgered99f642023-06-01 16:51:35 -07005085std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005086 Mutex::Autolock lock(mStatusLock);
5087 return mClientPackage;
5088}
5089
Ruben Brunkcc776712015-02-17 20:18:47 -08005090// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005091// ClientEventListener
5092// ----------------------------------------------------------------------------
5093
5094void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005095 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005096 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005097 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005098 if (basicClient.get() != nullptr) {
5099 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005100 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005101 static_cast<int>(basicClient->getClientUid()));
5102 }
5103}
5104
5105void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005106 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005107 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005108 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005109 if (basicClient.get() != nullptr) {
5110 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005111 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005112 static_cast<int>(basicClient->getClientUid()));
5113 }
5114}
5115
Ruben Brunk99e69712015-05-26 17:25:07 -07005116// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005117// CameraClientManager
5118// ----------------------------------------------------------------------------
5119
Ruben Brunk99e69712015-05-26 17:25:07 -07005120CameraService::CameraClientManager::CameraClientManager() {
5121 setListener(std::make_shared<ClientEventListener>());
5122}
5123
Ruben Brunkcc776712015-02-17 20:18:47 -08005124CameraService::CameraClientManager::~CameraClientManager() {}
5125
5126sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005127 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005128 auto descriptor = get(id);
5129 if (descriptor == nullptr) {
5130 return sp<BasicClient>{nullptr};
5131 }
5132 return descriptor->getValue();
5133}
5134
Austin Borgered99f642023-06-01 16:51:35 -07005135std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005136 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005137 std::ostringstream ret;
5138 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005139 bool hasAny = false;
5140 for (auto& i : all) {
5141 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005142 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005143 int32_t cost = i->getCost();
5144 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005145 int32_t score = i->getPriority().getScore();
5146 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005147 auto conflicting = i->getConflicting();
5148 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005149 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005150 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005151 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005152 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005153 uid_t clientUid = clientSp->getClientUid();
5154 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005155 }
Austin Borgered99f642023-06-01 16:51:35 -07005156 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5157 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005158
Ruben Brunk6267b532015-04-30 17:44:07 -07005159 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005160 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005161 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005162 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005163 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005164 }
5165
Austin Borgered99f642023-06-01 16:51:35 -07005166 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005167 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005168 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005169 }
Austin Borgered99f642023-06-01 16:51:35 -07005170 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005171 }
Austin Borgered99f642023-06-01 16:51:35 -07005172 if (hasAny) ret << "\n";
5173 ret << "]\n";
5174 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005175}
5176
5177CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005178 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5179 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005180 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005181
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005182 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005183 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005184
Austin Borgered99f642023-06-01 16:51:35 -07005185 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005186 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5187 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005188}
5189
5190CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005191 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005192 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005193 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005194 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005195 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5196 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005197}
5198
5199// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005200// InjectionStatusListener
5201// ----------------------------------------------------------------------------
5202
5203void CameraService::InjectionStatusListener::addListener(
5204 const sp<ICameraInjectionCallback>& callback) {
5205 Mutex::Autolock lock(mListenerLock);
5206 if (mCameraInjectionCallback) return;
5207 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5208 if (res == OK) {
5209 mCameraInjectionCallback = callback;
5210 }
5211}
5212
5213void CameraService::InjectionStatusListener::removeListener() {
5214 Mutex::Autolock lock(mListenerLock);
5215 if (mCameraInjectionCallback == nullptr) {
5216 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5217 return;
5218 }
5219 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5220 mCameraInjectionCallback = nullptr;
5221}
5222
5223void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005224 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005225 if (mCameraInjectionCallback == nullptr) {
5226 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5227 return;
5228 }
Cliff Wud3a05312021-04-26 23:07:31 +08005229
5230 switch (err) {
5231 case -ENODEV:
5232 mCameraInjectionCallback->onInjectionError(
5233 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5234 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005235 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005236 break;
5237 case -EBUSY:
5238 mCameraInjectionCallback->onInjectionError(
5239 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5240 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005241 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005242 break;
5243 case DEAD_OBJECT:
5244 mCameraInjectionCallback->onInjectionError(
5245 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5246 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005247 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005248 break;
5249 case INVALID_OPERATION:
5250 mCameraInjectionCallback->onInjectionError(
5251 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5252 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005253 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005254 break;
5255 case UNKNOWN_TRANSACTION:
5256 mCameraInjectionCallback->onInjectionError(
5257 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5258 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005259 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005260 break;
5261 default:
5262 mCameraInjectionCallback->onInjectionError(
5263 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5264 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005265 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005266 }
Cliff Wud8cae102021-03-11 01:37:42 +08005267}
5268
5269void CameraService::InjectionStatusListener::binderDied(
5270 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005271 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5272 auto parent = mParent.promote();
5273 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005274 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5275 if (clientDescriptor != nullptr) {
5276 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5277 baseClientPtr->stopInjection();
5278 }
Cliff Wu3b268182021-07-06 15:44:43 +08005279 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005280 }
5281}
5282
5283// ----------------------------------------------------------------------------
5284// CameraInjectionSession
5285// ----------------------------------------------------------------------------
5286
5287binder::Status CameraService::CameraInjectionSession::stopInjection() {
5288 Mutex::Autolock lock(mInjectionSessionLock);
5289 auto parent = mParent.promote();
5290 if (parent == nullptr) {
5291 ALOGE("CameraInjectionSession: Parent is gone");
5292 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5293 "Camera service encountered error");
5294 }
Cliff Wud3a05312021-04-26 23:07:31 +08005295
5296 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005297 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5298 if (clientDescriptor != nullptr) {
5299 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5300 res = baseClientPtr->stopInjection();
5301 if (res != OK) {
5302 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5303 " ret != NO_ERROR: %d", res);
5304 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5305 "Camera session encountered error");
5306 }
5307 }
Cliff Wu3b268182021-07-06 15:44:43 +08005308 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005309 return binder::Status::ok();
5310}
5311
5312// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005313
5314static const int kDumpLockRetries = 50;
5315static const int kDumpLockSleep = 60000;
5316
5317static bool tryLock(Mutex& mutex)
5318{
5319 bool locked = false;
5320 for (int i = 0; i < kDumpLockRetries; ++i) {
5321 if (mutex.tryLock() == NO_ERROR) {
5322 locked = true;
5323 break;
5324 }
5325 usleep(kDumpLockSleep);
5326 }
5327 return locked;
5328}
5329
Rucha Katakwardf223072021-06-15 10:21:00 -07005330void CameraService::cacheDump() {
5331 if (mMemFd != -1) {
5332 const Vector<String16> args;
5333 ATRACE_CALL();
5334 // Acquiring service lock here will avoid the deadlock since
5335 // cacheDump will not be called during the second disconnect.
5336 Mutex::Autolock lock(mServiceLock);
5337
5338 Mutex::Autolock l(mCameraStatesLock);
5339 // Start collecting the info for open sessions and store it in temp file.
5340 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005341 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005342 auto clientDescriptor = mActiveClientManager.get(cameraId);
5343 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005344 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005345 // Log the current open session info before device is disconnected.
5346 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5347 }
5348 }
5349 }
5350}
5351
Mathias Agopian65ab4712010-07-14 17:59:35 -07005352status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005353 ATRACE_CALL();
5354
Austin Borgered99f642023-06-01 16:51:35 -07005355 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005356 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005357 getCallingPid(),
5358 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005359 return NO_ERROR;
5360 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005361 bool locked = tryLock(mServiceLock);
5362 // failed to lock - CameraService is probably deadlocked
5363 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005364 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005365 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005366
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005367 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005368 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005369
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005370 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005371 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005372
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005373 if (locked) mServiceLock.unlock();
5374 return NO_ERROR;
5375 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005376 dprintf(fd, "\n== Service global info: ==\n\n");
5377 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005378 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005379 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5380 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005381 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5382 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5383 }
Austin Borgered99f642023-06-01 16:51:35 -07005384 std::string activeClientString = mActiveClientManager.toString();
5385 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5386 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005387 if (mStreamUseCaseOverrides.size() > 0) {
5388 dprintf(fd, "Active stream use case overrides:");
5389 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5390 dprintf(fd, " %" PRId64, useCaseOverride);
5391 }
5392 dprintf(fd, "\n");
5393 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005394
5395 dumpEventLog(fd);
5396
5397 bool stateLocked = tryLock(mCameraStatesLock);
5398 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005399 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005400 }
5401
Emilian Peevbd8c5032018-02-14 23:05:40 +00005402 int argSize = args.size();
5403 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005404 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005405 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005406 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005407 }
5408 break;
5409 }
5410 }
5411
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005412 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005413 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005414
Austin Borgered99f642023-06-01 16:51:35 -07005415 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005416
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005417 CameraParameters p = state.second->getShimParams();
5418 if (!p.isEmpty()) {
5419 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5420 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005421 }
5422
5423 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005424 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005425 // log the current open session info
5426 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005427 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005428 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005429 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005430
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005431 }
5432
5433 if (stateLocked) mCameraStatesLock.unlock();
5434
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005435 if (locked) mServiceLock.unlock();
5436
Emilian Peevf53f66e2017-04-11 14:29:43 +01005437 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005438
5439 dprintf(fd, "\n== Vendor tags: ==\n\n");
5440
5441 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5442 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005443 sp<VendorTagDescriptorCache> cache =
5444 VendorTagDescriptorCache::getGlobalVendorTagCache();
5445 if (cache == NULL) {
5446 dprintf(fd, "No vendor tags.\n");
5447 } else {
5448 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5449 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005450 } else {
5451 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5452 }
5453
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005454 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005455 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005456 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005457
5458 // Process dump arguments, if any
5459 int n = args.size();
5460 String16 verboseOption("-v");
5461 String16 unreachableOption("--unreachable");
5462 for (int i = 0; i < n; i++) {
5463 if (args[i] == verboseOption) {
5464 // change logging level
5465 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005466 std::string levelStr = toStdString(args[i+1]);
5467 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005468 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005469 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005470 } else if (args[i] == unreachableOption) {
5471 // Dump memory analysis
5472 // TODO - should limit be an argument parameter?
5473 UnreachableMemoryInfo info;
5474 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5475 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005476 dprintf(fd, "\n== Unable to dump unreachable memory. "
5477 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005478 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005479 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005480 std::string s = info.ToString(/*log_contents*/ true);
5481 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005482 }
5483 }
5484 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005485
5486 bool serviceLocked = tryLock(mServiceLock);
5487
5488 // Dump info from previous open sessions.
5489 // Reposition the offset to beginning of the file before reading
5490
5491 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5492 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5493 ssize_t size_read;
5494 char buf[4096];
5495 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5496 // Read data from file to a small buffer and write it to fd.
5497 write(fd, buf, size_read);
5498 if (size_read == -1) {
5499 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5500 break;
5501 }
5502 }
5503 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5504 } else {
5505 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5506 }
5507
5508 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005509 return NO_ERROR;
5510}
5511
Rucha Katakwardf223072021-06-15 10:21:00 -07005512void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005513 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005514 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005515 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005516 getFormattedCurrentTime().c_str(),
5517 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005518 dprintf(fd, " Client priority score: %d state: %d\n",
5519 clientDescriptor->getPriority().getScore(),
5520 clientDescriptor->getPriority().getState());
5521 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5522
5523 auto client = clientDescriptor->getValue();
5524 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005525 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005526
5527 client->dumpClient(fd, args);
5528}
5529
Austin Borgered99f642023-06-01 16:51:35 -07005530void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005531 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005532 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005533}
5534
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005535void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005536 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005537
5538 Mutex::Autolock l(mLogLock);
5539 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005540 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005541 }
5542
5543 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005544 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005545 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005546 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005547 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005548 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005549}
5550
Austin Borgered99f642023-06-01 16:51:35 -07005551void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005552 Mutex::Autolock lock(mLogLock);
5553 if (!isClientWatchedLocked(client)) { return; }
5554
5555 std::vector<std::string> dumpVector;
5556 client->dumpWatchedEventsToVector(dumpVector);
5557
5558 if (dumpVector.empty()) { return; }
5559
Austin Borgered99f642023-06-01 16:51:35 -07005560 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005561
Austin Borgered99f642023-06-01 16:51:35 -07005562 std::string currentTime = getFormattedCurrentTime();
5563 dumpString << "Cached @ ";
5564 dumpString << currentTime;
5565 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005566
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005567 size_t i = dumpVector.size();
5568
5569 // Store the string in reverse order (latest last)
5570 while (i > 0) {
5571 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005572 dumpString << cameraId;
5573 dumpString << ":";
5574 dumpString << client->getPackageName();
5575 dumpString << " ";
5576 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005577 }
5578
Austin Borgered99f642023-06-01 16:51:35 -07005579 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005580}
5581
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005582void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005583 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005584 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5585 if (mTorchClientMap[i] == who) {
5586 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005587 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005588 status_t res = mFlashlight->setTorchMode(cameraId, false);
5589 if (res) {
5590 ALOGE("%s: torch client died but couldn't turn off torch: "
5591 "%s (%d)", __FUNCTION__, strerror(-res), res);
5592 return;
5593 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005594 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005595 break;
5596 }
5597 }
5598}
5599
Ruben Brunkcc776712015-02-17 20:18:47 -08005600/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005601
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005602 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005603 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5604 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005605 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005606 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005607 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005608
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005609 // check torch client
5610 handleTorchClientBinderDied(who);
5611
5612 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005613 if(!evictClientIdByRemote(who)) {
5614 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005615 return;
5616 }
5617
Ruben Brunkcc776712015-02-17 20:18:47 -08005618 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5619 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005620}
5621
Austin Borgered99f642023-06-01 16:51:35 -07005622void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005623 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005624}
5625
Austin Borgered99f642023-06-01 16:51:35 -07005626void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005627 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005628 // Do not lock mServiceLock here or can get into a deadlock from
5629 // connect() -> disconnect -> updateStatus
5630
5631 auto state = getCameraState(cameraId);
5632
5633 if (state == nullptr) {
5634 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005635 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005636 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005637 }
5638
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005639 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5640 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5641 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005642 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005643 return;
5644 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005645
Biswarup Pal37a75182024-01-16 15:53:35 +00005646 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5647 CameraMetadata cameraInfo;
5648 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00005649 cameraId, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +00005650 if (res != OK) {
5651 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5652 __FUNCTION__, cameraId.c_str());
5653 } else {
5654 int32_t deviceId = getDeviceId(cameraInfo);
5655 if (deviceId != kDefaultDeviceId) {
5656 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5657 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5658 static_cast<camera_metadata_enum_android_lens_facing_t>(
5659 lensFacingEntry.data.u8[0]);
5660 std::string mappedCameraId;
5661 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5662 mappedCameraId = kVirtualDeviceBackCameraId;
5663 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5664 mappedCameraId = kVirtualDeviceFrontCameraId;
5665 } else {
5666 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5667 __func__);
5668 }
5669 if (!mappedCameraId.empty()) {
5670 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5671 }
5672 }
5673 }
5674 }
5675
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005676 // Collect the logical cameras without holding mStatusLock in updateStatus
5677 // as that can lead to a deadlock(b/162192331).
5678 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005679 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005680 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005681 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005682 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005683 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005684 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5685 auto [deviceId, mappedCameraId] =
5686 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005687
Biswarup Pal37a75182024-01-16 15:53:35 +00005688 if (status != StatusInternal::ENUMERATING) {
5689 // Update torch status if it has a flash unit.
5690 Mutex::Autolock al(mTorchStatusMutex);
5691 TorchModeStatus torchStatus;
5692 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5693 NAME_NOT_FOUND) {
5694 TorchModeStatus newTorchStatus =
5695 status == StatusInternal::PRESENT ?
5696 TorchModeStatus::AVAILABLE_OFF :
5697 TorchModeStatus::NOT_AVAILABLE;
5698 if (torchStatus != newTorchStatus) {
5699 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5700 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005701 }
5702 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005703
Biswarup Pal37a75182024-01-16 15:53:35 +00005704 Mutex::Autolock lock(mStatusListenerLock);
5705 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5706 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005707
Biswarup Pal37a75182024-01-16 15:53:35 +00005708 for (auto& listener : mListenerList) {
5709 bool isVendorListener = listener->isVendorListener();
5710 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5711 listener->getListenerPid(), listener->getListenerUid())) {
5712 ALOGV("Skipping discovery callback for system-only camera device %s",
5713 cameraId.c_str());
5714 continue;
5715 }
5716
5717 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5718 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005719 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005720 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005721 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5722 ret.exceptionCode());
5723 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005724 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005725}
5726
Austin Borgered99f642023-06-01 16:51:35 -07005727void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5728 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005729 auto state = getCameraState(cameraId);
5730 if (state == nullptr) {
5731 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005732 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005733 return;
5734 }
5735 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005736 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005737 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005738 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005739 }
5740
Biswarup Pal37a75182024-01-16 15:53:35 +00005741 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5742 auto [deviceId, mappedCameraId] =
5743 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5744
Shuzhen Wang695044d2020-03-06 09:02:23 -08005745 Mutex::Autolock lock(mStatusListenerLock);
5746
5747 for (const auto& it : mListenerList) {
5748 if (!it->isOpenCloseCallbackAllowed()) {
5749 continue;
5750 }
5751
5752 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005753 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005754 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5755 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005756 } else {
Biswarup Pal37a75182024-01-16 15:53:35 +00005757 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005758 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005759
5760 it->handleBinderStatus(ret,
5761 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5762 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005763 }
5764}
5765
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005766template<class Func>
5767void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005768 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005769 std::initializer_list<StatusInternal> rejectSourceStates,
5770 Func onStatusUpdatedLocked) {
5771 Mutex::Autolock lock(mStatusLock);
5772 StatusInternal oldStatus = mStatus;
5773 mStatus = status;
5774
5775 if (oldStatus == status) {
5776 return;
5777 }
5778
5779 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005780 cameraId.c_str(), oldStatus, status);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005781
5782 if (oldStatus == StatusInternal::NOT_PRESENT &&
5783 (status != StatusInternal::PRESENT &&
5784 status != StatusInternal::ENUMERATING)) {
5785
5786 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5787 __FUNCTION__);
5788 mStatus = oldStatus;
5789 return;
5790 }
5791
5792 /**
5793 * Sometimes we want to conditionally do a transition.
5794 * For example if a client disconnects, we want to go to PRESENT
5795 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5796 */
5797 for (auto& rejectStatus : rejectSourceStates) {
5798 if (oldStatus == rejectStatus) {
5799 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005800 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005801 mStatus = oldStatus;
5802 return;
5803 }
5804 }
5805
5806 onStatusUpdatedLocked(cameraId, status);
5807}
5808
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005809status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005810 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005811 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005812 if (!status) {
5813 return BAD_VALUE;
5814 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005815 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5816 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005817 // invalid camera ID or the camera doesn't have a flash unit
5818 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005819 }
5820
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005821 *status = mTorchStatusMap.valueAt(index);
5822 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005823}
5824
Austin Borgered99f642023-06-01 16:51:35 -07005825status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005826 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005827 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5828 if (index == NAME_NOT_FOUND) {
5829 return BAD_VALUE;
5830 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005831 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005832
5833 return OK;
5834}
5835
Austin Borgered99f642023-06-01 16:51:35 -07005836std::list<std::string> CameraService::getLogicalCameras(
5837 const std::string& physicalCameraId) {
5838 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005839 Mutex::Autolock lock(mCameraStatesLock);
5840 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005841 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5842 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005843 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005844 }
5845 return retList;
5846}
5847
5848void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005849 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00005850 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005851 // mStatusListenerLock is expected to be locked
5852 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005853 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005854 // Note: we check only the deviceKind of the physical camera id
5855 // since, logical camera ids and their physical camera ids are
5856 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005857 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5858 listener->getListenerPid(), listener->getListenerUid())) {
5859 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005860 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005861 continue;
5862 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005863 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00005864 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005865 listener->handleBinderStatus(ret,
5866 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5867 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5868 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005869 }
5870 }
5871}
5872
Svet Ganova453d0d2018-01-11 15:37:58 -08005873void CameraService::blockClientsForUid(uid_t uid) {
5874 const auto clients = mActiveClientManager.getAll();
5875 for (auto& current : clients) {
5876 if (current != nullptr) {
5877 const auto basicClient = current->getValue();
5878 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5879 basicClient->block();
5880 }
5881 }
5882 }
5883}
5884
Michael Grooverd1d435a2018-12-18 17:39:42 -08005885void CameraService::blockAllClients() {
5886 const auto clients = mActiveClientManager.getAll();
5887 for (auto& current : clients) {
5888 if (current != nullptr) {
5889 const auto basicClient = current->getValue();
5890 if (basicClient.get() != nullptr) {
5891 basicClient->block();
5892 }
5893 }
5894 }
5895}
5896
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005897void CameraService::blockPrivacyEnabledClients() {
5898 const auto clients = mActiveClientManager.getAll();
5899 for (auto& current : clients) {
5900 if (current != nullptr) {
5901 const auto basicClient = current->getValue();
5902 if (basicClient.get() != nullptr) {
5903 std::string pkgName = basicClient->getPackageName();
5904 bool cameraPrivacyEnabled =
5905 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
5906 if (cameraPrivacyEnabled) {
5907 basicClient->block();
5908 }
5909 }
5910 }
5911 }
5912}
5913
Svet Ganova453d0d2018-01-11 15:37:58 -08005914// NOTE: This is a remote API - make sure all args are validated
5915status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005916 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005917 return PERMISSION_DENIED;
5918 }
5919 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5920 return BAD_VALUE;
5921 }
Austin Borgered99f642023-06-01 16:51:35 -07005922 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005923 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005924 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005925 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005926 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005927 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005928 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005929 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005930 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005931 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005932 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005933 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005934 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005935 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005936 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005937 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005938 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005939 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005940 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005941 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005942 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005943 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005944 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005945 handleClearStreamUseCaseOverrides();
5946 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005947 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005948 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07005949 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005950 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07005951 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00005952 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07005953 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005954 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005955 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005956 }
5957 printHelp(err);
5958 return BAD_VALUE;
5959}
5960
5961status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005962 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005963
Svet Ganova453d0d2018-01-11 15:37:58 -08005964 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07005965 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005966 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07005967 } else if ((args[2] != toString16("idle"))) {
5968 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08005969 return BAD_VALUE;
5970 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005971
5972 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005973 if (args.size() >= 5 && args[3] == toString16("--user")) {
5974 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005975 }
5976
5977 uid_t uid;
5978 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5979 return BAD_VALUE;
5980 }
5981
5982 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005983 return NO_ERROR;
5984}
5985
5986status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005987 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005988
5989 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005990 if (args.size() >= 4 && args[2] == toString16("--user")) {
5991 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005992 }
5993
5994 uid_t uid;
5995 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005996 return BAD_VALUE;
5997 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005998
5999 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08006000 return NO_ERROR;
6001}
6002
6003status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006004 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006005
6006 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006007 if (args.size() >= 4 && args[2] == toString16("--user")) {
6008 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006009 }
6010
6011 uid_t uid;
6012 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006013 return BAD_VALUE;
6014 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006015
6016 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006017 return dprintf(out, "active\n");
6018 } else {
6019 return dprintf(out, "idle\n");
6020 }
6021}
6022
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006023status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006024 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006025 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
6026 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
6027 Mutex::Autolock lock(mServiceLock);
6028
6029 mOverrideRotateAndCropMode = rotateValue;
6030
6031 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_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->setRotateAndCropOverride(rotateValue);
6039 }
6040 }
6041 }
6042
6043 return OK;
6044}
6045
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006046status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6047 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006048 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006049 if ((*end != '\0') ||
6050 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6051 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6052 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6053 return BAD_VALUE;
6054 }
6055
6056 Mutex::Autolock lock(mServiceLock);
6057 mOverrideAutoframingMode = autoframingValue;
6058
6059 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6060
6061 const auto clients = mActiveClientManager.getAll();
6062 for (auto& current : clients) {
6063 if (current != nullptr) {
6064 const auto basicClient = current->getValue();
6065 if (basicClient.get() != nullptr) {
6066 basicClient->setAutoframingOverride(autoframingValue);
6067 }
6068 }
6069 }
6070
6071 return OK;
6072}
6073
Ravneetaeb20dc2022-03-30 05:33:03 +00006074status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006075 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006076
6077 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6078
6079 Mutex::Autolock lock(mServiceLock);
6080
6081 mCameraServiceWatchdogEnabled = enableWatchdog;
6082
6083 const auto clients = mActiveClientManager.getAll();
6084 for (auto& current : clients) {
6085 if (current != nullptr) {
6086 const auto basicClient = current->getValue();
6087 if (basicClient.get() != nullptr) {
6088 basicClient->setCameraServiceWatchdog(enableWatchdog);
6089 }
6090 }
6091 }
6092
6093 return OK;
6094}
6095
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006096status_t CameraService::handleGetRotateAndCrop(int out) {
6097 Mutex::Autolock lock(mServiceLock);
6098
6099 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6100}
6101
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006102status_t CameraService::handleGetAutoframing(int out) {
6103 Mutex::Autolock lock(mServiceLock);
6104
6105 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6106}
6107
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006108status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6109 char *endPtr;
6110 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006111 std::string maskString = toStdString(args[1]);
6112 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006113
6114 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006115 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006116 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6117
6118 Mutex::Autolock lock(mServiceLock);
6119
6120 mImageDumpMask = maskValue;
6121
6122 return OK;
6123}
6124
6125status_t CameraService::handleGetImageDumpMask(int out) {
6126 Mutex::Autolock lock(mServiceLock);
6127
6128 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6129}
6130
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006131status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006132 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006133 if (errno != 0) return BAD_VALUE;
6134
6135 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6136 Mutex::Autolock lock(mServiceLock);
6137
6138 mOverrideCameraMuteMode = (muteValue == 1);
6139
6140 const auto clients = mActiveClientManager.getAll();
6141 for (auto& current : clients) {
6142 if (current != nullptr) {
6143 const auto basicClient = current->getValue();
6144 if (basicClient.get() != nullptr) {
6145 if (basicClient->supportsCameraMute()) {
6146 basicClient->setCameraMute(mOverrideCameraMuteMode);
6147 }
6148 }
6149 }
6150 }
6151
6152 return OK;
6153}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006154
Shuzhen Wang16610a62022-12-15 22:38:07 -08006155status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6156 std::vector<int64_t> useCasesOverride;
6157 for (size_t i = 1; i < args.size(); i++) {
6158 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006159 std::string arg = toStdString(args[i]);
6160 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006161 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006162 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006163 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006164 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006165 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006166 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006167 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006168 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006169 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006170 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006171 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006172 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006173 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6174 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006175 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006176 return BAD_VALUE;
6177 }
6178 useCasesOverride.push_back(useCase);
6179 }
6180
6181 Mutex::Autolock lock(mServiceLock);
6182 mStreamUseCaseOverrides = std::move(useCasesOverride);
6183
6184 return OK;
6185}
6186
6187void CameraService::handleClearStreamUseCaseOverrides() {
6188 Mutex::Autolock lock(mServiceLock);
6189 mStreamUseCaseOverrides.clear();
6190}
6191
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006192status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6193 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006194 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006195 if ((*end != '\0') ||
6196 (zoomOverrideValue != -1 &&
6197 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6198 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6199 return BAD_VALUE;
6200 }
6201
6202 Mutex::Autolock lock(mServiceLock);
6203 mZoomOverrideValue = zoomOverrideValue;
6204
6205 const auto clients = mActiveClientManager.getAll();
6206 for (auto& current : clients) {
6207 if (current != nullptr) {
6208 const auto basicClient = current->getValue();
6209 if (basicClient.get() != nullptr) {
6210 if (basicClient->supportsZoomOverride()) {
6211 basicClient->setZoomOverride(mZoomOverrideValue);
6212 }
6213 }
6214 }
6215 }
6216
6217 return OK;
6218}
6219
Avichal Rakesh84147132021-11-11 17:47:11 -08006220status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006221 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006222 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006223 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006224 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006225 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006226 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006227 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006228 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006229 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006230 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006231 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006232 dprintf(outFd, "Camera service watch commands:\n"
6233 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6234 " starts watching the provided tags for clients with provided package\n"
6235 " recognizes tag shorthands like '3a'\n"
6236 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006237 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006238 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006239 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006240 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006241 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006242 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006243 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006244}
6245
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006246status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6247 Mutex::Autolock lock(mLogLock);
6248 size_t tagsIdx; // index of '-m'
6249 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006250 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006251 if (tagsIdx < args.size() - 1) {
6252 tags = args[tagsIdx + 1];
6253 } else {
6254 dprintf(outFd, "No tags provided.\n");
6255 return BAD_VALUE;
6256 }
6257
6258 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006259 // watch all clients if no clients are provided
6260 String16 clients = toString16(kWatchAllClientsFlag);
6261 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006262 clientsIdx++);
6263 if (clientsIdx < args.size() - 1) {
6264 clients = args[clientsIdx + 1];
6265 }
Austin Borgered99f642023-06-01 16:51:35 -07006266 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006267
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006268 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006269 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006270
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006271 bool serviceLock = tryLock(mServiceLock);
6272 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006273 auto cameraClients = mActiveClientManager.getAll();
6274 for (const auto &clientDescriptor: cameraClients) {
6275 if (clientDescriptor == nullptr) { continue; }
6276 sp<BasicClient> client = clientDescriptor->getValue();
6277 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006278
6279 if (isClientWatchedLocked(client.get())) {
6280 client->startWatchingTags(mMonitorTags, outFd);
6281 numWatchedClients++;
6282 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006283 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006284 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6285
6286 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006287 return OK;
6288}
6289
6290status_t CameraService::stopWatchingTags(int outFd) {
6291 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006292 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006293 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006294
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006295 mWatchedClientPackages.clear();
6296 mWatchedClientsDumpCache.clear();
6297
6298 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006299 auto cameraClients = mActiveClientManager.getAll();
6300 for (const auto &clientDescriptor : cameraClients) {
6301 if (clientDescriptor == nullptr) { continue; }
6302 sp<BasicClient> client = clientDescriptor->getValue();
6303 if (client.get() == nullptr) { continue; }
6304 client->stopWatchingTags(outFd);
6305 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006306 dprintf(outFd, "Stopped watching all clients.\n");
6307 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006308 return OK;
6309}
6310
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006311status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6312 Mutex::Autolock lock(mLogLock);
6313 size_t clearedSize = mWatchedClientsDumpCache.size();
6314 mWatchedClientsDumpCache.clear();
6315 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6316 return OK;
6317}
6318
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006319status_t CameraService::printWatchedTags(int outFd) {
6320 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006321 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006322
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006323 bool printedSomething = false; // tracks if any monitoring information was printed
6324 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006325
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006326 bool serviceLock = tryLock(mServiceLock);
6327 // get all watched clients that are currently connected
6328 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6329 if (clientDescriptor == nullptr) { continue; }
6330
6331 sp<BasicClient> client = clientDescriptor->getValue();
6332 if (client.get() == nullptr) { continue; }
6333 if (!isClientWatchedLocked(client.get())) { continue; }
6334
6335 std::vector<std::string> dumpVector;
6336 client->dumpWatchedEventsToVector(dumpVector);
6337
6338 size_t printIdx = dumpVector.size();
6339 if (printIdx == 0) {
6340 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006341 }
6342
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006343 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006344 const std::string &cameraId = clientDescriptor->getKey();
6345 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006346 while(printIdx > 0) {
6347 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006348 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006349 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006350 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006351 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006352 printedSomething = true;
6353
6354 connectedMonitoredClients.emplace(client->getPackageName());
6355 }
6356 if (serviceLock) { mServiceLock.unlock(); }
6357
6358 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6359 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006360 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006361 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6362 continue;
6363 }
6364
Austin Borgered99f642023-06-01 16:51:35 -07006365 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006366 dprintf(outFd, "%s\n", kv.second.c_str());
6367 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006368 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006369
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006370 if (!printedSomething) {
6371 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006372 }
6373
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006374 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006375}
6376
Avichal Rakesh84147132021-11-11 17:47:11 -08006377// Print all events in vector `events' that came after lastPrintedEvent
6378void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006379 const std::string &cameraId,
6380 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006381 const std::vector<std::string> &events,
6382 const std::string &lastPrintedEvent) {
6383 if (events.empty()) { return; }
6384
6385 // index of lastPrintedEvent in events.
6386 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6387 size_t lastPrintedIdx;
6388 for (lastPrintedIdx = 0;
6389 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6390 lastPrintedIdx++);
6391
6392 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6393
Avichal Rakesh84147132021-11-11 17:47:11 -08006394 // print events in chronological order (latest event last)
6395 size_t idxToPrint = lastPrintedIdx;
6396 do {
6397 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006398 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6399 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006400 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006401}
6402
6403// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6404// command should be interrupted if the user presses the return key, or if user loses any way to
6405// signal interrupt.
6406// If timeoutMs == 0, this function will always return false
6407bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6408 struct timeval startTime;
6409 int startTimeError = gettimeofday(&startTime, nullptr);
6410 if (startTimeError) {
6411 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6412 return true;
6413 }
6414
6415 const nfds_t numFds = 1;
6416 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6417
6418 struct timeval currTime;
6419 char buffer[2];
6420 while(true) {
6421 int currTimeError = gettimeofday(&currTime, nullptr);
6422 if (currTimeError) {
6423 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6424 return true;
6425 }
6426
6427 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6428 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6429 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6430
6431 if (remainingTimeMs <= 0) {
6432 // No user interrupt within timeoutMs, don't interrupt watch command
6433 return false;
6434 }
6435
6436 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6437 if (numFdsUpdated < 0) {
6438 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6439 return true;
6440 }
6441
6442 if (numFdsUpdated == 0) {
6443 // No user input within timeoutMs, don't interrupt watch command
6444 return false;
6445 }
6446
6447 if (!(pollFd.revents & POLLIN)) {
6448 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6449 return true;
6450 }
6451
6452 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6453 if (sizeRead < 0) {
6454 dprintf(outFd, "Error reading user input. Exiting.\n");
6455 return true;
6456 }
6457
6458 if (sizeRead == 0) {
6459 // Reached end of input fd (can happen if input is piped)
6460 // User has no way to signal an interrupt, so interrupt here
6461 return true;
6462 }
6463
6464 if (buffer[0] == '\n') {
6465 // User pressed return, interrupt watch command.
6466 return true;
6467 }
6468 }
6469}
6470
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006471status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6472 int inFd, int outFd) {
6473 // Figure out refresh interval, if present in args
6474 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006475 if (args.size() > 2) {
6476 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006477 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006478 intervalIdx++);
6479
6480 size_t intervalValIdx = intervalIdx + 1;
6481 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006482 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006483 if (errno) { return BAD_VALUE; }
6484 }
6485 }
6486
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006487 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6488 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006489
Avichal Rakesh84147132021-11-11 17:47:11 -08006490 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006491 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006492
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006493 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006494 bool serviceLock = tryLock(mServiceLock);
6495 auto cameraClients = mActiveClientManager.getAll();
6496 if (serviceLock) { mServiceLock.unlock(); }
6497
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006498 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006499 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006500 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006501
6502 sp<BasicClient> client = clientDescriptor->getValue();
6503 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006504 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006505
Austin Borgered99f642023-06-01 16:51:35 -07006506 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006507 // This also initializes the map entries with an empty string
6508 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6509
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006510 std::vector<std::string> latestEvents;
6511 client->dumpWatchedEventsToVector(latestEvents);
6512
6513 if (!latestEvents.empty()) {
6514 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006515 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006516 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006517 latestEvents,
6518 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006519 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006520 }
6521 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006522 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006523 break;
6524 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006525 }
6526 return OK;
6527}
6528
Austin Borgered99f642023-06-01 16:51:35 -07006529void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006530 mWatchedClientPackages.clear();
6531
Austin Borgered99f642023-06-01 16:51:35 -07006532 std::istringstream iss(clients);
6533 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006534
Austin Borgered99f642023-06-01 16:51:35 -07006535 while (std::getline(iss, nextClient, ',')) {
6536 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006537 // Don't need to track any other package if 'all' is present
6538 mWatchedClientPackages.clear();
6539 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6540 break;
6541 }
6542
6543 // track package names
6544 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006545 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006546}
6547
Svet Ganova453d0d2018-01-11 15:37:58 -08006548status_t CameraService::printHelp(int out) {
6549 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006550 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6551 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6552 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006553 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6554 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6555 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006556 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6557 " Valid values 0=false, 1=true, 2=auto\n"
6558 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006559 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6560 " Valid values 0=OFF, 1=ON for JPEG\n"
6561 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006562 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006563 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6564 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6565 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6566 " on. In case the number of usecases is smaller than the number of streams, the\n"
6567 " last use case is assigned to all the remaining streams. In case of multiple\n"
6568 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6569 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6570 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6571 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006572 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6573 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006574 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6575 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006576 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006577 " help print this message\n");
6578}
6579
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006580bool CameraService::isClientWatched(const BasicClient *client) {
6581 Mutex::Autolock lock(mLogLock);
6582 return isClientWatchedLocked(client);
6583}
6584
6585bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6586 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6587 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6588}
6589
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006590int32_t CameraService::updateAudioRestriction() {
6591 Mutex::Autolock lock(mServiceLock);
6592 return updateAudioRestrictionLocked();
6593}
6594
6595int32_t CameraService::updateAudioRestrictionLocked() {
6596 int32_t mode = 0;
6597 // iterate through all active client
6598 for (const auto& i : mActiveClientManager.getAll()) {
6599 const auto clientSp = i->getValue();
6600 mode |= clientSp->getAudioRestriction();
6601 }
6602
6603 bool modeChanged = (mAudioRestriction != mode);
6604 mAudioRestriction = mode;
6605 if (modeChanged) {
6606 mAppOps.setCameraAudioRestriction(mode);
6607 }
6608 return mode;
6609}
6610
Austin Borgered99f642023-06-01 16:51:35 -07006611status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006612 sp<BasicClient> clientSp) {
6613 std::unique_ptr<AutoConditionLock> lock =
6614 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6615 status_t res = NO_ERROR;
6616 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006617 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006618 mInjectionStatusListener->notifyInjectionError(
6619 externalCamId, UNKNOWN_TRANSACTION);
6620 clientSp->notifyError(
6621 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6622 CaptureResultExtras());
6623
6624 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6625 // other clients from connecting in mServiceLockWrapper if held
6626 mServiceLock.unlock();
6627
6628 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006629 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006630 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006631 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006632
6633 // Reacquire mServiceLock
6634 mServiceLock.lock();
6635 }
6636
6637 return res;
6638}
6639
Cliff Wud3a05312021-04-26 23:07:31 +08006640void CameraService::clearInjectionParameters() {
6641 {
6642 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006643 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006644 mInjectionInternalCamId = "";
6645 }
6646 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006647 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006648}
6649
Biswarup Pal37a75182024-01-16 15:53:35 +00006650} // namespace android