blob: c154bc01fb9de127d755fc18fe4e58e8a65ed305 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080024#include <cstdlib>
Ruben Brunkcc776712015-02-17 20:18:47 -080025#include <cstring>
26#include <ctime>
Austin Borgered99f642023-06-01 16:51:35 -070027#include <iostream>
28#include <sstream>
Ruben Brunkcc776712015-02-17 20:18:47 -080029#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080031#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <pthread.h>
Avichal Rakesh84147132021-11-11 17:47:11 -080033#include <poll.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070034
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080035#include <android/hardware/ICamera.h>
36#include <android/hardware/ICameraClient.h>
37
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -070038#include <aidl/AidlCameraService.h>
Alex Deymo9c2a2c22016-08-25 11:59:14 -070039#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080040#include <android-base/parseint.h>
Biswarup Pal37a75182024-01-16 15:53:35 +000041#include <android_companion_virtualdevice_flags.h>
42#include <android/companion/virtualnative/IVirtualDeviceManagerNative.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080043#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080044#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046#include <binder/MemoryBase.h>
47#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080048#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080049#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080050#include <binderthreadstate/CallerUtils.h>
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -070051#include <com_android_internal_camera_flags.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070052#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070053#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080054#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080055#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070057#include "hidl/HidlCameraService.h"
58#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080059#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070060#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080062#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070063#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070064#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000065#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070066#include <utils/Errors.h>
67#include <utils/Log.h>
68#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070069#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080070#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080071#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080072#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080073#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070074#include <system/camera_metadata.h>
Kunal Malhotrabfc96052023-02-28 23:25:34 +000075#include <binder/IServiceManager.h>
76#include <binder/IActivityManager.h>
Biswarup Pal37a75182024-01-16 15:53:35 +000077#include <camera/CameraUtils.h>
Austin Borgered99f642023-06-01 16:51:35 -070078#include <camera/StringUtils.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080079
Ruben Brunkb2119af2014-05-09 19:57:56 -070080#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070081
82#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070083#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070084#include "api2/CameraDeviceClient.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070085#include "utils/CameraServiceProxyWrapper.h"
Emilian Peev31bd2422024-04-23 22:24:09 +000086#include "utils/CameraTraces.h"
Shuzhen Wang045be6c2023-10-12 10:01:10 -070087#include "utils/SessionConfigurationUtils.h"
Emilian Peev31bd2422024-04-23 22:24:09 +000088#include "utils/TagMonitor.h"
89#include "utils/Utils.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070090
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080091namespace {
92 const char* kPermissionServiceName = "permission";
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080093 const char* kActivityServiceName = "activity";
94 const char* kSensorPrivacyServiceName = "sensor_privacy";
95 const char* kAppopsServiceName = "appops";
Jyoti Bhayanada519ab2023-05-15 15:49:15 -070096 const char* kProcessInfoServiceName = "processinfo";
Biswarup Pal37a75182024-01-16 15:53:35 +000097 const char* kVirtualDeviceBackCameraId = "0";
98 const char* kVirtualDeviceFrontCameraId = "1";
99
100 int32_t getDeviceId(const android::CameraMetadata& cameraInfo) {
101 if (!cameraInfo.exists(ANDROID_INFO_DEVICE_ID)) {
102 return android::kDefaultDeviceId;
103 }
104
105 const auto &deviceIdEntry = cameraInfo.find(ANDROID_INFO_DEVICE_ID);
106 return deviceIdEntry.data.i32[0];
107 }
108} // namespace anonymous
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -0800109
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110namespace android {
111
Austin Borgerea931242021-12-13 23:10:41 +0000112using namespace camera3;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700113using namespace camera3::SessionConfigurationUtils;
114
115using binder::Status;
Biswarup Pal37a75182024-01-16 15:53:35 +0000116using companion::virtualnative::IVirtualDeviceManagerNative;
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700117using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700118using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800119using hardware::ICamera;
120using hardware::ICameraClient;
121using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800122using hardware::camera2::ICameraInjectionCallback;
123using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800124using hardware::camera2::utils::CameraIdAndSessionConfiguration;
125using hardware::camera2::utils::ConcurrentCameraIdCombination;
Biswarup Pal37a75182024-01-16 15:53:35 +0000126
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -0700127namespace flags = com::android::internal::camera::flags;
Biswarup Pal37a75182024-01-16 15:53:35 +0000128namespace vd_flags = android::companion::virtualdevice::flags;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800129
Mathias Agopian65ab4712010-07-14 17:59:35 -0700130// ----------------------------------------------------------------------------
131// Logging support -- this is for debugging only
132// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700133volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700134
Steve Blockb8a80522011-12-20 16:23:08 +0000135#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
136#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700137
138static void setLogLevel(int level) {
139 android_atomic_write(level, &gLogLevel);
140}
141
Henri Chataingbcb99452023-11-01 17:40:30 +0000142int32_t format_as(CameraService::StatusInternal s) {
143 return fmt::underlying(s);
144}
145
Mathias Agopian65ab4712010-07-14 17:59:35 -0700146// ----------------------------------------------------------------------------
147
Austin Borger249e6592024-03-10 22:28:11 -0700148// Permission strings (references to AttributionAndPermissionUtils for brevity)
149static const std::string &sDumpPermission =
150 AttributionAndPermissionUtils::sDumpPermission;
151static const std::string &sManageCameraPermission =
152 AttributionAndPermissionUtils::sManageCameraPermission;
153static const std::string &sCameraSendSystemEventsPermission =
154 AttributionAndPermissionUtils::sCameraSendSystemEventsPermission;
155static const std::string &sCameraInjectExternalCameraPermission =
156 AttributionAndPermissionUtils::sCameraInjectExternalCameraPermission;
157
Kunal Malhotrabfc96052023-02-28 23:25:34 +0000158// Constant integer for FGS Logging, used to denote the API type for logger
159static const int LOG_FGS_CAMERA_API = 1;
Rucha Katakwardf223072021-06-15 10:21:00 -0700160const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800161static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
162static constexpr int32_t kSystemNativeClientState =
163 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Austin Borgered99f642023-06-01 16:51:35 -0700164static const std::string kServiceName("cameraserver");
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700165
Austin Borgered99f642023-06-01 16:51:35 -0700166const std::string CameraService::kOfflineDevice("offline-");
167const std::string CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700168
Biswarup Pal7d072862024-04-17 15:24:47 +0000169constexpr int32_t kInvalidDeviceId = -1;
170
Rucha Katakward9ea6452021-05-06 11:57:16 -0700171// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700172static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700173
Austin Borger74fca042022-05-23 12:41:21 -0700174CameraService::CameraService(
Austin Borger249e6592024-03-10 22:28:11 -0700175 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,
176 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils) :
177 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils == nullptr ?
178 std::make_shared<AttributionAndPermissionUtils>()\
179 : attributionAndPermissionUtils),
Austin Borger74fca042022-05-23 12:41:21 -0700180 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
181 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800182 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800183 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700184 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700185 mSoundRef(0), mInitialized(false),
186 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000187 ALOGI("CameraService started (pid=%d)", getpid());
Austin Borger249e6592024-03-10 22:28:11 -0700188 mAttributionAndPermissionUtils->setCameraService(this);
Ruben Brunkcc776712015-02-17 20:18:47 -0800189 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700190 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
191 if (mMemFd == -1) {
192 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
193 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700194}
195
Charles Chena7b613c2023-01-24 21:57:33 +0000196// Enable processes with isolated AID to request the binder
197void CameraService::instantiate() {
198 CameraService::publish(true);
199}
200
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800201void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700202 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800203 return;
204 }
205
206 ALOGV("appops service registered. setting camera audio restriction");
207 mAppOps.setCameraAudioRestriction(mAudioRestriction);
208}
209
Iliyan Malchev8951a972011-04-14 16:55:59 -0700210void CameraService::onFirstRef()
211{
Ruben Brunkcc776712015-02-17 20:18:47 -0800212 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800213
Iliyan Malchev8951a972011-04-14 16:55:59 -0700214 BnCameraService::onFirstRef();
215
Ruben Brunk99e69712015-05-26 17:25:07 -0700216 // Update battery life tracking if service is restarting
217 BatteryNotifier& notifier(BatteryNotifier::getInstance());
218 notifier.noteResetCamera();
219 notifier.noteResetFlashlight();
220
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800221 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800222
Emilian Peevf53f66e2017-04-11 14:29:43 +0100223 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800224 if (res == OK) {
225 mInitialized = true;
226 }
227
Svet Ganova453d0d2018-01-11 15:37:58 -0800228 mUidPolicy = new UidPolicy(this);
229 mUidPolicy->registerSelf();
Austin Borger249e6592024-03-10 22:28:11 -0700230 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this, mAttributionAndPermissionUtils);
Michael Grooverd1d435a2018-12-18 17:39:42 -0800231 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800232 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800233
234 // appops function setCamerAudioRestriction uses getService which
235 // is blocking till the appops service is ready. To enable early
236 // boot availability for cameraservice, use checkService which is
237 // non blocking and register for notifications
238 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700239 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800240 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700241 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800242 } else {
243 mAppOps.setCameraAudioRestriction(mAudioRestriction);
244 }
245
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700246 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
247 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000248 // Deprecated, so it will fail to register on newer devices
249 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700250 __FUNCTION__);
251 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700252
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700253 if (!AidlCameraService::registerService(this)) {
254 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
255 }
256
Shuzhen Wang24b44152019-09-20 10:38:11 -0700257 // This needs to be last call in this function, so that it's as close to
258 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700259 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700260 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800261}
262
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800263status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800264 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100265
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800266 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000267 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800268 {
269 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800270
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800271 if (nullptr == mCameraProviderManager.get()) {
272 mCameraProviderManager = new CameraProviderManager();
273 res = mCameraProviderManager->initialize(this);
274 if (res != OK) {
275 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
276 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700277 logServiceError("Unable to initialize camera provider manager",
278 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800279 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100280 }
281 }
282
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800283 // Setup vendor tags before we call get_camera_info the first time
284 // because HAL might need to setup static vendor keys in get_camera_info
285 // TODO: maybe put this into CameraProviderManager::initialize()?
286 mCameraProviderManager->setUpVendorTags();
287
288 if (nullptr == mFlashlight.get()) {
289 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700290 }
291
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800292 res = mFlashlight->findFlashUnits();
293 if (res != OK) {
294 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
295 }
296
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000297 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800298 }
299
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800300 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700301 if (getCameraState(cameraId) == nullptr) {
302 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800303 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000304 if (unavailPhysicalIds.count(cameraId) > 0) {
305 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700306 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000307 }
308 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800309 }
310
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700311 // Derive primary rear/front cameras, and filter their charactierstics.
312 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700313 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700314 // Assume internal cameras are advertised from the same
315 // provider. If multiple providers are registered at different time,
316 // and each provider contains multiple internal color cameras, the current
317 // logic may filter the characteristics of more than one front/rear color
318 // cameras.
319 Mutex::Autolock l(mServiceLock);
320 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700321 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700322
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800323 return OK;
324}
325
Austin Borgered99f642023-06-01 16:51:35 -0700326void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700327 SystemCameraKind systemCameraKind) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000328 // Get the device id and app-visible camera id for the given HAL-visible camera id.
329 auto [deviceId, mappedCameraId] =
330 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
331
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800332 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800333 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700334 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
335 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000336 ALOGV("%s: Skipping torch callback for system-only camera device %s",
337 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700338 continue;
339 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000340
Austin Borgere8e2c422022-05-12 13:45:24 -0700341 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Biswarup Pal37a75182024-01-16 15:53:35 +0000342 mappedCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700343 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
344 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800345 }
346}
347
Mathias Agopian65ab4712010-07-14 17:59:35 -0700348CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800349 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800350 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800351 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800352 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700353}
354
Emilian Peevaee727d2017-05-04 16:35:48 +0100355void CameraService::onNewProviderRegistered() {
356 enumerateProviders();
357}
358
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700359void CameraService::filterAPI1SystemCameraLocked(
360 const std::vector<std::string> &normalDeviceIds) {
361 mNormalDeviceIdsWithoutSystemCamera.clear();
Biswarup Pal37a75182024-01-16 15:53:35 +0000362 for (auto &cameraId : normalDeviceIds) {
363 if (vd_flags::camera_device_awareness()) {
364 CameraMetadata cameraInfo;
365 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000366 cameraId, false, &cameraInfo,
367 hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +0000368 int32_t deviceId = kDefaultDeviceId;
369 if (res != OK) {
370 ALOGW("%s: Not able to get camera characteristics for camera id %s",
371 __FUNCTION__, cameraId.c_str());
372 } else {
373 deviceId = getDeviceId(cameraInfo);
374 }
375 // Cameras associated with non-default device id's (i.e., virtual cameras) can never be
376 // system cameras, so skip for non-default device id's.
377 if (deviceId != kDefaultDeviceId) {
378 continue;
379 }
380 }
381
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700382 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Biswarup Pal37a75182024-01-16 15:53:35 +0000383 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
384 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700385 continue;
386 }
387 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700388 // All system camera ids will necessarily come after public camera
389 // device ids as per the HAL interface contract.
390 break;
391 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000392 mNormalDeviceIdsWithoutSystemCamera.push_back(cameraId);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700393 }
394 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
395 mNormalDeviceIdsWithoutSystemCamera.size());
396}
397
Austin Borgered99f642023-06-01 16:51:35 -0700398status_t CameraService::getSystemCameraKind(const std::string& cameraId,
399 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700400 auto state = getCameraState(cameraId);
401 if (state != nullptr) {
402 *kind = state->getSystemCameraKind();
403 return OK;
404 }
405 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700406 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700407}
408
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800409void CameraService::updateCameraNumAndIds() {
410 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700411 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
412 // Excludes hidden secure cameras
413 mNumberOfCameras =
414 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
415 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800416 mNormalDeviceIds =
417 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700418 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800419}
420
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700421void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700422 // To claim to be S Performance primary cameras, the cameras must be
423 // backward compatible. So performance class primary camera Ids must be API1
424 // compatible.
425 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
426 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
427 int facing = -1;
428 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800429 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000430 getDeviceVersion(cameraId,
431 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
432 /*out*/&portraitRotation, /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700433 if (facing == -1) {
434 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
435 return;
436 }
437
438 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
439 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700440 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
441 if (res == OK) {
442 mPerfClassPrimaryCameraIds.insert(cameraId);
443 } else {
444 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
445 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
446 break;
447 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700448
449 if (facing == hardware::CAMERA_FACING_BACK) {
450 firstRearCameraSeen = true;
451 }
452 if (facing == hardware::CAMERA_FACING_FRONT) {
453 firstFrontCameraSeen = true;
454 }
455 }
456
457 if (firstRearCameraSeen && firstFrontCameraSeen) {
458 break;
459 }
460 }
461}
462
Austin Borgered99f642023-06-01 16:51:35 -0700463void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700464 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100465 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
466 if (res != OK) {
467 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
468 return;
469 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000470 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700471 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
472 if (res != OK) {
473 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
474 return;
475 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000476 std::vector<std::string> physicalCameraIds;
477 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700478 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100479 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700480 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100481 }
482
483 {
484 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700485 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000486 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100487 }
488
Austin Borgered99f642023-06-01 16:51:35 -0700489 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100490 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700491 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800492
Austin Borgered99f642023-06-01 16:51:35 -0700493 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100494 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800495
496 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700497 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100498}
499
Austin Borgered99f642023-06-01 16:51:35 -0700500void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800501 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700502 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100503 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700504 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100505 }
506
507 {
508 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700509 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100510 }
511}
512
Austin Borgered99f642023-06-01 16:51:35 -0700513void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800514 CameraDeviceStatus newHalStatus) {
515 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700516 cameraId.c_str(), eToI(newHalStatus));
Igor Murashkincba2c162013-03-20 15:56:31 -0700517
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800518 StatusInternal newStatus = mapToInternal(newHalStatus);
519
Austin Borgered99f642023-06-01 16:51:35 -0700520 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800521
522 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700523 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100524 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700525 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100526
527 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700528 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100529
Austin Borgered99f642023-06-01 16:51:35 -0700530 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700531 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700532 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700533 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700534 return;
535 }
536
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800537 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800538
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800539 if (oldStatus == newStatus) {
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700540 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__,
541 eToI(newStatus));
Igor Murashkincba2c162013-03-20 15:56:31 -0700542 return;
543 }
544
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800545 if (newStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000546 logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
547 oldStatus, newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800548 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
549 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700550 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000551 mVirtualDeviceCameraIdMapper.removeCamera(cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800552
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800553 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700554 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800555 // Don't do this in updateStatus to avoid deadlock over mServiceLock
556 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700557
Ruben Brunkcc776712015-02-17 20:18:47 -0800558 // Remove cached shim parameters
559 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700560
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800561 // Remove online as well as offline client from the list of active clients,
562 // if they are present
Austin Borgered99f642023-06-01 16:51:35 -0700563 clientToDisconnectOnline = removeClientLocked(cameraId);
564 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700565 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800566
Austin Borgered99f642023-06-01 16:51:35 -0700567 disconnectClient(cameraId, clientToDisconnectOnline);
568 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700569
Austin Borgered99f642023-06-01 16:51:35 -0700570 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800571 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800572 if (oldStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000573 logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
574 oldStatus, newStatus));
Ruben Brunka8ca9152015-04-07 14:23:40 -0700575 }
Austin Borgered99f642023-06-01 16:51:35 -0700576 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700577 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800578}
Igor Murashkincba2c162013-03-20 15:56:31 -0700579
Austin Borgered99f642023-06-01 16:51:35 -0700580void CameraService::onDeviceStatusChanged(const std::string& id,
581 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800582 CameraDeviceStatus newHalStatus) {
583 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700584 __FUNCTION__, id.c_str(), physicalId.c_str(), eToI(newHalStatus));
Shuzhen Wang43858162020-01-10 13:42:15 -0800585
586 StatusInternal newStatus = mapToInternal(newHalStatus);
587
588 std::shared_ptr<CameraState> state = getCameraState(id);
589
590 if (state == nullptr) {
591 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700592 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800593 return;
594 }
595
596 StatusInternal logicalCameraStatus = state->getStatus();
597 if (logicalCameraStatus != StatusInternal::PRESENT &&
598 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
599 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700600 __FUNCTION__, physicalId.c_str(), eToI(newHalStatus), eToI(logicalCameraStatus));
Shuzhen Wang43858162020-01-10 13:42:15 -0800601 return;
602 }
603
604 bool updated = false;
605 if (newStatus == StatusInternal::PRESENT) {
606 updated = state->removeUnavailablePhysicalId(physicalId);
607 } else {
608 updated = state->addUnavailablePhysicalId(physicalId);
609 }
610
611 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700612 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800613 if (newStatus == StatusInternal::PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000614 logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800615 } else {
Henri Chataingbcb99452023-11-01 17:40:30 +0000616 logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800617 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700618 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
619 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
620 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700621 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700622 return;
623 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800624 Mutex::Autolock lock(mStatusListenerLock);
625 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700626 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
627 listener->getListenerPid(), listener->getListenerUid())) {
628 ALOGV("Skipping discovery callback for system-only camera device %s",
629 id.c_str());
630 continue;
631 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700632 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Biswarup Pal37a75182024-01-16 15:53:35 +0000633 mapToInterface(newStatus), id, physicalId, kDefaultDeviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700634 listener->handleBinderStatus(ret,
635 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
636 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
637 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800638 }
639 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700640}
641
Austin Borgered99f642023-06-01 16:51:35 -0700642void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800643 if (clientToDisconnect.get() != nullptr) {
644 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700645 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800646 // Notify the client of disconnection
647 clientToDisconnect->notifyError(
648 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
649 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800650 clientToDisconnect->disconnect();
651 }
652}
653
Austin Borgered99f642023-06-01 16:51:35 -0700654void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800655 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700656 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
657 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
658 if (res != OK) {
659 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700660 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700661 return;
662 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800663 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700664 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800665}
666
Austin Borgered99f642023-06-01 16:51:35 -0700667void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700668 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
669 Mutex::Autolock al(mTorchStatusMutex);
670 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
671}
672
Austin Borgered99f642023-06-01 16:51:35 -0700673void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800674 int32_t newStrengthLevel) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000675 // Get the device id and app-visible camera id for the given HAL-visible camera id.
676 auto [deviceId, mappedCameraId] =
677 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
678
Rucha Katakwar38284522021-11-10 11:25:21 -0800679 Mutex::Autolock lock(mStatusListenerLock);
680 for (auto& i : mListenerList) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000681 auto ret = i->getListener()->onTorchStrengthLevelChanged(mappedCameraId,
682 newStrengthLevel, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700683 i->handleBinderStatus(ret,
684 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
685 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800686 }
687}
688
Austin Borgered99f642023-06-01 16:51:35 -0700689void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700690 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800691 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700692 __FUNCTION__, cameraId.c_str(), eToI(newStatus));
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800693
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800694 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800695 status_t res = getTorchStatusLocked(cameraId, &status);
696 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700697 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700698 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800699 return;
700 }
701 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800702 return;
703 }
704
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800705 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800706 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800707 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
708 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800709 return;
710 }
711
Ruben Brunkcc776712015-02-17 20:18:47 -0800712 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700713 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700714 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700715 auto iter = mTorchUidMap.find(cameraId);
716 if (iter != mTorchUidMap.end()) {
717 int oldUid = iter->second.second;
718 int newUid = iter->second.first;
719 BatteryNotifier& notifier(BatteryNotifier::getInstance());
720 if (oldUid != newUid) {
721 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800722 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700723 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700724 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800725 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700726 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700727 }
728 iter->second.second = newUid;
729 } else {
730 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800731 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700732 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700733 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700734 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700735 }
736 }
737 }
738 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700739 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800740}
741
Austin Borger249e6592024-03-10 22:28:11 -0700742bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700743 // Returns false if this is not an automotive device type.
744 if (!isAutomotiveDevice())
745 return false;
746
747 // Returns false if no camera id is provided.
Austin Borger1c1bee02023-06-01 16:51:35 -0700748 if (cam_id.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700749 return false;
750
751 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
752 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
753 // This isn't a known camera ID, so it's not a system camera.
754 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
755 return false;
756 }
757
758 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
759 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
760 return false;
761 }
762
763 CameraMetadata cameraInfo;
764 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000765 cam_id, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700766 if (res != OK){
767 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
768 cam_id.c_str());
769 return false;
770 }
771
772 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
773 if (auto_location.count != 1)
774 return false;
775
776 uint8_t location = auto_location.data.u8[0];
777 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
778 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
779 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
780 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
781 return false;
782 }
783
784 return true;
785}
786
Biswarup Pal37a75182024-01-16 15:53:35 +0000787Status CameraService::getNumberOfCameras(int32_t type, int32_t deviceId, int32_t devicePolicy,
788 int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700789 ATRACE_CALL();
Biswarup Pal37a75182024-01-16 15:53:35 +0000790 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
791 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
792 *numCameras = mVirtualDeviceCameraIdMapper.getNumberOfCameras(deviceId);
793 return Status::ok();
794 }
795
Emilian Peevaee727d2017-05-04 16:35:48 +0100796 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700797 bool hasSystemCameraPermissions =
Austin Borger22c5c852024-03-08 13:31:36 -0800798 hasPermissionsForSystemCamera(std::string(), getCallingPid(),
799 getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700800 switch (type) {
801 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700802 if (hasSystemCameraPermissions) {
803 *numCameras = static_cast<int>(mNormalDeviceIds.size());
804 } else {
805 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
806 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800807 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700808 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700809 if (hasSystemCameraPermissions) {
810 *numCameras = mNumberOfCameras;
811 } else {
812 *numCameras = mNumberOfCamerasWithoutSystemCamera;
813 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800814 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700815 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800816 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700817 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800818 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
819 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700820 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800821 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700822}
823
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700824Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
Biswarup Pal37a75182024-01-16 15:53:35 +0000825 int32_t deviceId, int32_t devicePolicy,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700826 /* out */
827 hardware::camera2::impl::CameraMetadataNative* request) {
828 ATRACE_CALL();
829
830 if (!flags::feature_combination_query()) {
831 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
832 "Camera subsystem doesn't support this method!");
833 }
834 if (!mInitialized) {
835 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
836 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
837 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
838 }
839
Biswarup Pal37a75182024-01-16 15:53:35 +0000840 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
malikakash98260df2024-05-10 23:33:57 +0000841 devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000842 if (!cameraIdOptional.has_value()) {
843 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
844 unresolvedCameraId.c_str(), deviceId);
845 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
846 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
847 }
848 std::string cameraId = cameraIdOptional.value();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700849
850 binder::Status res;
851 if (request == nullptr) {
852 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
853 "Camera %s: Error creating default request", cameraId.c_str());
854 return res;
855 }
856 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
857 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
858 cameraId, templateId, &tempId);
859 if (!res.isOk()) {
860 ALOGE("%s: Camera %s: failed to map request Template %d",
861 __FUNCTION__, cameraId.c_str(), templateId);
862 return res;
863 }
864
865 if (shouldRejectSystemCameraConnection(cameraId)) {
866 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
867 "request for system only device %s: ", cameraId.c_str());
868 }
869
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700870 CameraMetadata metadata;
871 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
872 if (err == OK) {
873 request->swap(metadata);
874 } else if (err == BAD_VALUE) {
875 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
876 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
877 cameraId.c_str(), templateId, strerror(-err), err);
878 } else {
879 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
880 "Camera %s: Error creating default request for template %d: %s (%d)",
881 cameraId.c_str(), templateId, strerror(-err), err);
882 }
883 return res;
884}
885
886Status CameraService::isSessionConfigurationWithParametersSupported(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700887 const std::string& unresolvedCameraId, int targetSdkVersion,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700888 const SessionConfiguration& sessionConfiguration,
Biswarup Pal37a75182024-01-16 15:53:35 +0000889 int32_t deviceId, int32_t devicePolicy,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700890 /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700891 ATRACE_CALL();
892
893 if (!flags::feature_combination_query()) {
894 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
895 "Camera subsystem doesn't support this method!");
896 }
897 if (!mInitialized) {
898 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
899 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
900 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
901 }
902
Biswarup Pal37a75182024-01-16 15:53:35 +0000903 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
malikakash98260df2024-05-10 23:33:57 +0000904 devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000905 if (!cameraIdOptional.has_value()) {
906 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
907 unresolvedCameraId.c_str(), deviceId);
908 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
909 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
910 }
911 std::string cameraId = cameraIdOptional.value();
912
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700913 if (supported == nullptr) {
914 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
915 unresolvedCameraId.c_str());
916 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
917 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
918 }
919
920 if (shouldRejectSystemCameraConnection(cameraId)) {
921 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
922 "session configuration with parameters support for system only device %s: ",
923 cameraId.c_str());
924 }
925
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700926 bool overrideForPerfClass = flags::calculate_perf_override_during_session_support() &&
927 SessionConfigurationUtils::targetPerfClassPrimaryCamera(
928 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
929
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700930 return isSessionConfigurationWithParametersSupportedUnsafe(cameraId, sessionConfiguration,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700931 overrideForPerfClass, supported);
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700932}
933
934Status CameraService::isSessionConfigurationWithParametersSupportedUnsafe(
935 const std::string& cameraId, const SessionConfiguration& sessionConfiguration,
936 bool overrideForPerfClass, /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700937 *supported = false;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700938 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(
939 cameraId, sessionConfiguration, overrideForPerfClass,
940 /*checkSessionParams=*/true, supported);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700941 binder::Status res;
942 switch (ret) {
943 case OK:
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700944 // Expected. Do Nothing.
945 return Status::ok();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700946 case INVALID_OPERATION: {
947 std::string msg = fmt::sprintf(
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700948 "Camera %s: Session configuration with parameters supported query not "
949 "supported!",
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700950 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700951 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
952 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
953 *supported = false;
954 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700955 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700956 break;
957 case NAME_NOT_FOUND: {
958 std::string msg = fmt::sprintf("Camera %s: Unknown camera ID.", cameraId.c_str());
959 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
960 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
961 *supported = false;
962 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
963 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700964 break;
965 default: {
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700966 std::string msg = fmt::sprintf(
967 "Unable to retrieve session configuration support for camera "
968 "device %s: Error: %s (%d)",
969 cameraId.c_str(), strerror(-ret), ret);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700970 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700971 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
972 *supported = false;
973 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700974 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700975 break;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700976 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700977}
978
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800979Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000980 int targetSdkVersion, int rotationOverride,
Biswarup Pal37a75182024-01-16 15:53:35 +0000981 const SessionConfiguration& sessionConfiguration, int32_t deviceId, int32_t devicePolicy,
982 /*out*/ CameraMetadata* outMetadata) {
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800983 ATRACE_CALL();
984
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800985 if (outMetadata == nullptr) {
986 std::string msg =
987 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
988 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
989 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
990 }
991
Avichal Rakesh4baf7262024-03-20 19:16:04 -0700992 if (!mInitialized) {
993 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
994 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
995 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
996 }
997
Biswarup Pal37a75182024-01-16 15:53:35 +0000998 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
malikakash98260df2024-05-10 23:33:57 +0000999 devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001000 if (!cameraIdOptional.has_value()) {
1001 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001002 unresolvedCameraId.c_str(), deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001003 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1004 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1005 }
1006 std::string cameraId = cameraIdOptional.value();
1007
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001008 if (shouldRejectSystemCameraConnection(cameraId)) {
1009 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1010 "Unable to retrieve camera"
1011 "characteristics for system only device %s: ",
1012 cameraId.c_str());
1013 }
1014
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001015 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1016 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001017 if (flags::check_session_support_before_session_char()) {
1018 bool sessionConfigSupported;
1019 Status res = isSessionConfigurationWithParametersSupportedUnsafe(
1020 cameraId, sessionConfiguration, overrideForPerfClass, &sessionConfigSupported);
1021 if (!res.isOk()) {
1022 // isSessionConfigurationWithParametersSupportedUnsafe should log what went wrong and
1023 // report the correct Status to send to the client. Simply forward the error to
1024 // the client.
1025 outMetadata->clear();
1026 return res;
1027 }
1028 if (!sessionConfigSupported) {
1029 std::string msg = fmt::sprintf(
1030 "Session configuration not supported for camera device %s.", cameraId.c_str());
1031 outMetadata->clear();
1032 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1033 }
1034 }
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001035
1036 status_t ret = mCameraProviderManager->getSessionCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001037 cameraId, sessionConfiguration, overrideForPerfClass, rotationOverride, outMetadata);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001038
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001039 switch (ret) {
1040 case OK:
1041 // Expected, no handling needed.
1042 break;
1043 case INVALID_OPERATION: {
1044 std::string msg = fmt::sprintf(
1045 "Camera %s: Session characteristics query not supported!",
1046 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001047 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001048 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1049 outMetadata->clear();
1050 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1051 }
1052 break;
1053 case NAME_NOT_FOUND: {
1054 std::string msg = fmt::sprintf(
1055 "Camera %s: Unknown camera ID.",
1056 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001057 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001058 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1059 outMetadata->clear();
1060 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001061 }
1062 break;
1063 default: {
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001064 std::string msg = fmt::sprintf(
1065 "Unable to retrieve session characteristics for camera device %s: "
1066 "Error: %s (%d)",
1067 cameraId.c_str(), strerror(-ret), ret);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001068 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001069 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1070 outMetadata->clear();
1071 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001072 }
1073 }
1074
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001075 return filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
1076}
1077
1078Status CameraService::filterSensitiveMetadataIfNeeded(
1079 const std::string& cameraId, CameraMetadata* metadata) {
1080 int callingPid = getCallingPid();
1081 int callingUid = getCallingUid();
1082
1083 if (callingPid == getpid()) {
1084 // Caller is cameraserver; no need to remove keys
1085 return Status::ok();
1086 }
1087
1088 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1089 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1090 ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
1091 metadata->clear();
1092 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1093 "Unable to retrieve camera kind for device %s", cameraId.c_str());
1094 }
1095 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
1096 // Attempting to query system only camera without system camera permission would have
1097 // failed the shouldRejectSystemCameraConnection in the caller. So if we get here
1098 // for a system only camera, then the caller has the required permission.
1099 // No need to remove keys
1100 return Status::ok();
1101 }
1102
1103 std::vector<int32_t> tagsRemoved;
Biswarup Pale506e732024-03-27 13:46:20 +00001104 // Get the device id that owns this camera.
1105 auto [cameraOwnerDeviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1106 cameraId);
1107 bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid,
1108 cameraOwnerDeviceId);
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001109 if (hasCameraPermission) {
1110 // Caller has camera permission; no need to remove keys
1111 return Status::ok();
1112 }
1113
1114 status_t ret = metadata->removePermissionEntries(
1115 mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1116 if (ret != OK) {
1117 metadata->clear();
1118 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1119 "Failed to remove camera characteristics needing camera permission "
1120 "for device %s:%s (%d)",
1121 cameraId.c_str(), strerror(-ret), ret);
1122 }
1123
1124 if (!tagsRemoved.empty()) {
1125 ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1126 tagsRemoved.data(), tagsRemoved.size());
1127 if (ret != OK) {
1128 metadata->clear();
1129 return STATUS_ERROR_FMT(
1130 ERROR_INVALID_OPERATION,
1131 "Failed to insert camera keys needing permission for device %s: %s (%d)",
1132 cameraId.c_str(), strerror(-ret), ret);
1133 }
1134 }
1135 return Status::ok();
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001136}
1137
malikakash22af94c2023-12-04 18:13:14 +00001138Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001139 const std::string& cameraId,
1140 const CameraMetadata& sessionParams) {
1141 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001142 const int pid = getCallingPid();
1143 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001144 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1145 __FUNCTION__, pid, uid);
1146 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1147 "Permission Denial: no permission to inject session params");
1148 }
1149
Biswarup Pal37a75182024-01-16 15:53:35 +00001150 // Do not allow session params injection for a virtual camera.
1151 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1152 if (deviceId != kDefaultDeviceId) {
1153 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1154 "Cannot inject session params for a virtual camera");
1155 }
1156
malikakash22af94c2023-12-04 18:13:14 +00001157 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1158 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1159
1160 auto clientDescriptor = mActiveClientManager.get(cameraId);
1161 if (clientDescriptor == nullptr) {
1162 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1163 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1164 "No active client for camera id %s", cameraId.c_str());
1165 }
1166
1167 sp<BasicClient> clientSp = clientDescriptor->getValue();
1168 status_t res = clientSp->injectSessionParams(sessionParams);
1169
1170 if (res != OK) {
1171 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1172 "Error injecting session params into camera \"%s\": %s (%d)",
1173 cameraId.c_str(), strerror(-res), res);
1174 }
1175 return Status::ok();
1176}
1177
Biswarup Pal37a75182024-01-16 15:53:35 +00001178std::optional<std::string> CameraService::resolveCameraId(
1179 const std::string& inputCameraId,
1180 int32_t deviceId,
malikakash98260df2024-05-10 23:33:57 +00001181 int32_t devicePolicy) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001182 if ((deviceId == kDefaultDeviceId)
1183 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1184 auto [storedDeviceId, _] =
1185 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1186 if (storedDeviceId != kDefaultDeviceId) {
1187 // Trying to access a virtual camera from default-policy device context, we should fail.
1188 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1189 inputCameraId.c_str(), deviceId);
1190 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1191 return std::nullopt;
1192 }
malikakash98260df2024-05-10 23:33:57 +00001193 return inputCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001194 }
1195
1196 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1197}
1198
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001199Status CameraService::getCameraInfo(int cameraId, int rotationOverride, int32_t deviceId,
Biswarup Pal37a75182024-01-16 15:53:35 +00001200 int32_t devicePolicy, CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001201 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001202 Mutex::Autolock l(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001203 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId, deviceId, devicePolicy);
1204 if (cameraIdStr.empty()) {
1205 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
1206 cameraId, deviceId);
1207 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1208 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1209 }
malikakashedb38962023-09-06 00:03:35 +00001210
Austin Borgered99f642023-06-01 16:51:35 -07001211 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001212 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1213 "characteristics for system only device %s: ", cameraIdStr.c_str());
1214 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001215
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001216 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001217 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001218 return STATUS_ERROR(ERROR_DISCONNECTED,
1219 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001220 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001221 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001222 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001223 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1224 if (hasSystemCameraPermissions) {
1225 cameraIdBound = mNumberOfCameras;
1226 }
1227 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001228 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1229 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001230 }
1231
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001232 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001233 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001234 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001235 cameraIdStr, rotationOverride, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001236 if (err != OK) {
1237 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1238 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1239 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001240 logServiceError(std::string("Error retrieving camera info from device ")
1241 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001242 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001243
Ruben Brunkcc776712015-02-17 20:18:47 -08001244 return ret;
1245}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001246
Biswarup Pal37a75182024-01-16 15:53:35 +00001247std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1248 int32_t deviceId, int32_t devicePolicy) {
1249 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1250 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1251 std::optional<std::string> cameraIdOptional =
1252 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1253 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1254 }
1255
1256 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001257 auto callingPid = getCallingPid();
1258 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001259 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1260 callingPid, callingUid, /* checkCameraPermissions= */ false);
1261 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001262 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001263 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001264 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1265 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1266 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001267 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001268 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001269
malikakash98260df2024-05-10 23:33:57 +00001270 return (*cameraIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001271}
1272
Biswarup Pal37a75182024-01-16 15:53:35 +00001273std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1274 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001275 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001276 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001277}
1278
Austin Borgered99f642023-06-01 16:51:35 -07001279Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001280 int targetSdkVersion, int rotationOverride, int32_t deviceId, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +00001281 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001282 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001283
Zhijun He2b59be82013-09-25 10:14:30 -07001284 if (!cameraInfo) {
1285 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001286 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001287 }
1288
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001289 if (!mInitialized) {
1290 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001291 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001292 return STATUS_ERROR(ERROR_DISCONNECTED,
1293 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001294 }
1295
Biswarup Pal37a75182024-01-16 15:53:35 +00001296 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
malikakash98260df2024-05-10 23:33:57 +00001297 devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001298 if (!cameraIdOptional.has_value()) {
1299 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1300 unresolvedCameraId.c_str(), deviceId);
1301 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1302 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1303 }
1304 std::string cameraId = cameraIdOptional.value();
1305
Austin Borgered99f642023-06-01 16:51:35 -07001306 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001307 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001308 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001309 }
1310
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001311 bool overrideForPerfClass =
1312 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001313 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001314 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001315 cameraId, overrideForPerfClass, cameraInfo, rotationOverride);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001316 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001317 if (res == NAME_NOT_FOUND) {
1318 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001319 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001320 strerror(-res), res);
1321 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001322 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1323 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001324 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001325 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001326 strerror(-res), res);
1327 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001328 }
Emilian Peeve20c6372018-08-14 18:45:53 +01001329
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001330 return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -07001331}
1332
Biswarup Pal37a75182024-01-16 15:53:35 +00001333Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId, int32_t deviceId,
1334 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001335 ATRACE_CALL();
1336 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001337
Biswarup Pal37a75182024-01-16 15:53:35 +00001338 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
malikakash98260df2024-05-10 23:33:57 +00001339 devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001340 if (!cameraIdOptional.has_value()) {
1341 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1342 unresolvedCameraId.c_str(), deviceId);
1343 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1344 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1345 }
1346 std::string cameraId = cameraIdOptional.value();
1347
Rucha Katakwar38284522021-11-10 11:25:21 -08001348 if (!mInitialized) {
1349 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1350 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1351 }
1352
Biswarup Pal37a75182024-01-16 15:53:35 +00001353 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001354 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1355 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1356 }
1357
Austin Borgered99f642023-06-01 16:51:35 -07001358 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001359 if (res != OK) {
1360 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001361 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001362 strerror(-res), res);
1363 }
1364 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1365 return Status::ok();
1366}
1367
Austin Borgered99f642023-06-01 16:51:35 -07001368std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001369 time_t now = time(nullptr);
1370 char formattedTime[64];
1371 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001372 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001373}
1374
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001375Status CameraService::getCameraVendorTagDescriptor(
1376 /*out*/
1377 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001378 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001379 if (!mInitialized) {
1380 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001381 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001382 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001383 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1384 if (globalDescriptor != nullptr) {
1385 *desc = *(globalDescriptor.get());
1386 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001387 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001388}
1389
Emilian Peev71c73a22017-03-21 16:35:51 +00001390Status CameraService::getCameraVendorTagCache(
1391 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1392 ATRACE_CALL();
1393 if (!mInitialized) {
1394 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1395 return STATUS_ERROR(ERROR_DISCONNECTED,
1396 "Camera subsystem not available");
1397 }
1398 sp<VendorTagDescriptorCache> globalCache =
1399 VendorTagDescriptorCache::getGlobalVendorTagCache();
1400 if (globalCache != nullptr) {
1401 *cache = *(globalCache.get());
1402 }
1403 return Status::ok();
1404}
1405
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001406void CameraService::clearCachedVariables() {
1407 BasicClient::BasicClient::sCameraService = nullptr;
1408}
1409
Austin Borgered99f642023-06-01 16:51:35 -07001410std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001411 int rotationOverride, int* portraitRotation, int* facing,
1412 int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001413 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001414
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001415 int deviceVersion = 0;
1416
Emilian Peevf53f66e2017-04-11 14:29:43 +01001417 status_t res;
1418 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001419 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001420 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001421 if (res != OK || transport == IPCTransport::INVALID) {
1422 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001423 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001424 return std::make_pair(-1, IPCTransport::INVALID) ;
1425 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001426 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001427
Emilian Peevf53f66e2017-04-11 14:29:43 +01001428 hardware::CameraInfo info;
1429 if (facing) {
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001430 res = mCameraProviderManager->getCameraInfo(cameraId, rotationOverride,
Austin Borger18b30a72022-10-27 12:20:29 -07001431 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001432 if (res != OK) {
1433 return std::make_pair(-1, IPCTransport::INVALID);
1434 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001435 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001436 if (orientation) {
1437 *orientation = info.orientation;
1438 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001439 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001440
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001441 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001442}
1443
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001444Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001445 switch(err) {
1446 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001447 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001448 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001449 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1450 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001451 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001452 return STATUS_ERROR(ERROR_DISCONNECTED,
1453 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001454 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001455 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1456 "Camera HAL encountered error %d: %s",
1457 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001458 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001459}
1460
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001461Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001462 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1463 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001464 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001465 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001466 apiLevel effectiveApiLevel, bool overrideForPerfClass, int rotationOverride,
malikakash73125c62023-07-21 22:44:34 +00001467 bool forceSlowJpegMode, const std::string& originalCameraId,
1468 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001469 // For HIDL devices
1470 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1471 // Create CameraClient based on device version reported by the HAL.
1472 int deviceVersion = deviceVersionAndTransport.first;
1473 switch(deviceVersion) {
1474 case CAMERA_DEVICE_API_VERSION_1_0:
1475 ALOGE("Camera using old HAL version: %d", deviceVersion);
1476 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1477 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001478 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001479 break;
1480 case CAMERA_DEVICE_API_VERSION_3_0:
1481 case CAMERA_DEVICE_API_VERSION_3_1:
1482 case CAMERA_DEVICE_API_VERSION_3_2:
1483 case CAMERA_DEVICE_API_VERSION_3_3:
1484 case CAMERA_DEVICE_API_VERSION_3_4:
1485 case CAMERA_DEVICE_API_VERSION_3_5:
1486 case CAMERA_DEVICE_API_VERSION_3_6:
1487 case CAMERA_DEVICE_API_VERSION_3_7:
1488 break;
1489 default:
1490 // Should not be reachable
1491 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1492 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1493 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001494 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001495 }
1496 }
1497 if (effectiveApiLevel == API_1) { // Camera1 API route
1498 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001499 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001500 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001501 api1CameraId, facing, sensorOrientation,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001502 clientPid, clientUid, servicePid, overrideForPerfClass, rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00001503 forceSlowJpegMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001504 ALOGI("%s: Camera1 API (legacy), rotationOverride %d, forceSlowJpegMode %d",
1505 __FUNCTION__, rotationOverride, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001506 } else { // Camera2 API route
1507 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1508 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001509 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001510 cameraService->mCameraServiceProxyWrapper,
1511 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001512 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001513 overrideForPerfClass, rotationOverride, originalCameraId);
1514 ALOGI("%s: Camera2 API, rotationOverride %d", __FUNCTION__, rotationOverride);
Ruben Brunkcc776712015-02-17 20:18:47 -08001515 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001516 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001517}
1518
Austin Borgered99f642023-06-01 16:51:35 -07001519std::string CameraService::toString(std::set<userid_t> intSet) {
1520 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001521 bool first = true;
1522 for (userid_t i : intSet) {
1523 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001524 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001525 first = false;
1526 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001527 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001528 }
1529 }
Austin Borgered99f642023-06-01 16:51:35 -07001530 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001531}
1532
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001533int32_t CameraService::mapToInterface(TorchModeStatus status) {
1534 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1535 switch (status) {
1536 case TorchModeStatus::NOT_AVAILABLE:
1537 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1538 break;
1539 case TorchModeStatus::AVAILABLE_OFF:
1540 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1541 break;
1542 case TorchModeStatus::AVAILABLE_ON:
1543 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1544 break;
1545 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001546 ALOGW("Unknown new flash status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001547 }
1548 return serviceStatus;
1549}
1550
1551CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1552 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1553 switch (status) {
1554 case CameraDeviceStatus::NOT_PRESENT:
1555 serviceStatus = StatusInternal::NOT_PRESENT;
1556 break;
1557 case CameraDeviceStatus::PRESENT:
1558 serviceStatus = StatusInternal::PRESENT;
1559 break;
1560 case CameraDeviceStatus::ENUMERATING:
1561 serviceStatus = StatusInternal::ENUMERATING;
1562 break;
1563 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001564 ALOGW("Unknown new HAL device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001565 }
1566 return serviceStatus;
1567}
1568
1569int32_t CameraService::mapToInterface(StatusInternal status) {
1570 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1571 switch (status) {
1572 case StatusInternal::NOT_PRESENT:
1573 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1574 break;
1575 case StatusInternal::PRESENT:
1576 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1577 break;
1578 case StatusInternal::ENUMERATING:
1579 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1580 break;
1581 case StatusInternal::NOT_AVAILABLE:
1582 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1583 break;
1584 case StatusInternal::UNKNOWN:
1585 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1586 break;
1587 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001588 ALOGW("Unknown new internal device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001589 }
1590 return serviceStatus;
1591}
1592
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001593Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001594 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001595
Austin Borgered99f642023-06-01 16:51:35 -07001596 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001597 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001598 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001599 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001600 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1601 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001602 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001603 /*targetSdkVersion*/ __ANDROID_API_FUTURE__,
1604 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_OVERRIDE_TO_PORTRAIT,
Austin Borgered99f642023-06-01 16:51:35 -07001605 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001606 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001607 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001608 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001609 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001610}
1611
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001612Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001613 /*out*/
1614 CameraParameters* parameters) {
1615
1616 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1617
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001618 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001619
1620 if (parameters == NULL) {
1621 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001622 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001623 }
1624
malikakash98260df2024-05-10 23:33:57 +00001625 std::string cameraIdStr = std::to_string(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001626
1627 // Check if we already have parameters
1628 {
1629 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001630 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001631 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001632 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001633 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001634 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001635 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001636 }
1637 CameraParameters p = cameraState->getShimParams();
1638 if (!p.isEmpty()) {
1639 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001640 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001641 }
1642 }
1643
Austin Borger22c5c852024-03-08 13:31:36 -08001644 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001645 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001646 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001647 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001648 // Error already logged by callee
1649 return ret;
1650 }
1651
1652 // Check for parameters again
1653 {
1654 // Scope for service lock
1655 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001656 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001657 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001658 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001659 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001660 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001661 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001662 CameraParameters p = cameraState->getShimParams();
1663 if (!p.isEmpty()) {
1664 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001665 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001666 }
1667 }
1668
Ruben Brunkcc776712015-02-17 20:18:47 -08001669 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1670 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001671 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001672}
1673
Austin Borgered99f642023-06-01 16:51:35 -07001674Status CameraService::validateConnectLocked(const std::string& cameraId,
1675 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001676 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001677
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001678#ifdef __BRILLO__
1679 UNUSED(clientName8);
1680 UNUSED(clientUid);
1681 UNUSED(clientPid);
1682 UNUSED(originalClientPid);
1683#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001684 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1685 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001686 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001687 return allowed;
1688 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001689#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001690
Austin Borger22c5c852024-03-08 13:31:36 -08001691 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001692
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001693 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001694 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1695 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001696 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001697 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001698 }
1699
Ruben Brunkcc776712015-02-17 20:18:47 -08001700 if (getCameraState(cameraId) == nullptr) {
1701 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001702 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001703 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001704 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001705 }
1706
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001707 status_t err = checkIfDeviceIsUsable(cameraId);
1708 if (err != NO_ERROR) {
1709 switch(err) {
1710 case -ENODEV:
1711 case -EBUSY:
1712 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001713 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001714 default:
1715 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001716 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001717 }
1718 }
1719 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001720}
1721
Austin Borgered99f642023-06-01 16:51:35 -07001722Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1723 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001724 /*out*/int& originalClientPid) const {
Austin Borger22c5c852024-03-08 13:31:36 -08001725 int callingPid = getCallingPid();
1726 int callingUid = getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001727
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001728 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001729 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001730 clientUid = callingUid;
1731 } else if (!isTrustedCallingUid(callingUid)) {
1732 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1733 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001734 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1735 "Untrusted caller (calling PID %d, UID %d) trying to "
1736 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001737 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001738 clientName.c_str(), clientPid, clientUid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001739 }
1740
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001741 // Check if we can trust clientPid
1742 if (clientPid == USE_CALLING_PID) {
1743 clientPid = callingPid;
1744 } else if (!isTrustedCallingUid(callingUid)) {
1745 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1746 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001747 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1748 "Untrusted caller (calling PID %d, UID %d) trying to "
1749 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001750 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001751 clientName.c_str(), clientPid, clientUid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001752 }
1753
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001754 if (shouldRejectSystemCameraConnection(cameraId)) {
1755 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1756 cameraId.c_str());
1757 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001758 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001759 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001760 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1761 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001762 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001763 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001764 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001765 }
1766
Biswarup Pale506e732024-03-27 13:46:20 +00001767 // Get the device id that owns this camera.
1768 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1769
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001770 // If it's not calling from cameraserver, check the permission if the
1771 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1772 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001773 bool checkPermissionForCamera =
Biswarup Pale506e732024-03-27 13:46:20 +00001774 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName, deviceId);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001775 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001776 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001777 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001778 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1779 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001780 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001781 }
1782
Svet Ganova453d0d2018-01-11 15:37:58 -08001783 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001784 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001785 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001786 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1787 clientPid, clientUid);
1788 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001789 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1790 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001791 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001792 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001793 }
1794
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001795 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1796 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1797 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1798 if ((!isAutomotivePrivilegedClient(callingUid) ||
1799 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1800 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001801 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1802 return STATUS_ERROR_FMT(ERROR_DISABLED,
1803 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001804 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001805 }
1806
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001807 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1808 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001809 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001810 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001811
Ruben Brunk6267b532015-04-30 17:44:07 -07001812 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001813
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001814 // For non-system clients : Only allow clients who are being used by the current foreground
1815 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08001816 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001817 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001818 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1819 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001820 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001821 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1822 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001823 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001824 }
1825
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001826 if (flags::camera_hsum_permission()) {
1827 // If the System User tries to access the camera when the device is running in
1828 // headless system user mode, ensure that client has the required permission
1829 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07001830 if (isHeadlessSystemUserMode()
1831 && (clientUserId == USER_SYSTEM)
1832 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001833 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
1834 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1835 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1836 User without camera headless system user permission",
Austin Borger249e6592024-03-10 22:28:11 -07001837 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001838 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001839 }
1840
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001841 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001842}
1843
Austin Borgered99f642023-06-01 16:51:35 -07001844status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001845 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001846 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001847 if (cameraState == nullptr) {
1848 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001849 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001850 return -ENODEV;
1851 }
1852
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001853 StatusInternal currentStatus = cameraState->getStatus();
1854 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001855 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001856 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001857 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001858 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001859 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001860 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001861 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001862 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001863
Ruben Brunkcc776712015-02-17 20:18:47 -08001864 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001865}
1866
Ruben Brunkcc776712015-02-17 20:18:47 -08001867void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001868 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001869
Ruben Brunkcc776712015-02-17 20:18:47 -08001870 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001871 auto clientDescriptor =
1872 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001873 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001874 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1875
1876 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001877 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001878
1879 if (evicted.size() > 0) {
1880 // This should never happen - clients should already have been removed in disconnect
1881 for (auto& i : evicted) {
1882 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001883 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001884 }
1885
1886 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1887 __FUNCTION__);
1888 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001889
1890 // And register a death notification for the client callback. Do
1891 // this last to avoid Binder policy where a nested Binder
1892 // transaction might be pre-empted to service the client death
1893 // notification if the client process dies before linkToDeath is
1894 // invoked.
1895 sp<IBinder> remoteCallback = client->getRemote();
1896 if (remoteCallback != nullptr) {
1897 remoteCallback->linkToDeath(this);
1898 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001899}
1900
Austin Borgered99f642023-06-01 16:51:35 -07001901status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1902 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1903 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001904 /*out*/
1905 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001906 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001907 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001908 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001909 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001910 DescriptorPtr clientDescriptor;
1911 {
1912 if (effectiveApiLevel == API_1) {
1913 // If we are using API1, any existing client for this camera ID with the same remote
1914 // should be returned rather than evicted to allow MediaRecorder to work properly.
1915
1916 auto current = mActiveClientManager.get(cameraId);
1917 if (current != nullptr) {
1918 auto clientSp = current->getValue();
1919 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001920 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001921 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001922 " API level, evicting prior client...");
1923 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001924 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001925 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001926 *client = clientSp;
1927 return NO_ERROR;
1928 }
1929 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001930 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001931 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001932
Ruben Brunkcc776712015-02-17 20:18:47 -08001933 // Get state for the given cameraId
1934 auto state = getCameraState(cameraId);
1935 if (state == nullptr) {
1936 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001937 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001938 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001939 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001940 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001941
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001942 sp<IServiceManager> sm = defaultServiceManager();
1943 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08001944 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001945 // If processinfo service is not available and the client is automotive privileged
1946 // client used for safety critical uses cases such as rear-view and surround-view which
1947 // needs to be available before android boot completes, then use the hardcoded values
1948 // for the process state and priority score. As this scenario is before android system
1949 // services are up and client is native client, hence using NATIVE_ADJ as the priority
1950 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
1951 // visible on the top.
1952 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1953 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1954 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
1955 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
1956 } else {
1957 // Get current active client PIDs
1958 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1959 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001960
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001961 std::vector<int> priorityScores(ownerPids.size());
1962 std::vector<int> states(ownerPids.size());
1963
1964 // Get priority scores of all active PIDs
1965 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
1966 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
1967 if (err != OK) {
1968 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
1969 return err;
1970 }
1971
1972 // Update all active clients' priorities
1973 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
1974 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1975 pidToPriorityMap.emplace(ownerPids[i],
1976 resource_policy::ClientPriority(priorityScores[i], states[i],
1977 /* isVendorClient won't get copied over*/ false,
1978 /* oomScoreOffset won't get copied over*/ 0));
1979 }
1980 mActiveClientManager.updatePriorities(pidToPriorityMap);
1981
1982 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1983 int32_t actualState = states[states.size() - 1];
1984
1985 // Make descriptor for incoming client. We store the oomScoreOffset
1986 // since we might need it later on new handleEvictionsLocked and
1987 // ProcessInfoService would not take that into account.
1988 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1989 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1990 state->getConflicting(), actualScore, clientPid, actualState,
1991 oomScoreOffset, systemNativeClient);
1992 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001993
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001994 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1995
Ruben Brunkcc776712015-02-17 20:18:47 -08001996 // Find clients that would be evicted
1997 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1998
1999 // If the incoming client was 'evicted,' higher priority clients have the camera in the
2000 // background, so we cannot do evictions
2001 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2002 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2003 " priority).", clientPid);
2004
2005 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002006 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002007 auto incompatibleClients =
2008 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2009
Austin Borgered99f642023-06-01 16:51:35 -07002010 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2011 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2012 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002013 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002014
2015 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002016 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002017 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002018 i->getKey().c_str(),
2019 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002020 i->getOwnerId(), i->getPriority().getScore(),
2021 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002022 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002023 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2024 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002025 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002026 }
2027
2028 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002029 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002030 mEventLog.add(msg);
2031
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002032 auto current = mActiveClientManager.get(cameraId);
2033 if (current != nullptr) {
2034 return -EBUSY; // CAMERA_IN_USE
2035 } else {
2036 return -EUSERS; // MAX_CAMERAS_IN_USE
2037 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002038 }
2039
2040 for (auto& i : evicted) {
2041 sp<BasicClient> clientSp = i->getValue();
2042 if (clientSp.get() == nullptr) {
2043 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2044
2045 // TODO: Remove this
2046 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2047 __FUNCTION__);
2048 mActiveClientManager.remove(i);
2049 continue;
2050 }
2051
2052 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002053 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002054 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002055
Ruben Brunkcc776712015-02-17 20:18:47 -08002056 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002057 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002058 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2059 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002060 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002061 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002062 i->getPriority().getState(), cameraId.c_str(),
2063 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002064 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002065
2066 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002067 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002068 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002069 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002070 }
2071
Ruben Brunkcc776712015-02-17 20:18:47 -08002072 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2073 // other clients from connecting in mServiceLockWrapper if held
2074 mServiceLock.unlock();
2075
2076 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002077 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002078
2079 // Destroy evicted clients
2080 for (auto& i : evictedClients) {
2081 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002082 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002083 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002084
Austin Borger22c5c852024-03-08 13:31:36 -08002085 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002086
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002087 for (const auto& i : evictedClients) {
2088 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002089 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002090 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2091 if (ret == TIMED_OUT) {
2092 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002093 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2094 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002095 return -EBUSY;
2096 }
2097 if (ret != NO_ERROR) {
2098 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002099 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2100 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002101 return ret;
2102 }
2103 }
2104
2105 evictedClients.clear();
2106
Ruben Brunkcc776712015-02-17 20:18:47 -08002107 // Once clients have been disconnected, relock
2108 mServiceLock.lock();
2109
2110 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2111 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2112 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002113 }
2114
Ruben Brunkcc776712015-02-17 20:18:47 -08002115 *partial = clientDescriptor;
2116 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002117}
2118
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002119Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002120 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002121 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07002122 const std::string& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002123 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08002124 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002125 int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002126 int rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00002127 bool forceSlowJpegMode,
Biswarup Pal37a75182024-01-16 15:53:35 +00002128 int32_t deviceId,
2129 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002130 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002131 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002132 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002133 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002134
Biswarup Pal37a75182024-01-16 15:53:35 +00002135 std::string cameraIdStr = cameraIdIntToStr(api1CameraId, deviceId, devicePolicy);
2136 if (cameraIdStr.empty()) {
2137 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
2138 api1CameraId, deviceId);
2139 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2140 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2141 }
malikakashedb38962023-09-06 00:03:35 +00002142
Ruben Brunkcc776712015-02-17 20:18:47 -08002143 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002144 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
2145 clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002146 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002147 rotationOverride, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002148
Biswarup Pal37a75182024-01-16 15:53:35 +00002149 if (!ret.isOk()) {
2150 logRejected(cameraIdStr, getCallingPid(), clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002151 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002152 }
2153
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002154 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002155
2156 const sp<IServiceManager> sm(defaultServiceManager());
2157 const auto& mActivityManager = getActivityManager();
2158 if (mActivityManager) {
2159 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002160 getCallingUid(),
2161 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002162 }
2163
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002164 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002165}
2166
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002167bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2168 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002169 // If the client is not a vendor client, don't add listener if
2170 // a) the camera is a publicly hidden secure camera OR
2171 // b) the camera is a system only camera and the client doesn't
2172 // have android.permission.SYSTEM_CAMERA permissions.
2173 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2174 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002175 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002176 return true;
2177 }
2178 return false;
2179}
2180
Austin Borgered99f642023-06-01 16:51:35 -07002181bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002182 // Rules for rejection:
2183 // 1) If cameraserver tries to access this camera device, accept the
2184 // connection.
2185 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002186 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002187 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2188 // and the serving thread is a non hwbinder thread, the client must have
2189 // android.permission.SYSTEM_CAMERA permissions to connect.
2190
Austin Borger22c5c852024-03-08 13:31:36 -08002191 int cPid = getCallingPid();
2192 int cUid = getCallingUid();
2193 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002194 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2195 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002196 // This isn't a known camera ID, so it's not a system camera
2197 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2198 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002199 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002200
2201 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002202 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002203 return false;
2204 }
2205 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002206 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002207 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2208 return true;
2209 }
2210 // (3) Here we only check for permissions if it is a system only camera device. This is since
2211 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2212 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2213 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002214 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002215 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002216 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2217 cameraId.c_str());
2218 return true;
2219 }
2220
2221 return false;
2222}
2223
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002224Status CameraService::connectDevice(
2225 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002226 const std::string& unresolvedCameraId,
2227 const std::string& clientPackageName,
2228 const std::optional<std::string>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002229 int clientUid, int oomScoreOffset, int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002230 int rotationOverride, int32_t deviceId, int32_t devicePolicy,
Ruben Brunkcc776712015-02-17 20:18:47 -08002231 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002232 sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002233 ATRACE_CALL();
Emilian Peev31bd2422024-04-23 22:24:09 +00002234 RunThreadWithRealtimePriority priorityBump;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002235 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002236 sp<CameraDeviceClient> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002237 std::string clientPackageNameAdj = clientPackageName;
Austin Borger22c5c852024-03-08 13:31:36 -08002238 int callingPid = getCallingPid();
2239 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002240 bool systemNativeClient = false;
Austin Borger22c5c852024-03-08 13:31:36 -08002241 if (callerHasSystemUid() && (clientPackageNameAdj.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002242 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borgered99f642023-06-01 16:51:35 -07002243 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002244 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002245 }
Austin Borger249e6592024-03-10 22:28:11 -07002246
Biswarup Pal37a75182024-01-16 15:53:35 +00002247 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
malikakash98260df2024-05-10 23:33:57 +00002248 devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002249 if (!cameraIdOptional.has_value()) {
2250 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
2251 unresolvedCameraId.c_str(), deviceId);
2252 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2253 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2254 }
2255 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002256
2257 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002258 std::string msg =
2259 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
2260 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
2261 cameraId.c_str());
2262 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2263 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002264 }
2265
Austin Borger9bfa0a72022-08-03 17:50:40 -07002266 userid_t clientUserId = multiuser_get_user_id(clientUid);
Austin Borger9bfa0a72022-08-03 17:50:40 -07002267 if (clientUid == USE_CALLING_UID) {
2268 clientUserId = multiuser_get_user_id(callingUid);
2269 }
2270
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002271 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2272 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002273 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2274 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002275 std::string msg = "Camera disabled by device policy";
2276 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2277 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002278 }
2279
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002280 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002281 if (oomScoreOffset > 0
2282 && !hasPermissionsForSystemCamera(cameraId, callingPid,
Austin Borger249e6592024-03-10 22:28:11 -07002283 callingUid)
2284 && !isTrustedCallingUid(callingUid)) {
Austin Borgered99f642023-06-01 16:51:35 -07002285 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002286 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07002287 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2288 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2289 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002290 }
2291
Austin Borgered99f642023-06-01 16:51:35 -07002292 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
2293 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002294 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002295 targetSdkVersion, rotationOverride, /*forceSlowJpegMode*/false, unresolvedCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002296 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002297
Biswarup Pal37a75182024-01-16 15:53:35 +00002298 if (!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002299 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002300 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002301 }
2302
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002303 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002304 Mutex::Autolock lock(mServiceLock);
2305
2306 // Clear the previous cached logs and reposition the
2307 // file offset to beginning of the file to log new data.
2308 // If either truncate or lseek fails, close the previous file and create a new one.
2309 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2310 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2311 // Close the previous memfd.
2312 close(mMemFd);
2313 // If failure to wipe the data, then create a new file and
2314 // assign the new value to mMemFd.
2315 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2316 if (mMemFd == -1) {
2317 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2318 }
2319 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002320 const sp<IServiceManager> sm(defaultServiceManager());
2321 const auto& mActivityManager = getActivityManager();
2322 if (mActivityManager) {
2323 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002324 callingUid,
2325 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002326 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002327 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002328}
2329
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002330bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2331 int callingPid, int callingUid) {
2332 if (!isAutomotiveDevice()) {
2333 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2334 }
2335
2336 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2337 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2338 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2339 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2340 "using camera %s", callingUid, cam_id.c_str());
2341 return false;
2342 }
2343
2344 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2345 return true;
2346 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2347 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002348 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2349 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002350 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2351 return false;
2352 } else {
2353 return true;
2354 }
2355 }
2356 return false;
2357}
2358
Austin Borgered99f642023-06-01 16:51:35 -07002359std::string CameraService::getPackageNameFromUid(int clientUid) {
2360 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002361
Avichal Rakesh5788fec2024-03-15 14:39:20 -07002362 sp<IPermissionController> permCtrl;
2363 if (flags::cache_permission_services()) {
2364 permCtrl = getPermissionController();
2365 } else {
2366 sp<IServiceManager> sm = defaultServiceManager();
2367#pragma clang diagnostic push
2368#pragma clang diagnostic ignored "-Wdeprecated-declarations"
2369 // Using deprecated function to preserve functionality until the
2370 // cache_permission_services flag is removed.
2371 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
2372#pragma clang diagnostic pop
2373 if (binder == 0) {
2374 ALOGE("Cannot get permission service");
2375 permCtrl = nullptr;
2376 } else {
2377 permCtrl = interface_cast<IPermissionController>(binder);
2378 }
2379 }
2380
2381 if (permCtrl == nullptr) {
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002382 // Return empty package name and the further interaction
2383 // with camera will likely fail
2384 return packageName;
2385 }
2386
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002387 Vector<String16> packages;
2388
2389 permCtrl->getPackagesForUid(clientUid, packages);
2390
2391 if (packages.isEmpty()) {
2392 ALOGE("No packages for calling UID %d", clientUid);
2393 // Return empty package name and the further interaction
2394 // with camera will likely fail
2395 return packageName;
2396 }
2397
2398 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002399 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002400
2401 return packageName;
2402}
2403
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002404template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002405Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2406 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2407 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002408 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002409 int rotationOverride, bool forceSlowJpegMode,
2410 const std::string& originalCameraId, /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002411 binder::Status ret = binder::Status::ok();
2412
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002413 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002414 std::string clientPackageName;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002415 int packageUid = (clientUid == USE_CALLING_UID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002416 getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002417 if (clientPackageNameMaybe.size() <= 0) {
2418 // NDK calls don't come with package names, but we need one for various cases.
2419 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2420 // do exist. For all authentication cases, all packages under the same UID get the
2421 // same permissions, so picking any associated package name is sufficient. For some
2422 // other cases, this may give inaccurate names for clients in logs.
2423 isNonSystemNdk = true;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002424 clientPackageName = getPackageNameFromUid(packageUid);
2425 } else {
2426 clientPackageName = clientPackageNameMaybe;
2427 }
2428
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002429 int originalClientPid = 0;
2430
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002431 int packagePid = (clientPid == USE_CALLING_PID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002432 getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002433 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002434 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002435 static_cast<int>(effectiveApiLevel));
2436
Shuzhen Wang316781a2020-08-18 18:11:01 -07002437 nsecs_t openTimeNs = systemTime();
2438
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002439 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002440 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002441 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002442
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002443 {
2444 // Acquire mServiceLock and prevent other clients from connecting
2445 std::unique_ptr<AutoConditionLock> lock =
2446 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2447
2448 if (lock == nullptr) {
2449 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2450 , clientPid);
2451 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2452 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002453 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002454 }
2455
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002456 // Enforce client permissions and do basic validity checks
Biswarup Pal37a75182024-01-16 15:53:35 +00002457 if (!(ret = validateConnectLocked(cameraId, clientPackageName,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002458 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2459 return ret;
2460 }
2461
2462 // Check the shim parameters after acquiring lock, if they have already been updated and
2463 // we were doing a shim update, return immediately
2464 if (shimUpdateOnly) {
2465 auto cameraState = getCameraState(cameraId);
2466 if (cameraState != nullptr) {
2467 if (!cameraState->getShimParams().isEmpty()) return ret;
2468 }
2469 }
2470
2471 status_t err;
2472
2473 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002474 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002475 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002476 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2477 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002478 switch (err) {
2479 case -ENODEV:
2480 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2481 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002482 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002483 case -EBUSY:
2484 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2485 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002486 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002487 case -EUSERS:
2488 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2489 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002490 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002491 default:
2492 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2493 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002494 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002495 }
2496 }
2497
2498 if (clientTmp.get() != nullptr) {
2499 // Handle special case for API1 MediaRecorder where the existing client is returned
2500 device = static_cast<CLIENT*>(clientTmp.get());
2501 return ret;
2502 }
2503
2504 // give flashlight a chance to close devices if necessary.
2505 mFlashlight->prepareDeviceOpen(cameraId);
2506
Austin Borger18b30a72022-10-27 12:20:29 -07002507 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002508 auto deviceVersionAndTransport =
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002509 getDeviceVersion(cameraId, rotationOverride, /*out*/&portraitRotation,
Austin Borger18b30a72022-10-27 12:20:29 -07002510 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002511 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002512 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002513 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002514 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002515 }
2516
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002517 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002518 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002519 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002520
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002521 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002522 clientFeatureId, cameraId, api1CameraId, facing,
2523 orientation, clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002524 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002525 rotationOverride, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002526 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002527 return ret;
2528 }
2529 client = static_cast<CLIENT*>(tmp.get());
2530
2531 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2532 __FUNCTION__);
2533
Austin Borgered99f642023-06-01 16:51:35 -07002534 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002535 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002536 if (err != OK) {
2537 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002538 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002539 mServiceLock.unlock();
2540 client->disconnect();
2541 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002542 switch(err) {
2543 case BAD_VALUE:
2544 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002545 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002546 case -EBUSY:
2547 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002548 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002549 case -EUSERS:
2550 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2551 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002552 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002553 case PERMISSION_DENIED:
2554 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002555 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002556 case -EACCES:
2557 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002558 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002559 case -ENODEV:
2560 default:
2561 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002562 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002563 strerror(-err), err);
2564 }
2565 }
2566
2567 // Update shim paremeters for legacy clients
2568 if (effectiveApiLevel == API_1) {
2569 // Assume we have always received a Client subclass for API1
2570 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2571 String8 rawParams = shimClient->getParameters();
2572 CameraParameters params(rawParams);
2573
2574 auto cameraState = getCameraState(cameraId);
2575 if (cameraState != nullptr) {
2576 cameraState->setShimParams(params);
2577 } else {
2578 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002579 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002580 }
2581 }
2582
Ravneetaeb20dc2022-03-30 05:33:03 +00002583 // Enable/disable camera service watchdog
2584 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2585
Emilian Peev6d45db82024-01-18 20:11:54 +00002586 CameraMetadata chars;
2587 bool rotateAndCropSupported = true;
2588 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002589 &chars, rotationOverride);
Emilian Peev6d45db82024-01-18 20:11:54 +00002590 if (err == OK) {
2591 auto availableRotateCropEntry = chars.find(
2592 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2593 if (availableRotateCropEntry.count <= 1) {
2594 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002595 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002596 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002597 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2598 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002599 }
2600
Emilian Peev6d45db82024-01-18 20:11:54 +00002601 if (rotateAndCropSupported) {
2602 // Set rotate-and-crop override behavior
2603 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2604 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002605 } else if (rotationOverride != hardware::ICameraService::ROTATION_OVERRIDE_NONE &&
2606 portraitRotation != 0) {
Emilian Peev6d45db82024-01-18 20:11:54 +00002607 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2608 switch (portraitRotation) {
2609 case 90:
2610 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2611 break;
2612 case 180:
2613 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2614 break;
2615 case 270:
2616 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2617 break;
2618 default:
2619 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2620 break;
2621 }
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002622 // Here we're communicating to the client the chosen rotate
2623 // and crop mode to send to the HAL
Emilian Peev6d45db82024-01-18 20:11:54 +00002624 client->setRotateAndCropOverride(rotateAndCropMode);
2625 } else {
2626 client->setRotateAndCropOverride(
2627 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2628 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2629 }
2630 }
2631
2632 bool autoframingSupported = true;
2633 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2634 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2635 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2636 autoframingSupported = false;
2637 }
2638
2639 if (autoframingSupported) {
2640 // Set autoframing override behaviour
2641 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2642 client->setAutoframingOverride(mOverrideAutoframingMode);
2643 } else {
2644 client->setAutoframingOverride(
2645 mCameraServiceProxyWrapper->getAutoframingOverride(
2646 clientPackageName));
2647 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002648 }
2649
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002650 bool isCameraPrivacyEnabled;
2651 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002652 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002653 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2654 toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2655 } else {
2656 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002657 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002658 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002659
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002660 if (client->supportsCameraMute()) {
2661 client->setCameraMute(
2662 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2663 } else if (isCameraPrivacyEnabled) {
2664 // no camera mute supported, but privacy is on! => disconnect
2665 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2666 client->getPackageName().c_str(), cameraId.c_str());
2667 // Do not hold mServiceLock while disconnecting clients, but
2668 // retain the condition blocking other clients from connecting
2669 // in mServiceLockWrapper if held.
2670 mServiceLock.unlock();
2671 // Clear caller identity temporarily so client disconnect PID
2672 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002673 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002674 // Note AppOp to trigger the "Unblock" dialog
2675 client->noteAppOp();
2676 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002677 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002678 // Reacquire mServiceLock
2679 mServiceLock.lock();
2680
2681 return STATUS_ERROR_FMT(ERROR_DISABLED,
2682 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002683 }
2684
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002685 if (shimUpdateOnly) {
2686 // If only updating legacy shim parameters, immediately disconnect client
2687 mServiceLock.unlock();
2688 client->disconnect();
2689 mServiceLock.lock();
2690 } else {
2691 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002692 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002693 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002694
2695 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002696 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002697 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002698 } // lock is destroyed, allow further connect calls
2699
2700 // Important: release the mutex here so the client can call back into the service from its
2701 // destructor (can be at the end of the call)
2702 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002703
2704 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002705 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002706 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002707
Cliff Wud3a05312021-04-26 23:07:31 +08002708 {
2709 Mutex::Autolock lock(mInjectionParametersLock);
2710 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2711 mInjectionInitPending = false;
2712 status_t res = NO_ERROR;
2713 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2714 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002715 sp<BasicClient> clientSp = clientDescriptor->getValue();
2716 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2717 if(res != OK) {
2718 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2719 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002720 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002721 }
2722 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002723 if (res != OK) {
2724 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2725 }
2726 } else {
2727 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002728 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002729 res = NO_INIT;
2730 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2731 }
2732 }
2733 }
2734
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002735 return ret;
2736}
2737
Austin Borgered99f642023-06-01 16:51:35 -07002738status_t CameraService::addOfflineClient(const std::string &cameraId,
2739 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002740 if (offlineClient.get() == nullptr) {
2741 return BAD_VALUE;
2742 }
2743
2744 {
2745 // Acquire mServiceLock and prevent other clients from connecting
2746 std::unique_ptr<AutoConditionLock> lock =
2747 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2748
2749 if (lock == nullptr) {
2750 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2751 , __FUNCTION__, offlineClient->getClientPid());
2752 return TIMED_OUT;
2753 }
2754
2755 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2756 if (onlineClientDesc.get() == nullptr) {
2757 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2758 cameraId.c_str());
2759 return BAD_VALUE;
2760 }
2761
2762 // Offline clients do not evict or conflict with other online devices. Resource sharing
2763 // conflicts are handled by the camera provider which will either succeed or fail before
2764 // reaching this method.
2765 const auto& onlinePriority = onlineClientDesc->getPriority();
2766 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2767 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002768 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002769 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002770 // native clients don't have offline processing support.
2771 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002772 if (offlineClientDesc == nullptr) {
2773 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2774 return BAD_VALUE;
2775 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002776
2777 // Allow only one offline device per camera
2778 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2779 if (!incompatibleClients.empty()) {
2780 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2781 return BAD_VALUE;
2782 }
2783
Austin Borgered99f642023-06-01 16:51:35 -07002784 std::string monitorTags = isClientWatched(offlineClient.get())
2785 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002786 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002787 if (err != OK) {
2788 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2789 return err;
2790 }
2791
2792 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2793 if (evicted.size() > 0) {
2794 for (auto& i : evicted) {
2795 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002796 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002797 }
2798
2799 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2800 "properly", __FUNCTION__);
2801
2802 return BAD_VALUE;
2803 }
2804
2805 logConnectedOffline(offlineClientDesc->getKey(),
2806 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002807 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002808
2809 sp<IBinder> remoteCallback = offlineClient->getRemote();
2810 if (remoteCallback != nullptr) {
2811 remoteCallback->linkToDeath(this);
2812 }
2813 } // lock is destroyed, allow further connect calls
2814
2815 return OK;
2816}
2817
Austin Borgered99f642023-06-01 16:51:35 -07002818Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +00002819 int32_t torchStrength, const sp<IBinder>& clientBinder, int32_t deviceId,
2820 int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002821 Mutex::Autolock lock(mServiceLock);
2822
2823 ATRACE_CALL();
2824 if (clientBinder == nullptr) {
2825 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2826 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2827 "Torch client binder in null.");
2828 }
2829
Austin Borger22c5c852024-03-08 13:31:36 -08002830 int uid = getCallingUid();
Biswarup Pal37a75182024-01-16 15:53:35 +00002831 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
malikakash98260df2024-05-10 23:33:57 +00002832 devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002833 if (!cameraIdOptional.has_value()) {
2834 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
2835 unresolvedCameraId.c_str(), deviceId);
2836 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2837 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2838 }
2839 std::string cameraId = cameraIdOptional.value();
2840
Austin Borgered99f642023-06-01 16:51:35 -07002841 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002842 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002843 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002844 }
2845
2846 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002847 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002848 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002849 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002850 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002851 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002852 }
2853
2854 StatusInternal cameraStatus = state->getStatus();
2855 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2856 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002857 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002858 (int)cameraStatus);
2859 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 {
2864 Mutex::Autolock al(mTorchStatusMutex);
2865 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002866 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002867 if (err != OK) {
2868 if (err == NAME_NOT_FOUND) {
2869 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002870 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002871 }
2872 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002873 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002874 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2875 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002876 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002877 }
2878
2879 if (status == TorchModeStatus::NOT_AVAILABLE) {
2880 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2881 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002882 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002883 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2884 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002885 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002886 } else {
2887 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002888 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002889 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2890 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002891 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002892 }
2893 }
2894 }
2895
2896 {
2897 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002898 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002899 }
2900 // Check if the current torch strength level is same as the new one.
2901 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002902 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002903
Austin Borgered99f642023-06-01 16:51:35 -07002904 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002905
2906 if (err != OK) {
2907 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002908 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002909 switch (err) {
2910 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002911 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2912 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002913 errorCode = ERROR_ILLEGAL_ARGUMENT;
2914 break;
2915 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002916 msg = fmt::sprintf("Camera \"%s\" is in use",
2917 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002918 errorCode = ERROR_CAMERA_IN_USE;
2919 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002920 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002921 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002922 "valid range.", torchStrength);
2923 errorCode = ERROR_ILLEGAL_ARGUMENT;
2924 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002925 default:
Austin Borgered99f642023-06-01 16:51:35 -07002926 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002927 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002928 }
Austin Borgered99f642023-06-01 16:51:35 -07002929 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2930 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002931 }
2932
2933 {
2934 // update the link to client's death
2935 // Store the last client that turns on each camera's torch mode.
2936 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002937 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002938 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002939 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002940 } else {
2941 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2942 mTorchClientMap.replaceValueAt(index, clientBinder);
2943 }
2944 clientBinder->linkToDeath(this);
2945 }
2946
Austin Borger22c5c852024-03-08 13:31:36 -08002947 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002948 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002949 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002950 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002951 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002952 }
2953 return Status::ok();
2954}
2955
malikakash73125c62023-07-21 22:44:34 +00002956Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Biswarup Pal37a75182024-01-16 15:53:35 +00002957 const sp<IBinder>& clientBinder, int32_t deviceId, int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002958 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002959
2960 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002961 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002962 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002963 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2964 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002965 }
2966
Austin Borger22c5c852024-03-08 13:31:36 -08002967 int uid = getCallingUid();
Biswarup Pal37a75182024-01-16 15:53:35 +00002968 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
malikakash98260df2024-05-10 23:33:57 +00002969 devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002970 if (!cameraIdOptional.has_value()) {
2971 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
2972 unresolvedCameraId.c_str(), deviceId);
2973 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2974 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2975 }
2976 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002977
Austin Borgered99f642023-06-01 16:51:35 -07002978 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002979 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07002980 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002981 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002982 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07002983 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08002984 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002985 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002986 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002987 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002988 }
2989
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002990 StatusInternal cameraStatus = state->getStatus();
2991 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002992 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07002993 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
2994 (int)cameraStatus);
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());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002997 }
2998
2999 {
3000 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003001 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003002 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003003 if (err != OK) {
3004 if (err == NAME_NOT_FOUND) {
3005 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003006 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003007 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003008 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003009 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003010 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07003011 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003012 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003013 }
3014
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003015 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003016 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003017 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003018 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003019 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3020 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003021 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003022 } else {
3023 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003024 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003025 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3026 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003027 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003028 }
3029 }
3030 }
3031
Ruben Brunk99e69712015-05-26 17:25:07 -07003032 {
3033 // Update UID map - this is used in the torch status changed callbacks, so must be done
3034 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003035 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003036 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003037 }
3038
Austin Borgered99f642023-06-01 16:51:35 -07003039 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003040
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003041 if (err != OK) {
3042 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003043 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003044 switch (err) {
3045 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003046 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3047 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003048 errorCode = ERROR_ILLEGAL_ARGUMENT;
3049 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003050 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003051 msg = fmt::sprintf("Camera \"%s\" is in use",
3052 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003053 errorCode = ERROR_CAMERA_IN_USE;
3054 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003055 default:
Austin Borgered99f642023-06-01 16:51:35 -07003056 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003057 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003058 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003059 errorCode = ERROR_INVALID_OPERATION;
3060 }
Austin Borgered99f642023-06-01 16:51:35 -07003061 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3062 logServiceError(msg, errorCode);
3063 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003064 }
3065
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003066 {
3067 // update the link to client's death
3068 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003069 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003070 if (enabled) {
3071 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003072 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003073 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003074 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003075 mTorchClientMap.replaceValueAt(index, clientBinder);
3076 }
3077 clientBinder->linkToDeath(this);
3078 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003079 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003080 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003081 }
3082
Austin Borger22c5c852024-03-08 13:31:36 -08003083 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003084 std::string torchState = enabled ? "on" : "off";
3085 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3086 torchState.c_str(), clientPid);
3087 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003088 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003089}
3090
Austin Borgered99f642023-06-01 16:51:35 -07003091void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3092 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3093 mTorchUidMap[cameraId].first = uid;
3094 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003095 } else {
3096 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003097 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003098 }
3099}
3100
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003101Status CameraService::notifySystemEvent(int32_t eventId,
3102 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003103 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003104 const int selfPid = getpid();
3105
3106 // Permission checks
3107 if (pid != selfPid) {
3108 // Ensure we're being called by system_server, or similar process with
3109 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003110 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003111 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003112 ALOGE("Permission Denial: cannot send updates to camera service about system"
3113 " events from pid=%d, uid=%d", pid, uid);
3114 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003115 "No permission to send updates to camera service about system events"
3116 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003117 }
3118 }
3119
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003120 ATRACE_CALL();
3121
Ruben Brunk36597b22015-03-20 22:15:57 -07003122 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003123 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003124 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003125 // from a system server crash
3126 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003127 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003128 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003129 break;
3130 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003131 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3132 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003133 if (args.size() != 1) {
3134 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3135 "USB Device Event requires 1 argument");
3136 }
3137
Valentin Iftime29e2e152021-08-13 15:17:33 +02003138 // Notify CameraProviderManager for lazy HALs
3139 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3140 std::to_string(args[0]));
3141 break;
3142 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003143 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003144 default: {
3145 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3146 eventId);
3147 break;
3148 }
3149 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003150 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003151}
3152
Emilian Peev53722fa2019-02-22 17:47:20 -08003153void CameraService::notifyMonitoredUids() {
3154 Mutex::Autolock lock(mStatusListenerLock);
3155
3156 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003157 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003158 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3159 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003160 }
3161}
3162
Austin Borgerdddb7552023-03-30 17:53:01 -07003163void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3164 Mutex::Autolock lock(mStatusListenerLock);
3165
3166 for (const auto& it : mListenerList) {
3167 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3168 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3169 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3170 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3171 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3172 }
3173 }
3174}
3175
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003176Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003177 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003178 const int selfPid = getpid();
3179
3180 // Permission checks
3181 if (pid != selfPid) {
3182 // Ensure we're being called by system_server, or similar process with
3183 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003184 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003185 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003186 ALOGE("Permission Denial: cannot send updates to camera service about device"
3187 " state changes from pid=%d, uid=%d", pid, uid);
3188 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3189 "No permission to send updates to camera service about device state"
3190 " changes from pid=%d, uid=%d", pid, uid);
3191 }
3192 }
3193
3194 ATRACE_CALL();
3195
Austin Borger18b30a72022-10-27 12:20:29 -07003196 {
3197 Mutex::Autolock lock(mServiceLock);
3198 mDeviceState = newState;
3199 }
3200
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003201 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003202
3203 return Status::ok();
3204}
3205
Emilian Peev8b64f282021-03-25 16:49:57 -07003206Status CameraService::notifyDisplayConfigurationChange() {
3207 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003208 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003209 const int selfPid = getpid();
3210
3211 // Permission checks
3212 if (callingPid != selfPid) {
3213 // Ensure we're being called by system_server, or similar process with
3214 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003215 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003216 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003217 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3218 " changes from pid=%d, uid=%d", callingPid, uid);
3219 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3220 "No permission to send updates to camera service about orientation"
3221 " changes from pid=%d, uid=%d", callingPid, uid);
3222 }
3223 }
3224
3225 Mutex::Autolock lock(mServiceLock);
3226
3227 // Don't do anything if rotate-and-crop override via cmd is active
3228 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3229
3230 const auto clients = mActiveClientManager.getAll();
3231 for (auto& current : clients) {
3232 if (current != nullptr) {
3233 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003234 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3235 basicClient->setRotateAndCropOverride(
3236 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3237 basicClient->getPackageName(),
3238 basicClient->getCameraFacing(),
3239 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003240 }
3241 }
3242 }
3243
3244 return Status::ok();
3245}
3246
3247Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003248 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3249 ATRACE_CALL();
3250 if (!concurrentCameraIds) {
3251 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3252 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3253 }
3254
3255 if (!mInitialized) {
3256 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003257 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003258 return STATUS_ERROR(ERROR_DISCONNECTED,
3259 "Camera subsystem is not available");
3260 }
3261 // First call into the provider and get the set of concurrent camera
3262 // combinations
3263 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003264 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003265 for (auto &combination : concurrentCameraCombinations) {
Biswarup Pal7d072862024-04-17 15:24:47 +00003266 std::vector<std::pair<std::string, int32_t>> validCombination;
3267 int32_t firstDeviceId = kInvalidDeviceId;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003268 for (auto &cameraId : combination) {
3269 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003270 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003271 if (state == nullptr) {
3272 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3273 continue;
3274 }
3275 StatusInternal status = state->getStatus();
3276 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3277 continue;
3278 }
Austin Borgered99f642023-06-01 16:51:35 -07003279 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003280 continue;
3281 }
Biswarup Pal7d072862024-04-17 15:24:47 +00003282 auto [cameraOwnerDeviceId, mappedCameraId] =
3283 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
3284 if (firstDeviceId == kInvalidDeviceId) {
3285 firstDeviceId = cameraOwnerDeviceId;
3286 } else if (firstDeviceId != cameraOwnerDeviceId) {
3287 // Found an invalid combination which contains cameras with different device id's,
3288 // hence discard it.
3289 validCombination.clear();
3290 break;
3291 }
3292 validCombination.push_back({mappedCameraId, cameraOwnerDeviceId});
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003293 }
3294 if (validCombination.size() != 0) {
3295 concurrentCameraIds->push_back(std::move(validCombination));
3296 }
3297 }
3298 return Status::ok();
3299}
3300
3301Status CameraService::isConcurrentSessionConfigurationSupported(
3302 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Biswarup Pal7d072862024-04-17 15:24:47 +00003303 int targetSdkVersion, int32_t deviceId, int32_t devicePolicy,
3304 /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003305 if (!isSupported) {
3306 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3307 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3308 }
3309
3310 if (!mInitialized) {
3311 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3312 return STATUS_ERROR(ERROR_DISCONNECTED,
3313 "Camera subsystem is not available");
3314 }
3315
Biswarup Pal7d072862024-04-17 15:24:47 +00003316 for (auto cameraIdAndSessionConfiguration : cameraIdsAndSessionConfigurations) {
3317 std::optional<std::string> cameraIdOptional =
malikakash98260df2024-05-10 23:33:57 +00003318 resolveCameraId(cameraIdAndSessionConfiguration.mCameraId, deviceId, devicePolicy);
Biswarup Pal7d072862024-04-17 15:24:47 +00003319 if (!cameraIdOptional.has_value()) {
3320 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
3321 cameraIdAndSessionConfiguration.mCameraId.c_str(), deviceId);
3322 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3323 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3324 }
3325 cameraIdAndSessionConfiguration.mCameraId = cameraIdOptional.value();
3326 }
3327
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003328 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003329 int callingPid = getCallingPid();
3330 int callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003331 bool hasCameraPermission = ((callingPid == getpid()) ||
Biswarup Pal7d072862024-04-17 15:24:47 +00003332 hasPermissionsForCamera(callingPid, callingUid,
3333 devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT
3334 ? kDefaultDeviceId : deviceId));
Austin Borger249e6592024-03-10 22:28:11 -07003335 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003336 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3337 "android.permission.CAMERA needed to call"
3338 "isConcurrentSessionConfigurationSupported");
3339 }
3340
3341 status_t res =
3342 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003343 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3344 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003345 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003346 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003347 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003348 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3349 "support %s (%d)", strerror(-res), res);
3350 }
3351 return Status::ok();
3352}
3353
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003354Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3355 /*out*/
3356 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003357 return addListenerHelper(listener, cameraStatuses);
3358}
3359
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003360binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3361 std::vector<hardware::CameraStatus>* cameraStatuses) {
3362 return addListenerHelper(listener, cameraStatuses, false, true);
3363}
3364
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003365Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3366 /*out*/
3367 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003368 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003369 ATRACE_CALL();
3370
Igor Murashkinbfc99152013-02-27 12:55:20 -08003371 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003372
Ruben Brunk3450ba72015-06-16 11:00:37 -07003373 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003374 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003375 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003376 }
3377
Austin Borger22c5c852024-03-08 13:31:36 -08003378 auto clientPid = getCallingPid();
3379 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003380 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003381
Igor Murashkinbfc99152013-02-27 12:55:20 -08003382 Mutex::Autolock lock(mServiceLock);
3383
Ruben Brunkcc776712015-02-17 20:18:47 -08003384 {
3385 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003386 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003387 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003388 ALOGW("%s: Tried to add listener %p which was already subscribed",
3389 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003390 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003391 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003392 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003393
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003394 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003395 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3396 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003397 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003398 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003399 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003400 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003401 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3402 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3403 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003404 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003405 // The listener still needs to be added to the list of listeners, regardless of what
3406 // permissions the listener process has / whether it is a vendor listener. Since it might be
3407 // eligible to listen to other camera ids.
3408 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003409 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003410 }
3411
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003412 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003413 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003414 Mutex::Autolock lock(mCameraStatesLock);
3415 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003416 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3417 auto [deviceId, mappedCameraId] =
3418 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3419
3420 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003421 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003422 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3423 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003424 }
3425 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003426 // Remove the camera statuses that should be hidden from the client, we do
3427 // this after collecting the states in order to avoid holding
3428 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3429 // the same time.
3430 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3431 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003432 std::string cameraId = s.cameraId;
3433 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
malikakash98260df2024-05-10 23:33:57 +00003434 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM);
Biswarup Pal37a75182024-01-16 15:53:35 +00003435 if (!cameraIdOptional.has_value()) {
3436 std::string msg =
3437 fmt::sprintf(
3438 "Camera %s: Invalid camera id for device id %d",
3439 s.cameraId.c_str(), s.deviceId);
3440 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3441 return true;
3442 }
3443 cameraId = cameraIdOptional.value();
3444 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3445 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3446 ALOGE("%s: Invalid camera id %s, skipping status update",
3447 __FUNCTION__, s.cameraId.c_str());
3448 return true;
3449 }
3450 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3451 clientUid);
3452 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003453
Biswarup Pal37a75182024-01-16 15:53:35 +00003454 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003455 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003456 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003457 // Add only default device cameras here, as virtual cameras currently don't support torch
3458 // anyway. Note that this is a simplification of the implementation here, and we should
3459 // change this when virtual cameras support torch.
3460 if (s.deviceId == kDefaultDeviceId) {
3461 idsChosenForCallback.insert(s.cameraId);
3462 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003463 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003464
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003465 /*
3466 * Immediately signal current torch status to this listener only
3467 * This may be a subset of all the devices, so don't include it in the response directly
3468 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003469 {
3470 Mutex::Autolock al(mTorchStatusMutex);
3471 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003472 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003473 // The camera id is visible to the client. Fine to send torch
3474 // callback.
3475 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003476 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3477 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003478 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003479 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003480 }
3481
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003482 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003483}
Ruben Brunkcc776712015-02-17 20:18:47 -08003484
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003485Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003486 ATRACE_CALL();
3487
Igor Murashkinbfc99152013-02-27 12:55:20 -08003488 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3489
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003490 if (listener == 0) {
3491 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003492 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003493 }
3494
Igor Murashkinbfc99152013-02-27 12:55:20 -08003495 Mutex::Autolock lock(mServiceLock);
3496
Ruben Brunkcc776712015-02-17 20:18:47 -08003497 {
3498 Mutex::Autolock lock(mStatusListenerLock);
3499 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003500 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003501 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003502 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003503 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003504 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003505 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003506 }
3507 }
3508
3509 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3510 __FUNCTION__, listener.get());
3511
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003512 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003513}
3514
Austin Borgered99f642023-06-01 16:51:35 -07003515Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003516
3517 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003518 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3519
3520 if (parameters == NULL) {
3521 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003522 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003523 }
3524
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003525 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003526
3527 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003528 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003529 // Error logged by caller
3530 return ret;
3531 }
3532
3533 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003534
Austin Borgered99f642023-06-01 16:51:35 -07003535 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003536
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003537 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003538}
3539
malikakash98260df2024-05-10 23:33:57 +00003540Status CameraService::supportsCameraApi(const std::string& cameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003541 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003542 ATRACE_CALL();
3543
Austin Borgered99f642023-06-01 16:51:35 -07003544 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003545
3546 switch (apiVersion) {
3547 case API_VERSION_1:
3548 case API_VERSION_2:
3549 break;
3550 default:
Austin Borgered99f642023-06-01 16:51:35 -07003551 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3552 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3553 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003554 }
3555
Austin Borger18b30a72022-10-27 12:20:29 -07003556 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00003557 auto deviceVersionAndTransport =
3558 getDeviceVersion(cameraId,
3559 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
3560 &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003561 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003562 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3563 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3564 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003565 }
3566 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3567 int deviceVersion = deviceVersionAndTransport.first;
3568 switch (deviceVersion) {
3569 case CAMERA_DEVICE_API_VERSION_1_0:
3570 case CAMERA_DEVICE_API_VERSION_3_0:
3571 case CAMERA_DEVICE_API_VERSION_3_1:
3572 if (apiVersion == API_VERSION_2) {
3573 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003574 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003575 *isSupported = false;
3576 } else { // if (apiVersion == API_VERSION_1) {
3577 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003578 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003579 *isSupported = true;
3580 }
3581 break;
3582 case CAMERA_DEVICE_API_VERSION_3_2:
3583 case CAMERA_DEVICE_API_VERSION_3_3:
3584 case CAMERA_DEVICE_API_VERSION_3_4:
3585 case CAMERA_DEVICE_API_VERSION_3_5:
3586 case CAMERA_DEVICE_API_VERSION_3_6:
3587 case CAMERA_DEVICE_API_VERSION_3_7:
3588 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003589 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003590 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003591 break;
3592 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003593 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3594 deviceVersion, cameraId.c_str());
3595 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3596 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003597 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003598 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003599 } else {
3600 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003601 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003602 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003603}
3604
malikakash98260df2024-05-10 23:33:57 +00003605Status CameraService::isHiddenPhysicalCamera(const std::string& cameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003606 /*out*/ bool *isSupported) {
3607 ATRACE_CALL();
3608
Austin Borgered99f642023-06-01 16:51:35 -07003609 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3610 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003611
3612 return Status::ok();
3613}
3614
Cliff Wud8cae102021-03-11 01:37:42 +08003615Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003616 const std::string& packageName, const std::string& internalCamId,
3617 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003618 const sp<ICameraInjectionCallback>& callback,
3619 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003620 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003621 ATRACE_CALL();
3622
Austin Borgered99f642023-06-01 16:51:35 -07003623 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003624 const int pid = getCallingPid();
3625 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003626 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3627 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003628 "Permission Denial: no permission to inject camera");
3629 }
3630
3631 // Do not allow any camera injection that injects or replaces a virtual camera.
3632 auto [deviceIdForInternalCamera, _] =
3633 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3634 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3635 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3636 "Cannot replace a virtual camera");
3637 }
3638 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3639 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3640 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3641 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3642 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003643 }
3644
3645 ALOGV(
3646 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3647 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003648 __FUNCTION__, packageName.c_str(),
3649 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003650
Cliff Wud3a05312021-04-26 23:07:31 +08003651 {
3652 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003653 mInjectionInternalCamId = internalCamId;
3654 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003655 mInjectionStatusListener->addListener(callback);
3656 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003657 status_t res = NO_ERROR;
3658 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3659 // If the client already exists, we can directly connect to the camera device through the
3660 // client's injectCamera(), otherwise we need to wait until the client is established
3661 // (execute connectHelper()) before injecting the camera to the camera device.
3662 if (clientDescriptor != nullptr) {
3663 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003664 sp<BasicClient> clientSp = clientDescriptor->getValue();
3665 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3666 if(res != OK) {
3667 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3668 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003669 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003670 }
3671 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003672 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003673 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3674 }
3675 } else {
3676 mInjectionInitPending = true;
3677 }
3678 }
Cliff Wud8cae102021-03-11 01:37:42 +08003679
Cliff Wud3a05312021-04-26 23:07:31 +08003680 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003681}
3682
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003683Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003684 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003685 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3686 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3687 return Status::ok();
3688}
3689
Ruben Brunkcc776712015-02-17 20:18:47 -08003690void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003691 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003692 for (auto& i : mActiveClientManager.getAll()) {
3693 auto clientSp = i->getValue();
3694 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003695 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003696 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003697 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003698 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003699 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003700}
3701
Ruben Brunkcc776712015-02-17 20:18:47 -08003702bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003703 bool ret = false;
3704 {
3705 // Acquire mServiceLock and prevent other clients from connecting
3706 std::unique_ptr<AutoConditionLock> lock =
3707 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003708
Ruben Brunkcc776712015-02-17 20:18:47 -08003709 std::vector<sp<BasicClient>> evicted;
3710 for (auto& i : mActiveClientManager.getAll()) {
3711 auto clientSp = i->getValue();
3712 if (clientSp.get() == nullptr) {
3713 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3714 mActiveClientManager.remove(i);
3715 continue;
3716 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003717 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003718 mActiveClientManager.remove(i);
3719 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003720
Ruben Brunkcc776712015-02-17 20:18:47 -08003721 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003722 clientSp->notifyError(
3723 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003724 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003725 }
3726 }
3727
Ruben Brunkcc776712015-02-17 20:18:47 -08003728 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3729 // other clients from connecting in mServiceLockWrapper if held
3730 mServiceLock.unlock();
3731
Ruben Brunk36597b22015-03-20 22:15:57 -07003732 // Do not clear caller identity, remote caller should be client proccess
3733
Ruben Brunkcc776712015-02-17 20:18:47 -08003734 for (auto& i : evicted) {
3735 if (i.get() != nullptr) {
3736 i->disconnect();
3737 ret = true;
3738 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003739 }
3740
Ruben Brunkcc776712015-02-17 20:18:47 -08003741 // Reacquire mServiceLock
3742 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003743
Ruben Brunkcc776712015-02-17 20:18:47 -08003744 } // lock is destroyed, allow further connect calls
3745
3746 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003747}
3748
Ruben Brunkcc776712015-02-17 20:18:47 -08003749std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003750 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003751 std::shared_ptr<CameraState> state;
3752 {
3753 Mutex::Autolock lock(mCameraStatesLock);
3754 auto iter = mCameraStates.find(cameraId);
3755 if (iter != mCameraStates.end()) {
3756 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003757 }
3758 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003759 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003760}
3761
Austin Borgered99f642023-06-01 16:51:35 -07003762sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003763 // Remove from active clients list
3764 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3765 if (clientDescriptorPtr == nullptr) {
3766 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003767 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003768 return sp<BasicClient>{nullptr};
3769 }
3770
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003771 sp<BasicClient> client = clientDescriptorPtr->getValue();
3772 if (client.get() != nullptr) {
3773 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3774 }
3775 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003776}
3777
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003778void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003779 // Acquire mServiceLock and prevent other clients from connecting
3780 std::unique_ptr<AutoConditionLock> lock =
3781 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3782
Ruben Brunk6267b532015-04-30 17:44:07 -07003783 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003784 for (size_t i = 0; i < newUserIds.size(); i++) {
3785 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003786 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003787 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003788 return;
3789 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003790 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003791 }
3792
Ruben Brunka8ca9152015-04-07 14:23:40 -07003793
Ruben Brunk6267b532015-04-30 17:44:07 -07003794 if (newAllowedUsers == mAllowedUsers) {
3795 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3796 return;
3797 }
3798
3799 logUserSwitch(mAllowedUsers, newAllowedUsers);
3800
3801 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003802
3803 // Current user has switched, evict all current clients.
3804 std::vector<sp<BasicClient>> evicted;
3805 for (auto& i : mActiveClientManager.getAll()) {
3806 auto clientSp = i->getValue();
3807
3808 if (clientSp.get() == nullptr) {
3809 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3810 continue;
3811 }
3812
Ruben Brunk6267b532015-04-30 17:44:07 -07003813 // Don't evict clients that are still allowed.
3814 uid_t clientUid = clientSp->getClientUid();
3815 userid_t clientUserId = multiuser_get_user_id(clientUid);
3816 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3817 continue;
3818 }
3819
Ruben Brunk36597b22015-03-20 22:15:57 -07003820 evicted.push_back(clientSp);
3821
Ruben Brunk36597b22015-03-20 22:15:57 -07003822 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003823 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003824
Ruben Brunk36597b22015-03-20 22:15:57 -07003825 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003826 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003827 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003828 " to user switch.", i->getKey().c_str(),
3829 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003830 i->getOwnerId(), i->getPriority().getScore(),
3831 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003832
3833 }
3834
3835 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3836 // blocking other clients from connecting in mServiceLockWrapper if held.
3837 mServiceLock.unlock();
3838
3839 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08003840 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003841
3842 for (auto& i : evicted) {
3843 i->disconnect();
3844 }
3845
Austin Borger22c5c852024-03-08 13:31:36 -08003846 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003847
3848 // Reacquire mServiceLock
3849 mServiceLock.lock();
3850}
Ruben Brunkcc776712015-02-17 20:18:47 -08003851
Austin Borgered99f642023-06-01 16:51:35 -07003852void CameraService::logEvent(const std::string &event) {
3853 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003854 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003855 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003856 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003857 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003858 mEventLog.add(msg);
3859 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3860 // Error event not added to the dumpsys log before
3861 mEventLog.add(msg);
3862 sServiceErrorEventSet.insert(msg);
3863 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003864}
3865
Austin Borgered99f642023-06-01 16:51:35 -07003866void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3867 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003868 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003869 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3870 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003871}
3872
Austin Borgered99f642023-06-01 16:51:35 -07003873void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3874 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003875 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003876 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3877 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003878}
3879
Austin Borgered99f642023-06-01 16:51:35 -07003880void CameraService::logConnected(const std::string &cameraId, int clientPid,
3881 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003882 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003883 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3884 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003885}
3886
Austin Borgered99f642023-06-01 16:51:35 -07003887void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3888 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003889 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003890 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3891 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003892}
3893
Austin Borgered99f642023-06-01 16:51:35 -07003894void CameraService::logRejected(const std::string &cameraId, int clientPid,
3895 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003896 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003897 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3898 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003899}
3900
Austin Borgered99f642023-06-01 16:51:35 -07003901void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3902 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003903 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003904 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3905 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003906}
3907
Ruben Brunk6267b532015-04-30 17:44:07 -07003908void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3909 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003910 std::string newUsers = toString(newUserIds);
3911 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003912 if (oldUsers.size() == 0) {
3913 oldUsers = "<None>";
3914 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003915 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003916 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3917 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003918}
3919
Austin Borgered99f642023-06-01 16:51:35 -07003920void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003921 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003922 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003923}
3924
Austin Borgered99f642023-06-01 16:51:35 -07003925void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003926 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003927 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003928}
3929
Austin Borgered99f642023-06-01 16:51:35 -07003930void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003931 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003932 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003933}
3934
Austin Borgered99f642023-06-01 16:51:35 -07003935void CameraService::logServiceError(const std::string &msg, int errorCode) {
3936 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3937 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003938}
3939
Ruben Brunk36597b22015-03-20 22:15:57 -07003940status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3941 uint32_t flags) {
3942
Mathias Agopian65ab4712010-07-14 17:59:35 -07003943 // Permission checks
3944 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003945 case SHELL_COMMAND_TRANSACTION: {
3946 int in = data.readFileDescriptor();
3947 int out = data.readFileDescriptor();
3948 int err = data.readFileDescriptor();
3949 int argc = data.readInt32();
3950 Vector<String16> args;
3951 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3952 args.add(data.readString16());
3953 }
3954 sp<IBinder> unusedCallback;
3955 sp<IResultReceiver> resultReceiver;
3956 status_t status;
3957 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3958 return status;
3959 }
3960 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3961 return status;
3962 }
3963 status = shellCommand(in, out, err, args);
3964 if (resultReceiver != nullptr) {
3965 resultReceiver->send(status);
3966 }
3967 return NO_ERROR;
3968 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003969 }
3970
3971 return BnCameraService::onTransact(code, data, reply, flags);
3972}
3973
Mathias Agopian65ab4712010-07-14 17:59:35 -07003974// We share the media players for shutter and recording sound for all clients.
3975// A reference count is kept to determine when we will actually release the
3976// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09003977sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3978 sp<MediaPlayer> mp = new MediaPlayer();
3979 status_t error;
3980 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003981 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003982 error = mp->prepare();
3983 }
3984 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003985 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003986 mp->disconnect();
3987 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003988 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003989 }
3990 return mp;
3991}
3992
username5755fea2018-12-27 09:48:08 +08003993void CameraService::increaseSoundRef() {
3994 Mutex::Autolock lock(mSoundLock);
3995 mSoundRef++;
3996}
3997
3998void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003999 ATRACE_CALL();
4000
username5755fea2018-12-27 09:48:08 +08004001 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
4002 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
4003 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
4004 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
4005 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4006 }
4007 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
4008 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4009 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4010 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004011 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08004012 }
4013 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4014 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4015 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4016 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4017 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004018 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004019}
4020
username5755fea2018-12-27 09:48:08 +08004021void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004022 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004023 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004024 if (--mSoundRef) return;
4025
4026 for (int i = 0; i < NUM_SOUNDS; i++) {
4027 if (mSoundPlayer[i] != 0) {
4028 mSoundPlayer[i]->disconnect();
4029 mSoundPlayer[i].clear();
4030 }
4031 }
4032}
4033
4034void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004035 ATRACE_CALL();
4036
Mathias Agopian65ab4712010-07-14 17:59:35 -07004037 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004038 if (kind < 0 || kind >= NUM_SOUNDS) {
4039 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4040 return;
4041 }
4042
Mathias Agopian65ab4712010-07-14 17:59:35 -07004043 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004044 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004045 sp<MediaPlayer> player = mSoundPlayer[kind];
4046 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004047 player->seekTo(0);
4048 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004049 }
4050}
4051
4052// ----------------------------------------------------------------------------
4053
4054CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004055 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004056 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004057 const std::string& clientPackageName, bool systemNativeClient,
4058 const std::optional<std::string>& clientFeatureId,
4059 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004060 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004061 int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004062 int servicePid, int rotationOverride) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004063 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004064 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07004065 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004066 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004067 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004068 clientPid, clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004069 servicePid, rotationOverride),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004070 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004071{
Austin Borger22c5c852024-03-08 13:31:36 -08004072 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004073 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004074
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004075 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004076
username5755fea2018-12-27 09:48:08 +08004077 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004078
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004079 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004080}
4081
Mathias Agopian65ab4712010-07-14 17:59:35 -07004082// tear down the client
4083CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004084 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004085 mDestructionStarted = true;
4086
username5755fea2018-12-27 09:48:08 +08004087 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004088 // unconditionally disconnect. function is idempotent
4089 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004090}
4091
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004092sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4093
Igor Murashkin634a5152013-02-20 17:15:11 -08004094CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004095 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004096 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004097 const std::string& clientPackageName, bool nativeClient,
4098 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004099 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004100 int servicePid, int rotationOverride):
Austin Borger249e6592024-03-10 22:28:11 -07004101 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004102 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004103 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004104 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4105 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004106 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004107 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004108 mDisconnected(false), mUidIsTrusted(false),
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004109 mRotationOverride(rotationOverride),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004110 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004111 mRemoteBinder(remoteCallback),
4112 mOpsActive(false),
4113 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004114{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004115 if (sCameraService == nullptr) {
4116 sCameraService = cameraService;
4117 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004118
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004119 // There are 2 scenarios in which a client won't have AppOps operations
4120 // (both scenarios : native clients)
4121 // 1) It's an system native client*, the package name will be empty
4122 // and it will return from this function in the previous if condition
4123 // (This is the same as the previously existing behavior).
4124 // 2) It is a system native client, but its package name has been
4125 // modified for debugging, however it still must not use AppOps since
4126 // the package name is not a real one.
4127 //
4128 // * system native client - native client with UID < AID_APP_START. It
4129 // doesn't exclude clients not on the system partition.
4130 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004131 mAppOpsManager = std::make_unique<AppOpsManager>();
4132 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004133
Charles Chenf075f082024-03-04 23:32:55 +00004134 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004135}
4136
4137CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004138 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004139 mDestructionStarted = true;
4140}
4141
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004142binder::Status CameraService::BasicClient::disconnect() {
4143 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004144 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004145 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004146 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004147 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004148
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004149 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004150 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004151 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004152 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004153
4154 sp<IBinder> remote = getRemote();
4155 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004156 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004157 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004158
4159 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004160 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004161 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004162 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004163 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004164
Igor Murashkincba2c162013-03-20 15:56:31 -07004165 // client shouldn't be able to call into us anymore
4166 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004167
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004168 const auto& mActivityManager = getActivityManager();
4169 if (mActivityManager) {
4170 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004171 getCallingUid(),
4172 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004173 }
4174
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004175 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004176}
4177
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004178status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4179 // No dumping of clients directly over Binder,
4180 // must go through CameraService::dump
4181 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004182 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004183 return OK;
4184}
4185
Austin Borgered99f642023-06-01 16:51:35 -07004186status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004187 // Can't watch tags directly, must go through CameraService::startWatchingTags
4188 return OK;
4189}
4190
4191status_t CameraService::BasicClient::stopWatchingTags(int) {
4192 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4193 return OK;
4194}
4195
4196status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4197 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4198 return OK;
4199}
4200
Austin Borgered99f642023-06-01 16:51:35 -07004201std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004202 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004203}
4204
Emilian Peev8b64f282021-03-25 16:49:57 -07004205int CameraService::BasicClient::getCameraFacing() const {
4206 return mCameraFacing;
4207}
4208
4209int CameraService::BasicClient::getCameraOrientation() const {
4210 return mOrientation;
4211}
Ruben Brunkcc776712015-02-17 20:18:47 -08004212
4213int CameraService::BasicClient::getClientPid() const {
4214 return mClientPid;
4215}
4216
Ruben Brunk6267b532015-04-30 17:44:07 -07004217uid_t CameraService::BasicClient::getClientUid() const {
4218 return mClientUid;
4219}
4220
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004221bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4222 // Defaults to API2.
4223 return level == API_2;
4224}
4225
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004226status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004227 {
4228 Mutex::Autolock l(mAudioRestrictionLock);
4229 mAudioRestriction = mode;
4230 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004231 sCameraService->updateAudioRestriction();
4232 return OK;
4233}
4234
4235int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004236 return sCameraService->updateAudioRestriction();
4237}
4238
4239int32_t CameraService::BasicClient::getAudioRestriction() const {
4240 Mutex::Autolock l(mAudioRestrictionLock);
4241 return mAudioRestriction;
4242}
4243
4244bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4245 switch (mode) {
4246 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4247 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4248 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4249 return true;
4250 default:
4251 return false;
4252 }
4253}
4254
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004255status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4256 if (mode == AppOpsManager::MODE_ERRORED) {
4257 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004258 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004259 return PERMISSION_DENIED;
4260 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4261 // If the calling Uid is trusted (a native service), the AppOpsManager could
4262 // return MODE_IGNORED. Do not treat such case as error.
4263 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4264 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004265
4266 bool isCameraPrivacyEnabled;
4267 if (flags::camera_privacy_allowlist()) {
4268 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4269 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4270 } else {
4271 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004272 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004273 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004274 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4275 // We prefer to successfully open the camera and perform camera muting
4276 // or blocking in connectHelper as handleAppOpMode can be called before the
4277 // connection has been fully established and at that time camera muting
4278 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004279 if (!isUidActive || !isCameraPrivacyEnabled) {
Austin Borgerfd05d982024-04-22 15:54:50 -07004280 ALOGI("Camera %s: Access for \"%s\" has been restricted."
4281 "uid active: %s, privacy enabled: %s", mCameraIdStr.c_str(),
4282 mClientPackageName.c_str(), isUidActive ? "true" : "false",
4283 isCameraPrivacyEnabled ? "true" : "false");
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004284 // Return the same error as for device policy manager rejection
4285 return -EACCES;
4286 }
4287 }
4288 return OK;
4289}
4290
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004291status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004292 ATRACE_CALL();
4293
Igor Murashkine6800ce2013-03-04 17:25:57 -08004294 {
4295 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004296 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004297 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004298 if (mAppOpsManager != nullptr) {
4299 // Notify app ops that the camera is not available
4300 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004301
4302 if (flags::watch_foreground_changes()) {
4303 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4304 toString16(mClientPackageName),
4305 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4306 } else {
4307 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004308 toString16(mClientPackageName), mOpsCallback);
Austin Borgerca1e0062023-06-28 11:32:55 -07004309 }
Igor Murashkine6800ce2013-03-04 17:25:57 -08004310
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004311 // Just check for camera acccess here on open - delay startOp until
4312 // camera frames start streaming in startCameraStreamingOps
4313 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004314 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004315 status_t res = handleAppOpMode(mode);
4316 if (res != OK) {
4317 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004318 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004319 }
4320
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004321 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004322
4323 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004324 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004325
Austin Borgerdddb7552023-03-30 17:53:01 -07004326 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004327
Shuzhen Wang695044d2020-03-06 09:02:23 -08004328 // Notify listeners of camera open/close status
4329 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4330
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004331 return OK;
4332}
4333
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004334status_t CameraService::BasicClient::startCameraStreamingOps() {
4335 ATRACE_CALL();
4336
4337 if (!mOpsActive) {
4338 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4339 return INVALID_OPERATION;
4340 }
4341 if (mOpsStreaming) {
4342 ALOGV("%s: Streaming already active!", __FUNCTION__);
4343 return OK;
4344 }
4345
4346 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004347 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004348
4349 if (mAppOpsManager != nullptr) {
4350 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004351 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4352 toString16(mClientFeatureId),
4353 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004354 status_t res = handleAppOpMode(mode);
4355 if (res != OK) {
4356 return res;
4357 }
4358 }
4359
4360 mOpsStreaming = true;
4361
4362 return OK;
4363}
4364
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004365status_t CameraService::BasicClient::noteAppOp() {
4366 ATRACE_CALL();
4367
4368 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004369 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004370
4371 // noteAppOp is only used for when camera mute is not supported, in order
4372 // to trigger the sensor privacy "Unblock" dialog
4373 if (mAppOpsManager != nullptr) {
4374 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004375 toString16(mClientPackageName), toString16(mClientFeatureId),
4376 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004377 status_t res = handleAppOpMode(mode);
4378 if (res != OK) {
4379 return res;
4380 }
4381 }
4382
4383 return OK;
4384}
4385
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004386status_t CameraService::BasicClient::finishCameraStreamingOps() {
4387 ATRACE_CALL();
4388
4389 if (!mOpsActive) {
4390 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4391 return INVALID_OPERATION;
4392 }
4393 if (!mOpsStreaming) {
4394 ALOGV("%s: Streaming not active!", __FUNCTION__);
4395 return OK;
4396 }
4397
4398 if (mAppOpsManager != nullptr) {
4399 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004400 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004401 mOpsStreaming = false;
4402 }
4403
4404 return OK;
4405}
4406
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004407status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004408 ATRACE_CALL();
4409
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004410 if (mOpsStreaming) {
4411 // Make sure we've notified everyone about camera stopping
4412 finishCameraStreamingOps();
4413 }
4414
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004415 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004416 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004417 mOpsActive = false;
4418
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004419 // This function is called when a client disconnects. This should
4420 // release the camera, but actually only if it was in a proper
4421 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004422 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004423 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004424
Ruben Brunkcc776712015-02-17 20:18:47 -08004425 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004426 sCameraService->updateStatus(StatusInternal::PRESENT,
4427 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004428 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004429 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004430 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4431 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004432 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004433 mOpsCallback.clear();
4434
Austin Borgerdddb7552023-03-30 17:53:01 -07004435 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004436
Shuzhen Wang695044d2020-03-06 09:02:23 -08004437 // Notify listeners of camera open/close status
4438 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4439
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004440 return OK;
4441}
4442
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004443void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004444 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004445 if (mAppOpsManager == nullptr) {
4446 return;
4447 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004448 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004449 if (op != AppOpsManager::OP_CAMERA) {
4450 ALOGW("Unexpected app ops notification received: %d", op);
4451 return;
4452 }
4453
4454 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004455 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004456 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004457 ALOGV("checkOp returns: %d, %s ", res,
4458 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4459 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4460 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4461 "UNKNOWN");
4462
Shuzhen Wang64900852021-02-05 09:03:29 -08004463 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004464 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4465 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004466 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004467 } else if (res == AppOpsManager::MODE_IGNORED) {
4468 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004469
Austin Borgerca1e0062023-06-28 11:32:55 -07004470 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4471 // If not visible, but still active, then we want to block instead of muting the camera.
4472 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4473 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4474
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004475 bool isCameraPrivacyEnabled;
4476 if (flags::camera_privacy_allowlist()) {
4477 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4478 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4479 } else {
4480 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004481 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004482 }
4483
4484 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004485 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4486 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4487 isCameraPrivacyEnabled);
4488 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4489 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4490 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004491 if (!mUidIsTrusted) {
Austin Borgerca1e0062023-06-28 11:32:55 -07004492 if (flags::watch_foreground_changes()) {
4493 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4494 setCameraMute(true);
4495 } else {
4496 block();
4497 }
4498 } else {
4499 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4500 setCameraMute(true);
4501 } else if (!isUidActive
4502 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4503 block();
4504 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004505 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004506 }
Evan Severson09ab4002021-02-10 14:15:19 -08004507 } else if (res == AppOpsManager::MODE_ALLOWED) {
4508 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004509 }
4510}
4511
Svet Ganova453d0d2018-01-11 15:37:58 -08004512void CameraService::BasicClient::block() {
4513 ATRACE_CALL();
4514
4515 // Reset the client PID to allow server-initiated disconnect,
4516 // and to prevent further calls by client.
Austin Borger22c5c852024-03-08 13:31:36 -08004517 mClientPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004518 CaptureResultExtras resultExtras; // a dummy result (invalid)
4519 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4520 disconnect();
4521}
4522
Mathias Agopian65ab4712010-07-14 17:59:35 -07004523// ----------------------------------------------------------------------------
4524
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004525void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004526 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004527 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004528 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4529 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4530 api1ErrorCode = CAMERA_ERROR_DISABLED;
4531 }
4532 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004533 } else {
4534 ALOGE("mRemoteCallback is NULL!!");
4535 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004536}
4537
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004538// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004539binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004540 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004541 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004542}
4543
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004544bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4545 return level == API_1;
4546}
4547
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004548CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4549 mClient(client) {
4550}
4551
4552void CameraService::Client::OpsCallback::opChanged(int32_t op,
4553 const String16& packageName) {
4554 sp<BasicClient> client = mClient.promote();
4555 if (client != NULL) {
4556 client->opChanged(op, packageName);
4557 }
4558}
4559
Mathias Agopian65ab4712010-07-14 17:59:35 -07004560// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004561// UidPolicy
4562// ----------------------------------------------------------------------------
4563
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004564void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004565 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004566 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004567
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004568 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004569 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004570 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004571 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004572 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4573 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004574 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004575 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004576 if (res == OK) {
4577 mRegistered = true;
4578 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004579 } else {
4580 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004581 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004582}
4583
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004584void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004585 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004586 return;
4587 }
4588
4589 registerWithActivityManager();
4590}
4591
4592void CameraService::UidPolicy::registerSelf() {
4593 // Use check service to see if the activity service is available
4594 // If not available then register for notifications, instead of blocking
4595 // till the service is ready
4596 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004597 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004598 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004599 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004600 } else {
4601 registerWithActivityManager();
4602 }
4603}
4604
Svet Ganova453d0d2018-01-11 15:37:58 -08004605void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004606 Mutex::Autolock _l(mUidLock);
4607
Steven Moreland2f348142019-07-02 15:59:07 -07004608 mAm.unregisterUidObserver(this);
4609 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004610 mRegistered = false;
4611 mActiveUids.clear();
4612 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004613}
4614
4615void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4616 onUidIdle(uid, disabled);
4617}
4618
4619void CameraService::UidPolicy::onUidActive(uid_t uid) {
4620 Mutex::Autolock _l(mUidLock);
4621 mActiveUids.insert(uid);
4622}
4623
4624void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4625 bool deleted = false;
4626 {
4627 Mutex::Autolock _l(mUidLock);
4628 if (mActiveUids.erase(uid) > 0) {
4629 deleted = true;
4630 }
4631 }
4632 if (deleted) {
4633 sp<CameraService> service = mService.promote();
4634 if (service != nullptr) {
4635 service->blockClientsForUid(uid);
4636 }
4637 }
4638}
4639
Emilian Peev53722fa2019-02-22 17:47:20 -08004640void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004641 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004642 bool procStateChange = false;
4643 {
4644 Mutex::Autolock _l(mUidLock);
4645 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4646 mMonitoredUids[uid].procState != procState) {
4647 mMonitoredUids[uid].procState = procState;
4648 procStateChange = true;
4649 }
4650 }
4651
4652 if (procStateChange) {
4653 sp<CameraService> service = mService.promote();
4654 if (service != nullptr) {
4655 service->notifyMonitoredUids();
4656 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004657 }
4658}
4659
Austin Borgerdddb7552023-03-30 17:53:01 -07004660/**
4661 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4662 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4663 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4664 * monitoredUids. If it is revised above some other monitoredUid, signal
4665 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4666 * foreground apps in split screen - state changes will capture all other cases.
4667 */
4668void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4669 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004670 {
4671 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004672 auto it = mMonitoredUids.find(uid);
4673
4674 if (it != mMonitoredUids.end()) {
4675 if (it->second.hasCamera) {
4676 for (auto &monitoredUid : mMonitoredUids) {
4677 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004678 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004679 notifyUidSet.emplace(monitoredUid.first);
4680 }
4681 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004682 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004683 notifyUidSet.emplace(uid);
4684 } else {
4685 for (auto &monitoredUid : mMonitoredUids) {
4686 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004687 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004688 notifyUidSet.emplace(uid);
4689 }
4690 }
4691 }
4692 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004693 }
4694 }
4695
Austin Borgerdddb7552023-03-30 17:53:01 -07004696 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004697 sp<CameraService> service = mService.promote();
4698 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004699 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004700 }
4701 }
4702}
4703
Austin Borgerdddb7552023-03-30 17:53:01 -07004704/**
4705 * Register a uid for monitoring, and note whether it owns a camera.
4706 */
4707void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004708 Mutex::Autolock _l(mUidLock);
4709 auto it = mMonitoredUids.find(uid);
4710 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004711 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004712 } else {
Austin Borger65577682022-02-17 00:25:43 +00004713 MonitoredUid monitoredUid;
4714 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004715 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004716 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004717 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004718 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004719 if (res != OK) {
4720 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4721 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004722 }
4723
4724 if (openCamera) {
4725 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004726 }
4727}
4728
Austin Borgerdddb7552023-03-30 17:53:01 -07004729/**
4730 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4731 */
4732void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004733 Mutex::Autolock _l(mUidLock);
4734 auto it = mMonitoredUids.find(uid);
4735 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004736 it->second.refCount--;
4737 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004738 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004739 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004740 if (res != OK) {
4741 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4742 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004743 } else if (closeCamera) {
4744 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004745 }
4746 } else {
4747 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4748 }
4749}
4750
Austin Borgered99f642023-06-01 16:51:35 -07004751bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004752 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004753 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004754}
4755
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004756static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4757static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004758
Austin Borgered99f642023-06-01 16:51:35 -07004759bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004760 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004761 // If activity manager is unreachable, assume everything is active
4762 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004763 return true;
4764 }
4765 auto it = mOverrideUids.find(uid);
4766 if (it != mOverrideUids.end()) {
4767 return it->second;
4768 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004769 bool active = mActiveUids.find(uid) != mActiveUids.end();
4770 if (!active) {
4771 // We want active UIDs to always access camera with their first attempt since
4772 // there is no guarantee the app is robustly written and would retry getting
4773 // the camera on failure. The inverse case is not a problem as we would take
4774 // camera away soon once we get the callback that the uid is no longer active.
4775 ActivityManager am;
4776 // Okay to access with a lock held as UID changes are dispatched without
4777 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004778 int64_t startTimeMillis = 0;
4779 do {
4780 // TODO: Fix this b/109950150!
4781 // Okay this is a hack. There is a race between the UID turning active and
4782 // activity being resumed. The proper fix is very risky, so we temporary add
4783 // some polling which should happen pretty rarely anyway as the race is hard
4784 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004785 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004786 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004787 if (active) {
4788 break;
4789 }
4790 if (startTimeMillis <= 0) {
4791 startTimeMillis = uptimeMillis();
4792 }
4793 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004794 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004795 if (remainingTimeMillis <= 0) {
4796 break;
4797 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004798 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4799
4800 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004801 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004802 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004803 } while (true);
4804
Svet Ganov7b4ab782018-03-25 12:48:10 -07004805 if (active) {
4806 // Now that we found out the UID is actually active, cache that
4807 mActiveUids.insert(uid);
4808 }
4809 }
4810 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004811}
4812
Varun Shahb42f1eb2019-04-16 14:45:13 -07004813int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4814 Mutex::Autolock _l(mUidLock);
4815 return getProcStateLocked(uid);
4816}
4817
4818int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4819 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4820 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004821 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004822 }
4823 return procState;
4824}
4825
Austin Borgered99f642023-06-01 16:51:35 -07004826void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4827 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004828 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004829}
4830
Austin Borgered99f642023-06-01 16:51:35 -07004831void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004832 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004833}
4834
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004835void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4836 Mutex::Autolock _l(mUidLock);
4837 ALOGV("UidPolicy: ActivityManager has died");
4838 mRegistered = false;
4839 mActiveUids.clear();
4840}
4841
Austin Borgered99f642023-06-01 16:51:35 -07004842void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004843 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004844 bool wasActive = false;
4845 bool isActive = false;
4846 {
4847 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004848 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004849 mOverrideUids.erase(uid);
4850 if (insert) {
4851 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4852 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004853 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004854 }
4855 if (wasActive != isActive && !isActive) {
4856 sp<CameraService> service = mService.promote();
4857 if (service != nullptr) {
4858 service->blockClientsForUid(uid);
4859 }
4860 }
4861}
4862
4863// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004864// SensorPrivacyPolicy
4865// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004866
4867void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4868{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004869 Mutex::Autolock _l(mSensorPrivacyLock);
4870 if (mRegistered) {
4871 return;
4872 }
Evan Severson09ab4002021-02-10 14:15:19 -08004873 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004874 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004875 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004876 mSpm.addToggleSensorPrivacyListener(this);
4877 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004878 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004879 if (flags::camera_privacy_allowlist()) {
4880 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
4881 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
4882 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4883 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004884 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004885 if (res == OK) {
4886 mRegistered = true;
4887 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4888 }
4889}
4890
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004891void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4892 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004893 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004894 return;
4895 }
4896
4897 registerWithSensorPrivacyManager();
4898}
4899
4900void CameraService::SensorPrivacyPolicy::registerSelf() {
4901 // Use checkservice to see if the sensor_privacy service is available
4902 // If service is not available then register for notification
4903 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004904 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004905 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004906 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004907 } else {
4908 registerWithSensorPrivacyManager();
4909 }
4910}
4911
Michael Grooverd1d435a2018-12-18 17:39:42 -08004912void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4913 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004914 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004915 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004916 mSpm.removeToggleSensorPrivacyListener(this);
4917 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004918 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004919 mRegistered = false;
4920 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4921}
4922
4923bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004924 if (!mRegistered) {
4925 registerWithSensorPrivacyManager();
4926 }
4927
Michael Grooverd1d435a2018-12-18 17:39:42 -08004928 Mutex::Autolock _l(mSensorPrivacyLock);
4929 return mSensorPrivacyEnabled;
4930}
4931
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004932int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
4933 if (!mRegistered) {
4934 registerWithSensorPrivacyManager();
4935 }
4936
4937 Mutex::Autolock _l(mSensorPrivacyLock);
4938 return mCameraPrivacyState;
4939}
4940
Evan Seversond0b69922022-01-27 10:47:34 -08004941bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004942 if (!hasCameraPrivacyFeature()) {
4943 return false;
4944 }
Evan Seversond0b69922022-01-27 10:47:34 -08004945 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004946}
4947
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004948bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
4949 if (!hasCameraPrivacyFeature()) {
Jyoti Bhayana5882b032024-04-26 11:18:58 -07004950 return false;
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004951 }
4952 return mSpm.isCameraPrivacyEnabled(packageName);
4953}
4954
Evan Seversond0b69922022-01-27 10:47:34 -08004955binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004956 int toggleType, int sensor, bool enabled) {
4957 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
4958 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
4959 {
4960 Mutex::Autolock _l(mSensorPrivacyLock);
4961 mSensorPrivacyEnabled = enabled;
4962 }
4963 // if sensor privacy is enabled then block all clients from accessing the camera
4964 if (enabled) {
4965 sp<CameraService> service = mService.promote();
4966 if (service != nullptr) {
4967 service->blockAllClients();
4968 }
4969 }
4970 }
4971 return binder::Status::ok();
4972}
4973
4974binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
4975 int, int sensor, int state) {
4976 if (!flags::camera_privacy_allowlist()
4977 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
4978 return binder::Status::ok();
4979 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08004980 {
4981 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004982 mCameraPrivacyState = state;
4983 }
4984 sp<CameraService> service = mService.promote();
4985 if (!service) {
4986 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004987 }
4988 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004989 if (state == SensorPrivacyManager::ENABLED) {
4990 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08004991 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004992 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004993 }
4994 return binder::Status::ok();
4995}
4996
4997void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4998 Mutex::Autolock _l(mSensorPrivacyLock);
4999 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
5000 mRegistered = false;
5001}
5002
Evan Severson09ab4002021-02-10 14:15:19 -08005003bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08005004 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
5005 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5006 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
5007 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5008 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08005009}
5010
Michael Grooverd1d435a2018-12-18 17:39:42 -08005011// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005012// CameraState
5013// ----------------------------------------------------------------------------
5014
Austin Borgered99f642023-06-01 16:51:35 -07005015CameraService::CameraState::CameraState(const std::string& id, int cost,
5016 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005017 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005018 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005019 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005020
5021CameraService::CameraState::~CameraState() {}
5022
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005023CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005024 Mutex::Autolock lock(mStatusLock);
5025 return mStatus;
5026}
5027
Austin Borgered99f642023-06-01 16:51:35 -07005028std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005029 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005030 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005031 return res;
5032}
5033
Ruben Brunkcc776712015-02-17 20:18:47 -08005034CameraParameters CameraService::CameraState::getShimParams() const {
5035 return mShimParams;
5036}
5037
5038void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5039 mShimParams = params;
5040}
5041
5042int CameraService::CameraState::getCost() const {
5043 return mCost;
5044}
5045
Austin Borgered99f642023-06-01 16:51:35 -07005046std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005047 return mConflicting;
5048}
5049
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005050SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5051 return mSystemCameraKind;
5052}
5053
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005054bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5055 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5056 != mPhysicalCameras.end();
5057}
5058
Austin Borgered99f642023-06-01 16:51:35 -07005059bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005060 Mutex::Autolock lock(mStatusLock);
5061 auto result = mUnavailablePhysicalIds.insert(physicalId);
5062 return result.second;
5063}
5064
Austin Borgered99f642023-06-01 16:51:35 -07005065bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005066 Mutex::Autolock lock(mStatusLock);
5067 auto count = mUnavailablePhysicalIds.erase(physicalId);
5068 return count > 0;
5069}
5070
Austin Borgered99f642023-06-01 16:51:35 -07005071void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005072 Mutex::Autolock lock(mStatusLock);
5073 mClientPackage = clientPackage;
5074}
5075
Austin Borgered99f642023-06-01 16:51:35 -07005076std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005077 Mutex::Autolock lock(mStatusLock);
5078 return mClientPackage;
5079}
5080
Ruben Brunkcc776712015-02-17 20:18:47 -08005081// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005082// ClientEventListener
5083// ----------------------------------------------------------------------------
5084
5085void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005086 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005087 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005088 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005089 if (basicClient.get() != nullptr) {
5090 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005091 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005092 static_cast<int>(basicClient->getClientUid()));
5093 }
5094}
5095
5096void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005097 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005098 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005099 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005100 if (basicClient.get() != nullptr) {
5101 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005102 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005103 static_cast<int>(basicClient->getClientUid()));
5104 }
5105}
5106
Ruben Brunk99e69712015-05-26 17:25:07 -07005107// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005108// CameraClientManager
5109// ----------------------------------------------------------------------------
5110
Ruben Brunk99e69712015-05-26 17:25:07 -07005111CameraService::CameraClientManager::CameraClientManager() {
5112 setListener(std::make_shared<ClientEventListener>());
5113}
5114
Ruben Brunkcc776712015-02-17 20:18:47 -08005115CameraService::CameraClientManager::~CameraClientManager() {}
5116
5117sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005118 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005119 auto descriptor = get(id);
5120 if (descriptor == nullptr) {
5121 return sp<BasicClient>{nullptr};
5122 }
5123 return descriptor->getValue();
5124}
5125
Austin Borgered99f642023-06-01 16:51:35 -07005126std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005127 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005128 std::ostringstream ret;
5129 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005130 bool hasAny = false;
5131 for (auto& i : all) {
5132 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005133 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005134 int32_t cost = i->getCost();
5135 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005136 int32_t score = i->getPriority().getScore();
5137 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005138 auto conflicting = i->getConflicting();
5139 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005140 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005141 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005142 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005143 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005144 uid_t clientUid = clientSp->getClientUid();
5145 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005146 }
Austin Borgered99f642023-06-01 16:51:35 -07005147 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5148 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005149
Ruben Brunk6267b532015-04-30 17:44:07 -07005150 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005151 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005152 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005153 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005154 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005155 }
5156
Austin Borgered99f642023-06-01 16:51:35 -07005157 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005158 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005159 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005160 }
Austin Borgered99f642023-06-01 16:51:35 -07005161 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005162 }
Austin Borgered99f642023-06-01 16:51:35 -07005163 if (hasAny) ret << "\n";
5164 ret << "]\n";
5165 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005166}
5167
5168CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005169 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5170 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005171 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005172
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005173 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005174 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005175
Austin Borgered99f642023-06-01 16:51:35 -07005176 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005177 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5178 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005179}
5180
5181CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005182 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005183 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005184 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005185 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005186 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5187 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005188}
5189
5190// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005191// InjectionStatusListener
5192// ----------------------------------------------------------------------------
5193
5194void CameraService::InjectionStatusListener::addListener(
5195 const sp<ICameraInjectionCallback>& callback) {
5196 Mutex::Autolock lock(mListenerLock);
5197 if (mCameraInjectionCallback) return;
5198 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5199 if (res == OK) {
5200 mCameraInjectionCallback = callback;
5201 }
5202}
5203
5204void CameraService::InjectionStatusListener::removeListener() {
5205 Mutex::Autolock lock(mListenerLock);
5206 if (mCameraInjectionCallback == nullptr) {
5207 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5208 return;
5209 }
5210 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5211 mCameraInjectionCallback = nullptr;
5212}
5213
5214void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005215 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005216 if (mCameraInjectionCallback == nullptr) {
5217 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5218 return;
5219 }
Cliff Wud3a05312021-04-26 23:07:31 +08005220
5221 switch (err) {
5222 case -ENODEV:
5223 mCameraInjectionCallback->onInjectionError(
5224 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5225 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005226 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005227 break;
5228 case -EBUSY:
5229 mCameraInjectionCallback->onInjectionError(
5230 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5231 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005232 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005233 break;
5234 case DEAD_OBJECT:
5235 mCameraInjectionCallback->onInjectionError(
5236 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5237 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005238 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005239 break;
5240 case INVALID_OPERATION:
5241 mCameraInjectionCallback->onInjectionError(
5242 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5243 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005244 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005245 break;
5246 case UNKNOWN_TRANSACTION:
5247 mCameraInjectionCallback->onInjectionError(
5248 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5249 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005250 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005251 break;
5252 default:
5253 mCameraInjectionCallback->onInjectionError(
5254 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5255 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005256 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005257 }
Cliff Wud8cae102021-03-11 01:37:42 +08005258}
5259
5260void CameraService::InjectionStatusListener::binderDied(
5261 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005262 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5263 auto parent = mParent.promote();
5264 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005265 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5266 if (clientDescriptor != nullptr) {
5267 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5268 baseClientPtr->stopInjection();
5269 }
Cliff Wu3b268182021-07-06 15:44:43 +08005270 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005271 }
5272}
5273
5274// ----------------------------------------------------------------------------
5275// CameraInjectionSession
5276// ----------------------------------------------------------------------------
5277
5278binder::Status CameraService::CameraInjectionSession::stopInjection() {
5279 Mutex::Autolock lock(mInjectionSessionLock);
5280 auto parent = mParent.promote();
5281 if (parent == nullptr) {
5282 ALOGE("CameraInjectionSession: Parent is gone");
5283 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5284 "Camera service encountered error");
5285 }
Cliff Wud3a05312021-04-26 23:07:31 +08005286
5287 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005288 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5289 if (clientDescriptor != nullptr) {
5290 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5291 res = baseClientPtr->stopInjection();
5292 if (res != OK) {
5293 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5294 " ret != NO_ERROR: %d", res);
5295 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5296 "Camera session encountered error");
5297 }
5298 }
Cliff Wu3b268182021-07-06 15:44:43 +08005299 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005300 return binder::Status::ok();
5301}
5302
5303// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005304
5305static const int kDumpLockRetries = 50;
5306static const int kDumpLockSleep = 60000;
5307
5308static bool tryLock(Mutex& mutex)
5309{
5310 bool locked = false;
5311 for (int i = 0; i < kDumpLockRetries; ++i) {
5312 if (mutex.tryLock() == NO_ERROR) {
5313 locked = true;
5314 break;
5315 }
5316 usleep(kDumpLockSleep);
5317 }
5318 return locked;
5319}
5320
Rucha Katakwardf223072021-06-15 10:21:00 -07005321void CameraService::cacheDump() {
5322 if (mMemFd != -1) {
5323 const Vector<String16> args;
5324 ATRACE_CALL();
5325 // Acquiring service lock here will avoid the deadlock since
5326 // cacheDump will not be called during the second disconnect.
5327 Mutex::Autolock lock(mServiceLock);
5328
5329 Mutex::Autolock l(mCameraStatesLock);
5330 // Start collecting the info for open sessions and store it in temp file.
5331 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005332 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005333 auto clientDescriptor = mActiveClientManager.get(cameraId);
5334 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005335 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005336 // Log the current open session info before device is disconnected.
5337 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5338 }
5339 }
5340 }
5341}
5342
Mathias Agopian65ab4712010-07-14 17:59:35 -07005343status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005344 ATRACE_CALL();
5345
Austin Borgered99f642023-06-01 16:51:35 -07005346 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005347 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005348 getCallingPid(),
5349 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005350 return NO_ERROR;
5351 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005352 bool locked = tryLock(mServiceLock);
5353 // failed to lock - CameraService is probably deadlocked
5354 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005355 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005356 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005357
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005358 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005359 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005360
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005361 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005362 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005363
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005364 if (locked) mServiceLock.unlock();
5365 return NO_ERROR;
5366 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005367 dprintf(fd, "\n== Service global info: ==\n\n");
5368 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005369 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005370 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5371 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005372 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5373 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5374 }
Austin Borgered99f642023-06-01 16:51:35 -07005375 std::string activeClientString = mActiveClientManager.toString();
5376 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5377 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005378 if (mStreamUseCaseOverrides.size() > 0) {
5379 dprintf(fd, "Active stream use case overrides:");
5380 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5381 dprintf(fd, " %" PRId64, useCaseOverride);
5382 }
5383 dprintf(fd, "\n");
5384 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005385
5386 dumpEventLog(fd);
5387
5388 bool stateLocked = tryLock(mCameraStatesLock);
5389 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005390 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005391 }
5392
Emilian Peevbd8c5032018-02-14 23:05:40 +00005393 int argSize = args.size();
5394 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005395 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005396 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005397 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005398 }
5399 break;
5400 }
5401 }
5402
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005403 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005404 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005405
Austin Borgered99f642023-06-01 16:51:35 -07005406 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005407
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005408 CameraParameters p = state.second->getShimParams();
5409 if (!p.isEmpty()) {
5410 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5411 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005412 }
5413
5414 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005415 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005416 // log the current open session info
5417 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005418 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005419 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005420 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005421
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005422 }
5423
5424 if (stateLocked) mCameraStatesLock.unlock();
5425
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005426 if (locked) mServiceLock.unlock();
5427
Emilian Peevf53f66e2017-04-11 14:29:43 +01005428 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005429
5430 dprintf(fd, "\n== Vendor tags: ==\n\n");
5431
5432 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5433 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005434 sp<VendorTagDescriptorCache> cache =
5435 VendorTagDescriptorCache::getGlobalVendorTagCache();
5436 if (cache == NULL) {
5437 dprintf(fd, "No vendor tags.\n");
5438 } else {
5439 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5440 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005441 } else {
5442 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5443 }
5444
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005445 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005446 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005447 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005448
5449 // Process dump arguments, if any
5450 int n = args.size();
5451 String16 verboseOption("-v");
5452 String16 unreachableOption("--unreachable");
5453 for (int i = 0; i < n; i++) {
5454 if (args[i] == verboseOption) {
5455 // change logging level
5456 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005457 std::string levelStr = toStdString(args[i+1]);
5458 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005459 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005460 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005461 } else if (args[i] == unreachableOption) {
5462 // Dump memory analysis
5463 // TODO - should limit be an argument parameter?
5464 UnreachableMemoryInfo info;
5465 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5466 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005467 dprintf(fd, "\n== Unable to dump unreachable memory. "
5468 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005469 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005470 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005471 std::string s = info.ToString(/*log_contents*/ true);
5472 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005473 }
5474 }
5475 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005476
5477 bool serviceLocked = tryLock(mServiceLock);
5478
5479 // Dump info from previous open sessions.
5480 // Reposition the offset to beginning of the file before reading
5481
5482 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5483 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5484 ssize_t size_read;
5485 char buf[4096];
5486 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5487 // Read data from file to a small buffer and write it to fd.
5488 write(fd, buf, size_read);
5489 if (size_read == -1) {
5490 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5491 break;
5492 }
5493 }
5494 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5495 } else {
5496 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5497 }
5498
5499 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005500 return NO_ERROR;
5501}
5502
Rucha Katakwardf223072021-06-15 10:21:00 -07005503void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005504 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005505 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005506 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005507 getFormattedCurrentTime().c_str(),
5508 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005509 dprintf(fd, " Client priority score: %d state: %d\n",
5510 clientDescriptor->getPriority().getScore(),
5511 clientDescriptor->getPriority().getState());
5512 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5513
5514 auto client = clientDescriptor->getValue();
5515 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005516 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005517
5518 client->dumpClient(fd, args);
5519}
5520
Austin Borgered99f642023-06-01 16:51:35 -07005521void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005522 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005523 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005524}
5525
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005526void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005527 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005528
5529 Mutex::Autolock l(mLogLock);
5530 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005531 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005532 }
5533
5534 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005535 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005536 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005537 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005538 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005539 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005540}
5541
Austin Borgered99f642023-06-01 16:51:35 -07005542void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005543 Mutex::Autolock lock(mLogLock);
5544 if (!isClientWatchedLocked(client)) { return; }
5545
5546 std::vector<std::string> dumpVector;
5547 client->dumpWatchedEventsToVector(dumpVector);
5548
5549 if (dumpVector.empty()) { return; }
5550
Austin Borgered99f642023-06-01 16:51:35 -07005551 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005552
Austin Borgered99f642023-06-01 16:51:35 -07005553 std::string currentTime = getFormattedCurrentTime();
5554 dumpString << "Cached @ ";
5555 dumpString << currentTime;
5556 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005557
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005558 size_t i = dumpVector.size();
5559
5560 // Store the string in reverse order (latest last)
5561 while (i > 0) {
5562 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005563 dumpString << cameraId;
5564 dumpString << ":";
5565 dumpString << client->getPackageName();
5566 dumpString << " ";
5567 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005568 }
5569
Austin Borgered99f642023-06-01 16:51:35 -07005570 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005571}
5572
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005573void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005574 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005575 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5576 if (mTorchClientMap[i] == who) {
5577 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005578 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005579 status_t res = mFlashlight->setTorchMode(cameraId, false);
5580 if (res) {
5581 ALOGE("%s: torch client died but couldn't turn off torch: "
5582 "%s (%d)", __FUNCTION__, strerror(-res), res);
5583 return;
5584 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005585 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005586 break;
5587 }
5588 }
5589}
5590
Ruben Brunkcc776712015-02-17 20:18:47 -08005591/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005592
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005593 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005594 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5595 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005596 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005597 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005598 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005599
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005600 // check torch client
5601 handleTorchClientBinderDied(who);
5602
5603 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005604 if(!evictClientIdByRemote(who)) {
5605 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005606 return;
5607 }
5608
Ruben Brunkcc776712015-02-17 20:18:47 -08005609 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5610 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005611}
5612
Austin Borgered99f642023-06-01 16:51:35 -07005613void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005614 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005615}
5616
Austin Borgered99f642023-06-01 16:51:35 -07005617void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005618 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005619 // Do not lock mServiceLock here or can get into a deadlock from
5620 // connect() -> disconnect -> updateStatus
5621
5622 auto state = getCameraState(cameraId);
5623
5624 if (state == nullptr) {
5625 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005626 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005627 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005628 }
5629
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005630 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5631 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5632 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005633 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005634 return;
5635 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005636
Biswarup Pal37a75182024-01-16 15:53:35 +00005637 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5638 CameraMetadata cameraInfo;
5639 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00005640 cameraId, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +00005641 if (res != OK) {
5642 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5643 __FUNCTION__, cameraId.c_str());
5644 } else {
5645 int32_t deviceId = getDeviceId(cameraInfo);
5646 if (deviceId != kDefaultDeviceId) {
5647 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5648 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5649 static_cast<camera_metadata_enum_android_lens_facing_t>(
5650 lensFacingEntry.data.u8[0]);
5651 std::string mappedCameraId;
5652 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5653 mappedCameraId = kVirtualDeviceBackCameraId;
5654 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5655 mappedCameraId = kVirtualDeviceFrontCameraId;
5656 } else {
5657 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5658 __func__);
5659 }
5660 if (!mappedCameraId.empty()) {
5661 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5662 }
5663 }
5664 }
5665 }
5666
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005667 // Collect the logical cameras without holding mStatusLock in updateStatus
5668 // as that can lead to a deadlock(b/162192331).
5669 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005670 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005671 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005672 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005673 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005674 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005675 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5676 auto [deviceId, mappedCameraId] =
5677 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005678
Biswarup Pal37a75182024-01-16 15:53:35 +00005679 if (status != StatusInternal::ENUMERATING) {
5680 // Update torch status if it has a flash unit.
5681 Mutex::Autolock al(mTorchStatusMutex);
5682 TorchModeStatus torchStatus;
5683 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5684 NAME_NOT_FOUND) {
5685 TorchModeStatus newTorchStatus =
5686 status == StatusInternal::PRESENT ?
5687 TorchModeStatus::AVAILABLE_OFF :
5688 TorchModeStatus::NOT_AVAILABLE;
5689 if (torchStatus != newTorchStatus) {
5690 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5691 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005692 }
5693 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005694
Biswarup Pal37a75182024-01-16 15:53:35 +00005695 Mutex::Autolock lock(mStatusListenerLock);
5696 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5697 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005698
Biswarup Pal37a75182024-01-16 15:53:35 +00005699 for (auto& listener : mListenerList) {
5700 bool isVendorListener = listener->isVendorListener();
5701 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5702 listener->getListenerPid(), listener->getListenerUid())) {
5703 ALOGV("Skipping discovery callback for system-only camera device %s",
5704 cameraId.c_str());
5705 continue;
5706 }
5707
5708 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5709 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005710 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005711 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005712 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5713 ret.exceptionCode());
5714 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005715 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005716}
5717
Austin Borgered99f642023-06-01 16:51:35 -07005718void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5719 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005720 auto state = getCameraState(cameraId);
5721 if (state == nullptr) {
5722 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005723 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005724 return;
5725 }
5726 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005727 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005728 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005729 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005730 }
5731
Biswarup Pal37a75182024-01-16 15:53:35 +00005732 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5733 auto [deviceId, mappedCameraId] =
5734 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5735
Shuzhen Wang695044d2020-03-06 09:02:23 -08005736 Mutex::Autolock lock(mStatusListenerLock);
5737
5738 for (const auto& it : mListenerList) {
5739 if (!it->isOpenCloseCallbackAllowed()) {
5740 continue;
5741 }
5742
5743 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005744 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005745 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5746 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005747 } else {
Biswarup Pal37a75182024-01-16 15:53:35 +00005748 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005749 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005750
5751 it->handleBinderStatus(ret,
5752 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5753 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005754 }
5755}
5756
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005757template<class Func>
5758void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005759 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005760 std::initializer_list<StatusInternal> rejectSourceStates,
5761 Func onStatusUpdatedLocked) {
5762 Mutex::Autolock lock(mStatusLock);
5763 StatusInternal oldStatus = mStatus;
5764 mStatus = status;
5765
5766 if (oldStatus == status) {
5767 return;
5768 }
5769
5770 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07005771 cameraId.c_str(), eToI(oldStatus), eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005772
5773 if (oldStatus == StatusInternal::NOT_PRESENT &&
5774 (status != StatusInternal::PRESENT &&
5775 status != StatusInternal::ENUMERATING)) {
5776
5777 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5778 __FUNCTION__);
5779 mStatus = oldStatus;
5780 return;
5781 }
5782
5783 /**
5784 * Sometimes we want to conditionally do a transition.
5785 * For example if a client disconnects, we want to go to PRESENT
5786 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5787 */
5788 for (auto& rejectStatus : rejectSourceStates) {
5789 if (oldStatus == rejectStatus) {
5790 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005791 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005792 mStatus = oldStatus;
5793 return;
5794 }
5795 }
5796
5797 onStatusUpdatedLocked(cameraId, status);
5798}
5799
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005800status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005801 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005802 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005803 if (!status) {
5804 return BAD_VALUE;
5805 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005806 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5807 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005808 // invalid camera ID or the camera doesn't have a flash unit
5809 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005810 }
5811
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005812 *status = mTorchStatusMap.valueAt(index);
5813 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005814}
5815
Austin Borgered99f642023-06-01 16:51:35 -07005816status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005817 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005818 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5819 if (index == NAME_NOT_FOUND) {
5820 return BAD_VALUE;
5821 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005822 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005823
5824 return OK;
5825}
5826
Austin Borgered99f642023-06-01 16:51:35 -07005827std::list<std::string> CameraService::getLogicalCameras(
5828 const std::string& physicalCameraId) {
5829 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005830 Mutex::Autolock lock(mCameraStatesLock);
5831 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005832 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5833 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005834 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005835 }
5836 return retList;
5837}
5838
5839void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005840 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00005841 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005842 // mStatusListenerLock is expected to be locked
5843 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005844 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005845 // Note: we check only the deviceKind of the physical camera id
5846 // since, logical camera ids and their physical camera ids are
5847 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005848 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5849 listener->getListenerPid(), listener->getListenerUid())) {
5850 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005851 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005852 continue;
5853 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005854 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00005855 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005856 listener->handleBinderStatus(ret,
5857 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5858 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5859 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005860 }
5861 }
5862}
5863
Svet Ganova453d0d2018-01-11 15:37:58 -08005864void CameraService::blockClientsForUid(uid_t uid) {
5865 const auto clients = mActiveClientManager.getAll();
5866 for (auto& current : clients) {
5867 if (current != nullptr) {
5868 const auto basicClient = current->getValue();
5869 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5870 basicClient->block();
5871 }
5872 }
5873 }
5874}
5875
Michael Grooverd1d435a2018-12-18 17:39:42 -08005876void CameraService::blockAllClients() {
5877 const auto clients = mActiveClientManager.getAll();
5878 for (auto& current : clients) {
5879 if (current != nullptr) {
5880 const auto basicClient = current->getValue();
5881 if (basicClient.get() != nullptr) {
5882 basicClient->block();
5883 }
5884 }
5885 }
5886}
5887
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005888void CameraService::blockPrivacyEnabledClients() {
5889 const auto clients = mActiveClientManager.getAll();
5890 for (auto& current : clients) {
5891 if (current != nullptr) {
5892 const auto basicClient = current->getValue();
5893 if (basicClient.get() != nullptr) {
5894 std::string pkgName = basicClient->getPackageName();
5895 bool cameraPrivacyEnabled =
5896 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
5897 if (cameraPrivacyEnabled) {
5898 basicClient->block();
5899 }
5900 }
5901 }
5902 }
5903}
5904
Svet Ganova453d0d2018-01-11 15:37:58 -08005905// NOTE: This is a remote API - make sure all args are validated
5906status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005907 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005908 return PERMISSION_DENIED;
5909 }
5910 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5911 return BAD_VALUE;
5912 }
Austin Borgered99f642023-06-01 16:51:35 -07005913 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005914 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005915 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005916 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005917 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005918 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005919 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005920 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005921 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005922 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005923 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005924 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005925 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005926 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005927 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005928 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005929 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005930 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005931 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005932 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005933 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005934 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005935 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005936 handleClearStreamUseCaseOverrides();
5937 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005938 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005939 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07005940 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005941 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07005942 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00005943 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07005944 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005945 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005946 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005947 }
5948 printHelp(err);
5949 return BAD_VALUE;
5950}
5951
5952status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005953 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005954
Svet Ganova453d0d2018-01-11 15:37:58 -08005955 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07005956 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005957 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07005958 } else if ((args[2] != toString16("idle"))) {
5959 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08005960 return BAD_VALUE;
5961 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005962
5963 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005964 if (args.size() >= 5 && args[3] == toString16("--user")) {
5965 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005966 }
5967
5968 uid_t uid;
5969 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5970 return BAD_VALUE;
5971 }
5972
5973 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005974 return NO_ERROR;
5975}
5976
5977status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005978 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005979
5980 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005981 if (args.size() >= 4 && args[2] == toString16("--user")) {
5982 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005983 }
5984
5985 uid_t uid;
5986 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005987 return BAD_VALUE;
5988 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005989
5990 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005991 return NO_ERROR;
5992}
5993
5994status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005995 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005996
5997 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005998 if (args.size() >= 4 && args[2] == toString16("--user")) {
5999 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006000 }
6001
6002 uid_t uid;
6003 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006004 return BAD_VALUE;
6005 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006006
6007 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006008 return dprintf(out, "active\n");
6009 } else {
6010 return dprintf(out, "idle\n");
6011 }
6012}
6013
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006014status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006015 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006016 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
6017 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
6018 Mutex::Autolock lock(mServiceLock);
6019
6020 mOverrideRotateAndCropMode = rotateValue;
6021
6022 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6023
6024 const auto clients = mActiveClientManager.getAll();
6025 for (auto& current : clients) {
6026 if (current != nullptr) {
6027 const auto basicClient = current->getValue();
6028 if (basicClient.get() != nullptr) {
6029 basicClient->setRotateAndCropOverride(rotateValue);
6030 }
6031 }
6032 }
6033
6034 return OK;
6035}
6036
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006037status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6038 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006039 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006040 if ((*end != '\0') ||
6041 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6042 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6043 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6044 return BAD_VALUE;
6045 }
6046
6047 Mutex::Autolock lock(mServiceLock);
6048 mOverrideAutoframingMode = autoframingValue;
6049
6050 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6051
6052 const auto clients = mActiveClientManager.getAll();
6053 for (auto& current : clients) {
6054 if (current != nullptr) {
6055 const auto basicClient = current->getValue();
6056 if (basicClient.get() != nullptr) {
6057 basicClient->setAutoframingOverride(autoframingValue);
6058 }
6059 }
6060 }
6061
6062 return OK;
6063}
6064
Ravneetaeb20dc2022-03-30 05:33:03 +00006065status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006066 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006067
6068 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6069
6070 Mutex::Autolock lock(mServiceLock);
6071
6072 mCameraServiceWatchdogEnabled = enableWatchdog;
6073
6074 const auto clients = mActiveClientManager.getAll();
6075 for (auto& current : clients) {
6076 if (current != nullptr) {
6077 const auto basicClient = current->getValue();
6078 if (basicClient.get() != nullptr) {
6079 basicClient->setCameraServiceWatchdog(enableWatchdog);
6080 }
6081 }
6082 }
6083
6084 return OK;
6085}
6086
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006087status_t CameraService::handleGetRotateAndCrop(int out) {
6088 Mutex::Autolock lock(mServiceLock);
6089
6090 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6091}
6092
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006093status_t CameraService::handleGetAutoframing(int out) {
6094 Mutex::Autolock lock(mServiceLock);
6095
6096 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6097}
6098
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006099status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6100 char *endPtr;
6101 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006102 std::string maskString = toStdString(args[1]);
6103 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006104
6105 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006106 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006107 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6108
6109 Mutex::Autolock lock(mServiceLock);
6110
6111 mImageDumpMask = maskValue;
6112
6113 return OK;
6114}
6115
6116status_t CameraService::handleGetImageDumpMask(int out) {
6117 Mutex::Autolock lock(mServiceLock);
6118
6119 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6120}
6121
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006122status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006123 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006124 if (errno != 0) return BAD_VALUE;
6125
6126 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6127 Mutex::Autolock lock(mServiceLock);
6128
6129 mOverrideCameraMuteMode = (muteValue == 1);
6130
6131 const auto clients = mActiveClientManager.getAll();
6132 for (auto& current : clients) {
6133 if (current != nullptr) {
6134 const auto basicClient = current->getValue();
6135 if (basicClient.get() != nullptr) {
6136 if (basicClient->supportsCameraMute()) {
6137 basicClient->setCameraMute(mOverrideCameraMuteMode);
6138 }
6139 }
6140 }
6141 }
6142
6143 return OK;
6144}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006145
Shuzhen Wang16610a62022-12-15 22:38:07 -08006146status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6147 std::vector<int64_t> useCasesOverride;
6148 for (size_t i = 1; i < args.size(); i++) {
6149 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006150 std::string arg = toStdString(args[i]);
6151 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006152 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006153 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006154 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006155 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006156 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006157 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006158 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006159 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006160 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006161 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006162 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006163 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006164 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6165 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006166 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006167 return BAD_VALUE;
6168 }
6169 useCasesOverride.push_back(useCase);
6170 }
6171
6172 Mutex::Autolock lock(mServiceLock);
6173 mStreamUseCaseOverrides = std::move(useCasesOverride);
6174
6175 return OK;
6176}
6177
6178void CameraService::handleClearStreamUseCaseOverrides() {
6179 Mutex::Autolock lock(mServiceLock);
6180 mStreamUseCaseOverrides.clear();
6181}
6182
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006183status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6184 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006185 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006186 if ((*end != '\0') ||
6187 (zoomOverrideValue != -1 &&
6188 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6189 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6190 return BAD_VALUE;
6191 }
6192
6193 Mutex::Autolock lock(mServiceLock);
6194 mZoomOverrideValue = zoomOverrideValue;
6195
6196 const auto clients = mActiveClientManager.getAll();
6197 for (auto& current : clients) {
6198 if (current != nullptr) {
6199 const auto basicClient = current->getValue();
6200 if (basicClient.get() != nullptr) {
6201 if (basicClient->supportsZoomOverride()) {
6202 basicClient->setZoomOverride(mZoomOverrideValue);
6203 }
6204 }
6205 }
6206 }
6207
6208 return OK;
6209}
6210
Avichal Rakesh84147132021-11-11 17:47:11 -08006211status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006212 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006213 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006214 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006215 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006216 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006217 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006218 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006219 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006220 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006221 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006222 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006223 dprintf(outFd, "Camera service watch commands:\n"
6224 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6225 " starts watching the provided tags for clients with provided package\n"
6226 " recognizes tag shorthands like '3a'\n"
6227 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006228 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006229 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006230 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006231 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006232 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006233 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006234 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006235}
6236
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006237status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6238 Mutex::Autolock lock(mLogLock);
6239 size_t tagsIdx; // index of '-m'
6240 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006241 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006242 if (tagsIdx < args.size() - 1) {
6243 tags = args[tagsIdx + 1];
6244 } else {
6245 dprintf(outFd, "No tags provided.\n");
6246 return BAD_VALUE;
6247 }
6248
6249 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006250 // watch all clients if no clients are provided
6251 String16 clients = toString16(kWatchAllClientsFlag);
6252 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006253 clientsIdx++);
6254 if (clientsIdx < args.size() - 1) {
6255 clients = args[clientsIdx + 1];
6256 }
Austin Borgered99f642023-06-01 16:51:35 -07006257 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006258
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006259 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006260 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006261
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006262 bool serviceLock = tryLock(mServiceLock);
6263 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006264 auto cameraClients = mActiveClientManager.getAll();
6265 for (const auto &clientDescriptor: cameraClients) {
6266 if (clientDescriptor == nullptr) { continue; }
6267 sp<BasicClient> client = clientDescriptor->getValue();
6268 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006269
6270 if (isClientWatchedLocked(client.get())) {
6271 client->startWatchingTags(mMonitorTags, outFd);
6272 numWatchedClients++;
6273 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006274 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006275 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6276
6277 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006278 return OK;
6279}
6280
6281status_t CameraService::stopWatchingTags(int outFd) {
6282 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006283 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006284 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006285
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006286 mWatchedClientPackages.clear();
6287 mWatchedClientsDumpCache.clear();
6288
6289 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006290 auto cameraClients = mActiveClientManager.getAll();
6291 for (const auto &clientDescriptor : cameraClients) {
6292 if (clientDescriptor == nullptr) { continue; }
6293 sp<BasicClient> client = clientDescriptor->getValue();
6294 if (client.get() == nullptr) { continue; }
6295 client->stopWatchingTags(outFd);
6296 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006297 dprintf(outFd, "Stopped watching all clients.\n");
6298 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006299 return OK;
6300}
6301
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006302status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6303 Mutex::Autolock lock(mLogLock);
6304 size_t clearedSize = mWatchedClientsDumpCache.size();
6305 mWatchedClientsDumpCache.clear();
6306 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6307 return OK;
6308}
6309
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006310status_t CameraService::printWatchedTags(int outFd) {
6311 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006312 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006313
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006314 bool printedSomething = false; // tracks if any monitoring information was printed
6315 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006316
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006317 bool serviceLock = tryLock(mServiceLock);
6318 // get all watched clients that are currently connected
6319 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6320 if (clientDescriptor == nullptr) { continue; }
6321
6322 sp<BasicClient> client = clientDescriptor->getValue();
6323 if (client.get() == nullptr) { continue; }
6324 if (!isClientWatchedLocked(client.get())) { continue; }
6325
6326 std::vector<std::string> dumpVector;
6327 client->dumpWatchedEventsToVector(dumpVector);
6328
6329 size_t printIdx = dumpVector.size();
6330 if (printIdx == 0) {
6331 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006332 }
6333
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006334 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006335 const std::string &cameraId = clientDescriptor->getKey();
6336 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006337 while(printIdx > 0) {
6338 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006339 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006340 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006341 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006342 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006343 printedSomething = true;
6344
6345 connectedMonitoredClients.emplace(client->getPackageName());
6346 }
6347 if (serviceLock) { mServiceLock.unlock(); }
6348
6349 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6350 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006351 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006352 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6353 continue;
6354 }
6355
Austin Borgered99f642023-06-01 16:51:35 -07006356 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006357 dprintf(outFd, "%s\n", kv.second.c_str());
6358 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006359 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006360
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006361 if (!printedSomething) {
6362 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006363 }
6364
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006365 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006366}
6367
Avichal Rakesh84147132021-11-11 17:47:11 -08006368// Print all events in vector `events' that came after lastPrintedEvent
6369void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006370 const std::string &cameraId,
6371 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006372 const std::vector<std::string> &events,
6373 const std::string &lastPrintedEvent) {
6374 if (events.empty()) { return; }
6375
6376 // index of lastPrintedEvent in events.
6377 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6378 size_t lastPrintedIdx;
6379 for (lastPrintedIdx = 0;
6380 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6381 lastPrintedIdx++);
6382
6383 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6384
Avichal Rakesh84147132021-11-11 17:47:11 -08006385 // print events in chronological order (latest event last)
6386 size_t idxToPrint = lastPrintedIdx;
6387 do {
6388 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006389 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6390 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006391 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006392}
6393
6394// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6395// command should be interrupted if the user presses the return key, or if user loses any way to
6396// signal interrupt.
6397// If timeoutMs == 0, this function will always return false
6398bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6399 struct timeval startTime;
6400 int startTimeError = gettimeofday(&startTime, nullptr);
6401 if (startTimeError) {
6402 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6403 return true;
6404 }
6405
6406 const nfds_t numFds = 1;
6407 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6408
6409 struct timeval currTime;
6410 char buffer[2];
6411 while(true) {
6412 int currTimeError = gettimeofday(&currTime, nullptr);
6413 if (currTimeError) {
6414 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6415 return true;
6416 }
6417
6418 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6419 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6420 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6421
6422 if (remainingTimeMs <= 0) {
6423 // No user interrupt within timeoutMs, don't interrupt watch command
6424 return false;
6425 }
6426
6427 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6428 if (numFdsUpdated < 0) {
6429 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6430 return true;
6431 }
6432
6433 if (numFdsUpdated == 0) {
6434 // No user input within timeoutMs, don't interrupt watch command
6435 return false;
6436 }
6437
6438 if (!(pollFd.revents & POLLIN)) {
6439 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6440 return true;
6441 }
6442
6443 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6444 if (sizeRead < 0) {
6445 dprintf(outFd, "Error reading user input. Exiting.\n");
6446 return true;
6447 }
6448
6449 if (sizeRead == 0) {
6450 // Reached end of input fd (can happen if input is piped)
6451 // User has no way to signal an interrupt, so interrupt here
6452 return true;
6453 }
6454
6455 if (buffer[0] == '\n') {
6456 // User pressed return, interrupt watch command.
6457 return true;
6458 }
6459 }
6460}
6461
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006462status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6463 int inFd, int outFd) {
6464 // Figure out refresh interval, if present in args
6465 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006466 if (args.size() > 2) {
6467 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006468 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006469 intervalIdx++);
6470
6471 size_t intervalValIdx = intervalIdx + 1;
6472 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006473 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006474 if (errno) { return BAD_VALUE; }
6475 }
6476 }
6477
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006478 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6479 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006480
Avichal Rakesh84147132021-11-11 17:47:11 -08006481 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006482 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006483
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006484 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006485 bool serviceLock = tryLock(mServiceLock);
6486 auto cameraClients = mActiveClientManager.getAll();
6487 if (serviceLock) { mServiceLock.unlock(); }
6488
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006489 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006490 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006491 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006492
6493 sp<BasicClient> client = clientDescriptor->getValue();
6494 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006495 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006496
Austin Borgered99f642023-06-01 16:51:35 -07006497 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006498 // This also initializes the map entries with an empty string
6499 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6500
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006501 std::vector<std::string> latestEvents;
6502 client->dumpWatchedEventsToVector(latestEvents);
6503
6504 if (!latestEvents.empty()) {
6505 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006506 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006507 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006508 latestEvents,
6509 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006510 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006511 }
6512 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006513 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006514 break;
6515 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006516 }
6517 return OK;
6518}
6519
Austin Borgered99f642023-06-01 16:51:35 -07006520void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006521 mWatchedClientPackages.clear();
6522
Austin Borgered99f642023-06-01 16:51:35 -07006523 std::istringstream iss(clients);
6524 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006525
Austin Borgered99f642023-06-01 16:51:35 -07006526 while (std::getline(iss, nextClient, ',')) {
6527 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006528 // Don't need to track any other package if 'all' is present
6529 mWatchedClientPackages.clear();
6530 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6531 break;
6532 }
6533
6534 // track package names
6535 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006536 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006537}
6538
Svet Ganova453d0d2018-01-11 15:37:58 -08006539status_t CameraService::printHelp(int out) {
6540 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006541 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6542 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6543 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006544 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6545 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6546 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006547 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6548 " Valid values 0=false, 1=true, 2=auto\n"
6549 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006550 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6551 " Valid values 0=OFF, 1=ON for JPEG\n"
6552 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006553 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006554 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6555 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6556 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6557 " on. In case the number of usecases is smaller than the number of streams, the\n"
6558 " last use case is assigned to all the remaining streams. In case of multiple\n"
6559 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6560 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6561 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6562 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006563 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6564 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006565 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6566 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006567 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006568 " help print this message\n");
6569}
6570
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006571bool CameraService::isClientWatched(const BasicClient *client) {
6572 Mutex::Autolock lock(mLogLock);
6573 return isClientWatchedLocked(client);
6574}
6575
6576bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6577 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6578 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6579}
6580
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006581int32_t CameraService::updateAudioRestriction() {
6582 Mutex::Autolock lock(mServiceLock);
6583 return updateAudioRestrictionLocked();
6584}
6585
6586int32_t CameraService::updateAudioRestrictionLocked() {
6587 int32_t mode = 0;
6588 // iterate through all active client
6589 for (const auto& i : mActiveClientManager.getAll()) {
6590 const auto clientSp = i->getValue();
6591 mode |= clientSp->getAudioRestriction();
6592 }
6593
6594 bool modeChanged = (mAudioRestriction != mode);
6595 mAudioRestriction = mode;
6596 if (modeChanged) {
6597 mAppOps.setCameraAudioRestriction(mode);
6598 }
6599 return mode;
6600}
6601
Austin Borgered99f642023-06-01 16:51:35 -07006602status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006603 sp<BasicClient> clientSp) {
6604 std::unique_ptr<AutoConditionLock> lock =
6605 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6606 status_t res = NO_ERROR;
6607 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006608 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006609 mInjectionStatusListener->notifyInjectionError(
6610 externalCamId, UNKNOWN_TRANSACTION);
6611 clientSp->notifyError(
6612 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6613 CaptureResultExtras());
6614
6615 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6616 // other clients from connecting in mServiceLockWrapper if held
6617 mServiceLock.unlock();
6618
6619 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006620 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006621 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006622 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006623
6624 // Reacquire mServiceLock
6625 mServiceLock.lock();
6626 }
6627
6628 return res;
6629}
6630
Cliff Wud3a05312021-04-26 23:07:31 +08006631void CameraService::clearInjectionParameters() {
6632 {
6633 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006634 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006635 mInjectionInternalCamId = "";
6636 }
6637 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006638 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006639}
6640
Biswarup Pal37a75182024-01-16 15:53:35 +00006641} // namespace android