blob: ff364a4a033e716214242ef0dfe7b1deb0914117 [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
Austin Borger65e64642024-06-11 15:58:23 -0700787Status CameraService::getNumberOfCameras(int32_t type,
788 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +0000789 int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700790 ATRACE_CALL();
Austin Borger65e64642024-06-11 15:58:23 -0700791 if (vd_flags::camera_device_awareness() && (clientAttribution.deviceId != kDefaultDeviceId)
Biswarup Pal37a75182024-01-16 15:53:35 +0000792 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
Austin Borger65e64642024-06-11 15:58:23 -0700793 *numCameras = mVirtualDeviceCameraIdMapper.getNumberOfCameras(clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000794 return Status::ok();
795 }
796
Emilian Peevaee727d2017-05-04 16:35:48 +0100797 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700798 bool hasSystemCameraPermissions =
Austin Borger22c5c852024-03-08 13:31:36 -0800799 hasPermissionsForSystemCamera(std::string(), getCallingPid(),
800 getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700801 switch (type) {
802 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700803 if (hasSystemCameraPermissions) {
804 *numCameras = static_cast<int>(mNormalDeviceIds.size());
805 } else {
806 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
807 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800808 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700809 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700810 if (hasSystemCameraPermissions) {
811 *numCameras = mNumberOfCameras;
812 } else {
813 *numCameras = mNumberOfCamerasWithoutSystemCamera;
814 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800815 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700816 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800817 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700818 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800819 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
820 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700821 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800822 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700823}
824
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700825Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
Austin Borger65e64642024-06-11 15:58:23 -0700826 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700827 /* out */
828 hardware::camera2::impl::CameraMetadataNative* request) {
829 ATRACE_CALL();
830
831 if (!flags::feature_combination_query()) {
832 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
833 "Camera subsystem doesn't support this method!");
834 }
835 if (!mInitialized) {
836 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
837 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
838 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
839 }
840
Austin Borger65e64642024-06-11 15:58:23 -0700841 std::optional<std::string> cameraIdOptional =
842 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000843 if (!cameraIdOptional.has_value()) {
844 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700845 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000846 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
847 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
848 }
849 std::string cameraId = cameraIdOptional.value();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700850
851 binder::Status res;
852 if (request == nullptr) {
853 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
854 "Camera %s: Error creating default request", cameraId.c_str());
855 return res;
856 }
857 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
858 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
859 cameraId, templateId, &tempId);
860 if (!res.isOk()) {
861 ALOGE("%s: Camera %s: failed to map request Template %d",
862 __FUNCTION__, cameraId.c_str(), templateId);
863 return res;
864 }
865
866 if (shouldRejectSystemCameraConnection(cameraId)) {
867 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
868 "request for system only device %s: ", cameraId.c_str());
869 }
870
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700871 CameraMetadata metadata;
872 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
873 if (err == OK) {
874 request->swap(metadata);
875 } else if (err == BAD_VALUE) {
876 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
877 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
878 cameraId.c_str(), templateId, strerror(-err), err);
879 } else {
880 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
881 "Camera %s: Error creating default request for template %d: %s (%d)",
882 cameraId.c_str(), templateId, strerror(-err), err);
883 }
884 return res;
885}
886
887Status CameraService::isSessionConfigurationWithParametersSupported(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700888 const std::string& unresolvedCameraId, int targetSdkVersion,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700889 const SessionConfiguration& sessionConfiguration,
Austin Borger65e64642024-06-11 15:58:23 -0700890 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700891 /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700892 ATRACE_CALL();
893
894 if (!flags::feature_combination_query()) {
895 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
896 "Camera subsystem doesn't support this method!");
897 }
898 if (!mInitialized) {
899 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
900 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
901 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
902 }
903
Austin Borger65e64642024-06-11 15:58:23 -0700904 std::optional<std::string> cameraIdOptional =
905 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000906 if (!cameraIdOptional.has_value()) {
907 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700908 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000909 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
910 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
911 }
912 std::string cameraId = cameraIdOptional.value();
913
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700914 if (supported == nullptr) {
915 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
916 unresolvedCameraId.c_str());
917 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
918 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
919 }
920
921 if (shouldRejectSystemCameraConnection(cameraId)) {
922 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
923 "session configuration with parameters support for system only device %s: ",
924 cameraId.c_str());
925 }
926
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700927 bool overrideForPerfClass = flags::calculate_perf_override_during_session_support() &&
928 SessionConfigurationUtils::targetPerfClassPrimaryCamera(
929 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
930
Shuzhen Wange3e8e732024-05-22 17:48:01 -0700931 auto ret = isSessionConfigurationWithParametersSupportedUnsafe(cameraId,
932 sessionConfiguration, overrideForPerfClass, supported);
933 if (flags::analytics_24q3()) {
934 mCameraServiceProxyWrapper->logFeatureCombinationQuery(cameraId,
935 getCallingUid(), sessionConfiguration, ret);
936 }
937 return ret;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700938}
939
940Status CameraService::isSessionConfigurationWithParametersSupportedUnsafe(
941 const std::string& cameraId, const SessionConfiguration& sessionConfiguration,
942 bool overrideForPerfClass, /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700943 *supported = false;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700944 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(
945 cameraId, sessionConfiguration, overrideForPerfClass,
946 /*checkSessionParams=*/true, supported);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700947 binder::Status res;
948 switch (ret) {
949 case OK:
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700950 // Expected. Do Nothing.
951 return Status::ok();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700952 case INVALID_OPERATION: {
953 std::string msg = fmt::sprintf(
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700954 "Camera %s: Session configuration with parameters supported query not "
955 "supported!",
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700956 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700957 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
958 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
959 *supported = false;
960 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700961 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700962 break;
963 case NAME_NOT_FOUND: {
964 std::string msg = fmt::sprintf("Camera %s: Unknown camera ID.", cameraId.c_str());
965 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
966 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
967 *supported = false;
968 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
969 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700970 break;
971 default: {
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700972 std::string msg = fmt::sprintf(
973 "Unable to retrieve session configuration support for camera "
974 "device %s: Error: %s (%d)",
975 cameraId.c_str(), strerror(-ret), ret);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700976 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700977 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
978 *supported = false;
979 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700980 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700981 break;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700982 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700983}
984
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800985Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000986 int targetSdkVersion, int rotationOverride,
Austin Borger65e64642024-06-11 15:58:23 -0700987 const SessionConfiguration& sessionConfiguration,
988 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +0000989 /*out*/ CameraMetadata* outMetadata) {
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800990 ATRACE_CALL();
991
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800992 if (outMetadata == nullptr) {
993 std::string msg =
994 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
995 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
996 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
997 }
998
Avichal Rakesh4baf7262024-03-20 19:16:04 -0700999 if (!mInitialized) {
1000 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1001 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
1002 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
1003 }
1004
Austin Borger65e64642024-06-11 15:58:23 -07001005 std::optional<std::string> cameraIdOptional =
1006 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001007 if (!cameraIdOptional.has_value()) {
1008 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001009 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001010 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1011 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1012 }
1013 std::string cameraId = cameraIdOptional.value();
1014
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001015 if (shouldRejectSystemCameraConnection(cameraId)) {
1016 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1017 "Unable to retrieve camera"
1018 "characteristics for system only device %s: ",
1019 cameraId.c_str());
1020 }
1021
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001022 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1023 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001024 if (flags::check_session_support_before_session_char()) {
1025 bool sessionConfigSupported;
1026 Status res = isSessionConfigurationWithParametersSupportedUnsafe(
1027 cameraId, sessionConfiguration, overrideForPerfClass, &sessionConfigSupported);
1028 if (!res.isOk()) {
1029 // isSessionConfigurationWithParametersSupportedUnsafe should log what went wrong and
1030 // report the correct Status to send to the client. Simply forward the error to
1031 // the client.
1032 outMetadata->clear();
1033 return res;
1034 }
1035 if (!sessionConfigSupported) {
1036 std::string msg = fmt::sprintf(
1037 "Session configuration not supported for camera device %s.", cameraId.c_str());
1038 outMetadata->clear();
1039 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1040 }
1041 }
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001042
1043 status_t ret = mCameraProviderManager->getSessionCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001044 cameraId, sessionConfiguration, overrideForPerfClass, rotationOverride, outMetadata);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001045
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001046 switch (ret) {
1047 case OK:
1048 // Expected, no handling needed.
1049 break;
1050 case INVALID_OPERATION: {
1051 std::string msg = fmt::sprintf(
1052 "Camera %s: Session characteristics query not supported!",
1053 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001054 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001055 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1056 outMetadata->clear();
1057 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1058 }
1059 break;
1060 case NAME_NOT_FOUND: {
1061 std::string msg = fmt::sprintf(
1062 "Camera %s: Unknown camera ID.",
1063 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001064 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001065 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1066 outMetadata->clear();
1067 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001068 }
1069 break;
1070 default: {
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001071 std::string msg = fmt::sprintf(
1072 "Unable to retrieve session characteristics for camera device %s: "
1073 "Error: %s (%d)",
1074 cameraId.c_str(), strerror(-ret), ret);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001075 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001076 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1077 outMetadata->clear();
1078 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001079 }
1080 }
1081
Shuzhen Wange3e8e732024-05-22 17:48:01 -07001082 Status res = filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
1083 if (flags::analytics_24q3()) {
1084 mCameraServiceProxyWrapper->logSessionCharacteristicsQuery(cameraId,
1085 getCallingUid(), sessionConfiguration, res);
1086 }
1087 return res;
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001088}
1089
1090Status CameraService::filterSensitiveMetadataIfNeeded(
1091 const std::string& cameraId, CameraMetadata* metadata) {
1092 int callingPid = getCallingPid();
1093 int callingUid = getCallingUid();
1094
1095 if (callingPid == getpid()) {
1096 // Caller is cameraserver; no need to remove keys
1097 return Status::ok();
1098 }
1099
1100 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1101 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1102 ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
1103 metadata->clear();
1104 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1105 "Unable to retrieve camera kind for device %s", cameraId.c_str());
1106 }
1107 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
1108 // Attempting to query system only camera without system camera permission would have
1109 // failed the shouldRejectSystemCameraConnection in the caller. So if we get here
1110 // for a system only camera, then the caller has the required permission.
1111 // No need to remove keys
1112 return Status::ok();
1113 }
1114
1115 std::vector<int32_t> tagsRemoved;
Biswarup Pale506e732024-03-27 13:46:20 +00001116 // Get the device id that owns this camera.
1117 auto [cameraOwnerDeviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1118 cameraId);
1119 bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid,
1120 cameraOwnerDeviceId);
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001121 if (hasCameraPermission) {
1122 // Caller has camera permission; no need to remove keys
1123 return Status::ok();
1124 }
1125
1126 status_t ret = metadata->removePermissionEntries(
1127 mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1128 if (ret != OK) {
1129 metadata->clear();
1130 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1131 "Failed to remove camera characteristics needing camera permission "
1132 "for device %s:%s (%d)",
1133 cameraId.c_str(), strerror(-ret), ret);
1134 }
1135
1136 if (!tagsRemoved.empty()) {
1137 ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1138 tagsRemoved.data(), tagsRemoved.size());
1139 if (ret != OK) {
1140 metadata->clear();
1141 return STATUS_ERROR_FMT(
1142 ERROR_INVALID_OPERATION,
1143 "Failed to insert camera keys needing permission for device %s: %s (%d)",
1144 cameraId.c_str(), strerror(-ret), ret);
1145 }
1146 }
1147 return Status::ok();
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001148}
1149
malikakash22af94c2023-12-04 18:13:14 +00001150Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001151 const std::string& cameraId,
1152 const CameraMetadata& sessionParams) {
1153 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001154 const int pid = getCallingPid();
1155 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001156 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1157 __FUNCTION__, pid, uid);
1158 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1159 "Permission Denial: no permission to inject session params");
1160 }
1161
Biswarup Pal37a75182024-01-16 15:53:35 +00001162 // Do not allow session params injection for a virtual camera.
1163 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1164 if (deviceId != kDefaultDeviceId) {
1165 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1166 "Cannot inject session params for a virtual camera");
1167 }
1168
malikakash22af94c2023-12-04 18:13:14 +00001169 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1170 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1171
1172 auto clientDescriptor = mActiveClientManager.get(cameraId);
1173 if (clientDescriptor == nullptr) {
1174 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1175 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1176 "No active client for camera id %s", cameraId.c_str());
1177 }
1178
1179 sp<BasicClient> clientSp = clientDescriptor->getValue();
1180 status_t res = clientSp->injectSessionParams(sessionParams);
1181
1182 if (res != OK) {
1183 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1184 "Error injecting session params into camera \"%s\": %s (%d)",
1185 cameraId.c_str(), strerror(-res), res);
1186 }
1187 return Status::ok();
1188}
1189
Biswarup Pal37a75182024-01-16 15:53:35 +00001190std::optional<std::string> CameraService::resolveCameraId(
1191 const std::string& inputCameraId,
1192 int32_t deviceId,
malikakash98260df2024-05-10 23:33:57 +00001193 int32_t devicePolicy) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001194 if ((deviceId == kDefaultDeviceId)
1195 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1196 auto [storedDeviceId, _] =
1197 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1198 if (storedDeviceId != kDefaultDeviceId) {
1199 // Trying to access a virtual camera from default-policy device context, we should fail.
1200 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1201 inputCameraId.c_str(), deviceId);
1202 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1203 return std::nullopt;
1204 }
malikakash98260df2024-05-10 23:33:57 +00001205 return inputCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001206 }
1207
1208 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1209}
1210
Austin Borger65e64642024-06-11 15:58:23 -07001211Status CameraService::getCameraInfo(int cameraId, int rotationOverride,
1212 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
1213 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001214 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001215 Mutex::Autolock l(mServiceLock);
Austin Borger65e64642024-06-11 15:58:23 -07001216 std::string cameraIdStr =
1217 cameraIdIntToStrLocked(cameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001218 if (cameraIdStr.empty()) {
1219 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001220 cameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001221 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1222 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1223 }
malikakashedb38962023-09-06 00:03:35 +00001224
Austin Borgered99f642023-06-01 16:51:35 -07001225 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001226 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1227 "characteristics for system only device %s: ", cameraIdStr.c_str());
1228 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001229
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001230 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001231 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001232 return STATUS_ERROR(ERROR_DISCONNECTED,
1233 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001234 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001235 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001236 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001237 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1238 if (hasSystemCameraPermissions) {
1239 cameraIdBound = mNumberOfCameras;
1240 }
1241 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001242 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1243 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001244 }
1245
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001246 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001247 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001248 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001249 cameraIdStr, rotationOverride, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001250 if (err != OK) {
1251 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1252 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1253 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001254 logServiceError(std::string("Error retrieving camera info from device ")
1255 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001256 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001257
Ruben Brunkcc776712015-02-17 20:18:47 -08001258 return ret;
1259}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001260
Biswarup Pal37a75182024-01-16 15:53:35 +00001261std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1262 int32_t deviceId, int32_t devicePolicy) {
1263 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1264 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1265 std::optional<std::string> cameraIdOptional =
1266 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1267 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1268 }
1269
1270 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001271 auto callingPid = getCallingPid();
1272 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001273 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1274 callingPid, callingUid, /* checkCameraPermissions= */ false);
1275 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001276 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001277 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001278 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1279 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1280 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001281 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001282 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001283
malikakash98260df2024-05-10 23:33:57 +00001284 return (*cameraIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001285}
1286
Biswarup Pal37a75182024-01-16 15:53:35 +00001287std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1288 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001289 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001290 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001291}
1292
Austin Borgered99f642023-06-01 16:51:35 -07001293Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07001294 int targetSdkVersion, int rotationOverride, const AttributionSourceState& clientAttribution,
1295 int32_t devicePolicy, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001296 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001297
Zhijun He2b59be82013-09-25 10:14:30 -07001298 if (!cameraInfo) {
1299 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001300 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001301 }
1302
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001303 if (!mInitialized) {
1304 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001305 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001306 return STATUS_ERROR(ERROR_DISCONNECTED,
1307 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001308 }
1309
Austin Borger65e64642024-06-11 15:58:23 -07001310 std::optional<std::string> cameraIdOptional =
1311 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001312 if (!cameraIdOptional.has_value()) {
1313 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001314 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001315 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1316 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1317 }
1318 std::string cameraId = cameraIdOptional.value();
1319
Austin Borgered99f642023-06-01 16:51:35 -07001320 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001321 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001322 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001323 }
1324
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001325 bool overrideForPerfClass =
1326 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001327 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001328 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001329 cameraId, overrideForPerfClass, cameraInfo, rotationOverride);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001330 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001331 if (res == NAME_NOT_FOUND) {
1332 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001333 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001334 strerror(-res), res);
1335 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001336 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1337 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001338 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001339 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001340 strerror(-res), res);
1341 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001342 }
Emilian Peeve20c6372018-08-14 18:45:53 +01001343
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001344 return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -07001345}
1346
Austin Borger65e64642024-06-11 15:58:23 -07001347Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId,
1348 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00001349 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001350 ATRACE_CALL();
1351 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001352
Austin Borger65e64642024-06-11 15:58:23 -07001353 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
1354 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001355 if (!cameraIdOptional.has_value()) {
1356 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001357 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001358 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1359 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1360 }
1361 std::string cameraId = cameraIdOptional.value();
1362
Rucha Katakwar38284522021-11-10 11:25:21 -08001363 if (!mInitialized) {
1364 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1365 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1366 }
1367
Biswarup Pal37a75182024-01-16 15:53:35 +00001368 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001369 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1370 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1371 }
1372
Austin Borgered99f642023-06-01 16:51:35 -07001373 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001374 if (res != OK) {
1375 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001376 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001377 strerror(-res), res);
1378 }
1379 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1380 return Status::ok();
1381}
1382
Austin Borgered99f642023-06-01 16:51:35 -07001383std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001384 time_t now = time(nullptr);
1385 char formattedTime[64];
1386 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001387 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001388}
1389
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001390Status CameraService::getCameraVendorTagDescriptor(
1391 /*out*/
1392 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001393 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001394 if (!mInitialized) {
1395 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001396 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001397 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001398 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1399 if (globalDescriptor != nullptr) {
1400 *desc = *(globalDescriptor.get());
1401 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001402 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001403}
1404
Emilian Peev71c73a22017-03-21 16:35:51 +00001405Status CameraService::getCameraVendorTagCache(
1406 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1407 ATRACE_CALL();
1408 if (!mInitialized) {
1409 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1410 return STATUS_ERROR(ERROR_DISCONNECTED,
1411 "Camera subsystem not available");
1412 }
1413 sp<VendorTagDescriptorCache> globalCache =
1414 VendorTagDescriptorCache::getGlobalVendorTagCache();
1415 if (globalCache != nullptr) {
1416 *cache = *(globalCache.get());
1417 }
1418 return Status::ok();
1419}
1420
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001421void CameraService::clearCachedVariables() {
1422 BasicClient::BasicClient::sCameraService = nullptr;
1423}
1424
Austin Borgered99f642023-06-01 16:51:35 -07001425std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001426 int rotationOverride, int* portraitRotation, int* facing,
1427 int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001428 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001429
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001430 int deviceVersion = 0;
1431
Emilian Peevf53f66e2017-04-11 14:29:43 +01001432 status_t res;
1433 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001434 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001435 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001436 if (res != OK || transport == IPCTransport::INVALID) {
1437 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001438 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001439 return std::make_pair(-1, IPCTransport::INVALID) ;
1440 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001441 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001442
Emilian Peevf53f66e2017-04-11 14:29:43 +01001443 hardware::CameraInfo info;
1444 if (facing) {
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001445 res = mCameraProviderManager->getCameraInfo(cameraId, rotationOverride,
Austin Borger18b30a72022-10-27 12:20:29 -07001446 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001447 if (res != OK) {
1448 return std::make_pair(-1, IPCTransport::INVALID);
1449 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001450 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001451 if (orientation) {
1452 *orientation = info.orientation;
1453 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001454 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001455
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001456 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001457}
1458
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001459Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001460 switch(err) {
1461 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001462 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001463 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001464 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1465 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001466 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001467 return STATUS_ERROR(ERROR_DISCONNECTED,
1468 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001469 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001470 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1471 "Camera HAL encountered error %d: %s",
1472 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001473 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001474}
1475
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001476Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001477 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1478 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001479 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001480 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001481 apiLevel effectiveApiLevel, bool overrideForPerfClass, int rotationOverride,
malikakash73125c62023-07-21 22:44:34 +00001482 bool forceSlowJpegMode, const std::string& originalCameraId,
1483 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001484 // For HIDL devices
1485 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1486 // Create CameraClient based on device version reported by the HAL.
1487 int deviceVersion = deviceVersionAndTransport.first;
1488 switch(deviceVersion) {
1489 case CAMERA_DEVICE_API_VERSION_1_0:
1490 ALOGE("Camera using old HAL version: %d", deviceVersion);
1491 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1492 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001493 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001494 break;
1495 case CAMERA_DEVICE_API_VERSION_3_0:
1496 case CAMERA_DEVICE_API_VERSION_3_1:
1497 case CAMERA_DEVICE_API_VERSION_3_2:
1498 case CAMERA_DEVICE_API_VERSION_3_3:
1499 case CAMERA_DEVICE_API_VERSION_3_4:
1500 case CAMERA_DEVICE_API_VERSION_3_5:
1501 case CAMERA_DEVICE_API_VERSION_3_6:
1502 case CAMERA_DEVICE_API_VERSION_3_7:
1503 break;
1504 default:
1505 // Should not be reachable
1506 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1507 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1508 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001509 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001510 }
1511 }
1512 if (effectiveApiLevel == API_1) { // Camera1 API route
1513 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001514 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001515 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001516 api1CameraId, facing, sensorOrientation,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001517 clientPid, clientUid, servicePid, overrideForPerfClass, rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00001518 forceSlowJpegMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001519 ALOGI("%s: Camera1 API (legacy), rotationOverride %d, forceSlowJpegMode %d",
1520 __FUNCTION__, rotationOverride, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001521 } else { // Camera2 API route
1522 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1523 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001524 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001525 cameraService->mCameraServiceProxyWrapper,
1526 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001527 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001528 overrideForPerfClass, rotationOverride, originalCameraId);
1529 ALOGI("%s: Camera2 API, rotationOverride %d", __FUNCTION__, rotationOverride);
Ruben Brunkcc776712015-02-17 20:18:47 -08001530 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001531 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001532}
1533
Austin Borgered99f642023-06-01 16:51:35 -07001534std::string CameraService::toString(std::set<userid_t> intSet) {
1535 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001536 bool first = true;
1537 for (userid_t i : intSet) {
1538 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001539 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001540 first = false;
1541 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001542 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001543 }
1544 }
Austin Borgered99f642023-06-01 16:51:35 -07001545 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001546}
1547
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001548int32_t CameraService::mapToInterface(TorchModeStatus status) {
1549 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1550 switch (status) {
1551 case TorchModeStatus::NOT_AVAILABLE:
1552 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1553 break;
1554 case TorchModeStatus::AVAILABLE_OFF:
1555 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1556 break;
1557 case TorchModeStatus::AVAILABLE_ON:
1558 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1559 break;
1560 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001561 ALOGW("Unknown new flash status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001562 }
1563 return serviceStatus;
1564}
1565
1566CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1567 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1568 switch (status) {
1569 case CameraDeviceStatus::NOT_PRESENT:
1570 serviceStatus = StatusInternal::NOT_PRESENT;
1571 break;
1572 case CameraDeviceStatus::PRESENT:
1573 serviceStatus = StatusInternal::PRESENT;
1574 break;
1575 case CameraDeviceStatus::ENUMERATING:
1576 serviceStatus = StatusInternal::ENUMERATING;
1577 break;
1578 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001579 ALOGW("Unknown new HAL device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001580 }
1581 return serviceStatus;
1582}
1583
1584int32_t CameraService::mapToInterface(StatusInternal status) {
1585 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1586 switch (status) {
1587 case StatusInternal::NOT_PRESENT:
1588 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1589 break;
1590 case StatusInternal::PRESENT:
1591 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1592 break;
1593 case StatusInternal::ENUMERATING:
1594 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1595 break;
1596 case StatusInternal::NOT_AVAILABLE:
1597 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1598 break;
1599 case StatusInternal::UNKNOWN:
1600 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1601 break;
1602 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001603 ALOGW("Unknown new internal device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001604 }
1605 return serviceStatus;
1606}
1607
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001608Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001609 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001610
Austin Borgered99f642023-06-01 16:51:35 -07001611 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001612 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001613 sp<Client> tmp = nullptr;
Austin Borger7d2b9232024-07-22 14:17:14 -07001614
1615 logConnectionAttempt(getCallingPid(), kServiceName, cameraIdStr, API_1);
1616
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001617 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001618 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1619 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001620 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001621 /*targetSdkVersion*/ __ANDROID_API_FUTURE__,
1622 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_OVERRIDE_TO_PORTRAIT,
Austin Borger7d2b9232024-07-22 14:17:14 -07001623 /*forceSlowJpegMode*/false, cameraIdStr, /*isNonSystemNdk*/ false, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001624 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001625 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001626 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001627 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001628}
1629
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001630Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001631 /*out*/
1632 CameraParameters* parameters) {
1633
1634 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1635
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001636 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001637
1638 if (parameters == NULL) {
1639 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001640 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001641 }
1642
malikakash98260df2024-05-10 23:33:57 +00001643 std::string cameraIdStr = std::to_string(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001644
1645 // Check if we already have parameters
1646 {
1647 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001648 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001649 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001650 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001651 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001652 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001653 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001654 }
1655 CameraParameters p = cameraState->getShimParams();
1656 if (!p.isEmpty()) {
1657 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001658 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001659 }
1660 }
1661
Austin Borger22c5c852024-03-08 13:31:36 -08001662 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001663 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001664 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001665 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001666 // Error already logged by callee
1667 return ret;
1668 }
1669
1670 // Check for parameters again
1671 {
1672 // Scope for service lock
1673 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001674 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001675 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001676 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001677 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001678 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001679 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001680 CameraParameters p = cameraState->getShimParams();
1681 if (!p.isEmpty()) {
1682 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001683 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001684 }
1685 }
1686
Ruben Brunkcc776712015-02-17 20:18:47 -08001687 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1688 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001689 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001690}
1691
Austin Borgered99f642023-06-01 16:51:35 -07001692Status CameraService::validateConnectLocked(const std::string& cameraId,
Austin Borger6e831c42024-07-22 13:07:56 -07001693 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001694
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001695#ifdef __BRILLO__
1696 UNUSED(clientName8);
1697 UNUSED(clientUid);
1698 UNUSED(clientPid);
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001699#else
Austin Borger6e831c42024-07-22 13:07:56 -07001700 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001701 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001702 return allowed;
1703 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001704#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001705
Austin Borger22c5c852024-03-08 13:31:36 -08001706 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001707
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001708 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001709 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1710 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001711 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001712 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001713 }
1714
Ruben Brunkcc776712015-02-17 20:18:47 -08001715 if (getCameraState(cameraId) == nullptr) {
1716 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001717 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001718 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001719 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001720 }
1721
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001722 status_t err = checkIfDeviceIsUsable(cameraId);
1723 if (err != NO_ERROR) {
1724 switch(err) {
1725 case -ENODEV:
1726 case -EBUSY:
1727 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001728 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001729 default:
1730 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001731 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001732 }
1733 }
1734 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001735}
1736
Austin Borgered99f642023-06-01 16:51:35 -07001737Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
Austin Borger6e831c42024-07-22 13:07:56 -07001738 const std::string& clientName, int& clientUid, int& clientPid) const {
Austin Borger22c5c852024-03-08 13:31:36 -08001739 int callingPid = getCallingPid();
1740 int callingUid = getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001741
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001742 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001743 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001744 clientUid = callingUid;
1745 } else if (!isTrustedCallingUid(callingUid)) {
1746 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1747 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001748 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1749 "Untrusted caller (calling PID %d, UID %d) trying to "
1750 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001751 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001752 clientName.c_str(), clientPid, clientUid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001753 }
1754
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001755 // Check if we can trust clientPid
1756 if (clientPid == USE_CALLING_PID) {
1757 clientPid = callingPid;
1758 } else if (!isTrustedCallingUid(callingUid)) {
1759 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1760 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001761 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1762 "Untrusted caller (calling PID %d, UID %d) trying to "
1763 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001764 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001765 clientName.c_str(), clientPid, clientUid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001766 }
1767
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001768 if (shouldRejectSystemCameraConnection(cameraId)) {
1769 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1770 cameraId.c_str());
1771 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001772 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001773 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001774 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1775 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001776 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001777 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001778 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001779 }
1780
Biswarup Pale506e732024-03-27 13:46:20 +00001781 // Get the device id that owns this camera.
1782 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1783
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001784 // If it's not calling from cameraserver, check the permission if the
1785 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1786 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001787 bool checkPermissionForCamera =
Biswarup Pale506e732024-03-27 13:46:20 +00001788 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName, deviceId);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001789 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001790 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001791 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001792 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1793 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001794 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001795 }
1796
Svet Ganova453d0d2018-01-11 15:37:58 -08001797 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001798 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001799 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001800 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1801 clientPid, clientUid);
1802 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001803 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1804 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001805 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001806 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001807 }
1808
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001809 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1810 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1811 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1812 if ((!isAutomotivePrivilegedClient(callingUid) ||
1813 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1814 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001815 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1816 return STATUS_ERROR_FMT(ERROR_DISABLED,
1817 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001818 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001819 }
1820
Austin Borger6e831c42024-07-22 13:07:56 -07001821 userid_t clientUserId = multiuser_get_user_id(clientUid);
1822
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001823 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1824 // connected to camera service directly.
Wu-cheng Lia3355432011-05-20 14:54:25 +08001825
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001826 // For non-system clients : Only allow clients who are being used by the current foreground
1827 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08001828 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001829 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001830 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1831 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001832 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001833 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1834 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001835 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001836 }
1837
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001838 if (flags::camera_hsum_permission()) {
1839 // If the System User tries to access the camera when the device is running in
1840 // headless system user mode, ensure that client has the required permission
1841 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07001842 if (isHeadlessSystemUserMode()
1843 && (clientUserId == USER_SYSTEM)
1844 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Austin Borger6e831c42024-07-22 13:07:56 -07001845 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", callingPid, clientUid);
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001846 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1847 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1848 User without camera headless system user permission",
Austin Borger6e831c42024-07-22 13:07:56 -07001849 clientName.c_str(), callingPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001850 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001851 }
1852
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001853 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001854}
1855
Austin Borgered99f642023-06-01 16:51:35 -07001856status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001857 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001858 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001859 if (cameraState == nullptr) {
1860 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001861 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001862 return -ENODEV;
1863 }
1864
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001865 StatusInternal currentStatus = cameraState->getStatus();
1866 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001867 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001868 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001869 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001870 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001871 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001872 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001873 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001874 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001875
Ruben Brunkcc776712015-02-17 20:18:47 -08001876 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001877}
1878
Ruben Brunkcc776712015-02-17 20:18:47 -08001879void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001880 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001881
Ruben Brunkcc776712015-02-17 20:18:47 -08001882 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001883 auto clientDescriptor =
1884 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001885 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001886 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1887
1888 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001889 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001890
1891 if (evicted.size() > 0) {
1892 // This should never happen - clients should already have been removed in disconnect
1893 for (auto& i : evicted) {
1894 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001895 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001896 }
1897
1898 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1899 __FUNCTION__);
1900 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001901
1902 // And register a death notification for the client callback. Do
1903 // this last to avoid Binder policy where a nested Binder
1904 // transaction might be pre-empted to service the client death
1905 // notification if the client process dies before linkToDeath is
1906 // invoked.
1907 sp<IBinder> remoteCallback = client->getRemote();
1908 if (remoteCallback != nullptr) {
1909 remoteCallback->linkToDeath(this);
1910 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001911}
1912
Austin Borgered99f642023-06-01 16:51:35 -07001913status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1914 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1915 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001916 /*out*/
1917 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001918 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001919 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001920 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001921 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001922 DescriptorPtr clientDescriptor;
1923 {
1924 if (effectiveApiLevel == API_1) {
1925 // If we are using API1, any existing client for this camera ID with the same remote
1926 // should be returned rather than evicted to allow MediaRecorder to work properly.
1927
1928 auto current = mActiveClientManager.get(cameraId);
1929 if (current != nullptr) {
1930 auto clientSp = current->getValue();
1931 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001932 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001933 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001934 " API level, evicting prior client...");
1935 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001936 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001937 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001938 *client = clientSp;
1939 return NO_ERROR;
1940 }
1941 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001942 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001943 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001944
Ruben Brunkcc776712015-02-17 20:18:47 -08001945 // Get state for the given cameraId
1946 auto state = getCameraState(cameraId);
1947 if (state == nullptr) {
1948 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001949 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001950 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001951 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001952 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001953
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001954 sp<IServiceManager> sm = defaultServiceManager();
1955 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08001956 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001957 // If processinfo service is not available and the client is automotive privileged
1958 // client used for safety critical uses cases such as rear-view and surround-view which
1959 // needs to be available before android boot completes, then use the hardcoded values
1960 // for the process state and priority score. As this scenario is before android system
1961 // services are up and client is native client, hence using NATIVE_ADJ as the priority
1962 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
1963 // visible on the top.
1964 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1965 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1966 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
1967 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
1968 } else {
1969 // Get current active client PIDs
1970 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1971 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001972
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001973 std::vector<int> priorityScores(ownerPids.size());
1974 std::vector<int> states(ownerPids.size());
1975
1976 // Get priority scores of all active PIDs
1977 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
1978 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
1979 if (err != OK) {
1980 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
1981 return err;
1982 }
1983
1984 // Update all active clients' priorities
1985 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
1986 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1987 pidToPriorityMap.emplace(ownerPids[i],
1988 resource_policy::ClientPriority(priorityScores[i], states[i],
1989 /* isVendorClient won't get copied over*/ false,
1990 /* oomScoreOffset won't get copied over*/ 0));
1991 }
1992 mActiveClientManager.updatePriorities(pidToPriorityMap);
1993
1994 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1995 int32_t actualState = states[states.size() - 1];
1996
1997 // Make descriptor for incoming client. We store the oomScoreOffset
1998 // since we might need it later on new handleEvictionsLocked and
1999 // ProcessInfoService would not take that into account.
2000 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2001 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2002 state->getConflicting(), actualScore, clientPid, actualState,
2003 oomScoreOffset, systemNativeClient);
2004 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002005
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002006 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
2007
Ruben Brunkcc776712015-02-17 20:18:47 -08002008 // Find clients that would be evicted
2009 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
2010
2011 // If the incoming client was 'evicted,' higher priority clients have the camera in the
2012 // background, so we cannot do evictions
2013 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2014 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2015 " priority).", clientPid);
2016
2017 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002018 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002019 auto incompatibleClients =
2020 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2021
Austin Borgered99f642023-06-01 16:51:35 -07002022 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2023 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2024 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002025 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002026
2027 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002028 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002029 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002030 i->getKey().c_str(),
2031 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002032 i->getOwnerId(), i->getPriority().getScore(),
2033 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002034 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002035 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2036 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002037 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002038 }
2039
2040 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002041 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002042 mEventLog.add(msg);
2043
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002044 auto current = mActiveClientManager.get(cameraId);
2045 if (current != nullptr) {
2046 return -EBUSY; // CAMERA_IN_USE
2047 } else {
2048 return -EUSERS; // MAX_CAMERAS_IN_USE
2049 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002050 }
2051
2052 for (auto& i : evicted) {
2053 sp<BasicClient> clientSp = i->getValue();
2054 if (clientSp.get() == nullptr) {
2055 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2056
2057 // TODO: Remove this
2058 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2059 __FUNCTION__);
2060 mActiveClientManager.remove(i);
2061 continue;
2062 }
2063
2064 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002065 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002066 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002067
Ruben Brunkcc776712015-02-17 20:18:47 -08002068 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002069 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002070 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2071 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002072 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002073 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002074 i->getPriority().getState(), cameraId.c_str(),
2075 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002076 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002077
2078 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002079 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002080 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002081 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002082 }
2083
Ruben Brunkcc776712015-02-17 20:18:47 -08002084 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2085 // other clients from connecting in mServiceLockWrapper if held
2086 mServiceLock.unlock();
2087
2088 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002089 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002090
2091 // Destroy evicted clients
2092 for (auto& i : evictedClients) {
2093 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002094 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002095 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002096
Austin Borger22c5c852024-03-08 13:31:36 -08002097 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002098
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002099 for (const auto& i : evictedClients) {
2100 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002101 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002102 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2103 if (ret == TIMED_OUT) {
2104 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002105 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2106 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002107 return -EBUSY;
2108 }
2109 if (ret != NO_ERROR) {
2110 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002111 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2112 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002113 return ret;
2114 }
2115 }
2116
2117 evictedClients.clear();
2118
Ruben Brunkcc776712015-02-17 20:18:47 -08002119 // Once clients have been disconnected, relock
2120 mServiceLock.lock();
2121
2122 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2123 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2124 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002125 }
2126
Ruben Brunkcc776712015-02-17 20:18:47 -08002127 *partial = clientDescriptor;
2128 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002129}
2130
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002131Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002132 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002133 int api1CameraId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002134 int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002135 int rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00002136 bool forceSlowJpegMode,
Austin Borger65e64642024-06-11 15:58:23 -07002137 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00002138 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002139 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002140 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002141 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002142 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002143
Austin Borger65e64642024-06-11 15:58:23 -07002144 std::string cameraIdStr =
2145 cameraIdIntToStr(api1CameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002146 if (cameraIdStr.empty()) {
2147 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002148 api1CameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002149 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2150 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2151 }
malikakashedb38962023-09-06 00:03:35 +00002152
Austin Borger7d2b9232024-07-22 14:17:14 -07002153 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
2154 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
2155 std::string clientPackageName = resolvePackageName(clientAttribution.uid,
2156 clientPackageNameMaybe);
2157 logConnectionAttempt(clientAttribution.pid, clientPackageName, cameraIdStr, API_1);
2158
Ruben Brunkcc776712015-02-17 20:18:47 -08002159 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002160 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
Austin Borger7d2b9232024-07-22 14:17:14 -07002161 clientPackageName, /*systemNativeClient*/ false, {},
Austin Borgerd1ad6c62024-07-01 11:28:31 -07002162 clientAttribution.uid, clientAttribution.pid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002163 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borger7d2b9232024-07-22 14:17:14 -07002164 rotationOverride, forceSlowJpegMode, cameraIdStr, isNonSystemNdk, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002165
Biswarup Pal37a75182024-01-16 15:53:35 +00002166 if (!ret.isOk()) {
Austin Borgerd1ad6c62024-07-01 11:28:31 -07002167 logRejected(cameraIdStr, getCallingPid(), clientAttribution.packageName.value_or(""),
2168 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002169 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002170 }
2171
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002172 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002173
2174 const sp<IServiceManager> sm(defaultServiceManager());
2175 const auto& mActivityManager = getActivityManager();
2176 if (mActivityManager) {
2177 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002178 getCallingUid(),
2179 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002180 }
2181
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002182 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002183}
2184
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002185bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2186 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002187 // If the client is not a vendor client, don't add listener if
2188 // a) the camera is a publicly hidden secure camera OR
2189 // b) the camera is a system only camera and the client doesn't
2190 // have android.permission.SYSTEM_CAMERA permissions.
2191 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2192 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002193 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002194 return true;
2195 }
2196 return false;
2197}
2198
Austin Borgered99f642023-06-01 16:51:35 -07002199bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002200 // Rules for rejection:
2201 // 1) If cameraserver tries to access this camera device, accept the
2202 // connection.
2203 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002204 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002205 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2206 // and the serving thread is a non hwbinder thread, the client must have
2207 // android.permission.SYSTEM_CAMERA permissions to connect.
2208
Austin Borger22c5c852024-03-08 13:31:36 -08002209 int cPid = getCallingPid();
2210 int cUid = getCallingUid();
2211 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002212 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2213 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002214 // This isn't a known camera ID, so it's not a system camera
2215 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2216 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002217 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002218
2219 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002220 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002221 return false;
2222 }
2223 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002224 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002225 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2226 return true;
2227 }
2228 // (3) Here we only check for permissions if it is a system only camera device. This is since
2229 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2230 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2231 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002232 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002233 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002234 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2235 cameraId.c_str());
2236 return true;
2237 }
2238
2239 return false;
2240}
2241
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002242Status CameraService::connectDevice(
2243 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002244 const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002245 int oomScoreOffset, int targetSdkVersion,
2246 int rotationOverride, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Ruben Brunkcc776712015-02-17 20:18:47 -08002247 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002248 sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002249 ATRACE_CALL();
Emilian Peev31bd2422024-04-23 22:24:09 +00002250 RunThreadWithRealtimePriority priorityBump;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002251 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002252 sp<CameraDeviceClient> client = nullptr;
Austin Borger7d2b9232024-07-22 14:17:14 -07002253 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
Austin Borger22c5c852024-03-08 13:31:36 -08002254 int callingPid = getCallingPid();
2255 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002256 bool systemNativeClient = false;
Austin Borger7d2b9232024-07-22 14:17:14 -07002257 if (callerHasSystemUid() && (clientPackageNameMaybe.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002258 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borger7d2b9232024-07-22 14:17:14 -07002259 clientPackageNameMaybe = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002260 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002261 }
Austin Borger249e6592024-03-10 22:28:11 -07002262
Austin Borger65e64642024-06-11 15:58:23 -07002263 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2264 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002265 if (!cameraIdOptional.has_value()) {
2266 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002267 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002268 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2269 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2270 }
2271 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002272
Austin Borger7d2b9232024-07-22 14:17:14 -07002273 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
2274 std::string clientPackageName = resolvePackageName(clientAttribution.uid,
2275 clientPackageNameMaybe);
2276 logConnectionAttempt(clientAttribution.pid, clientPackageName, cameraId, API_2);
2277
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002278 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002279 std::string msg =
2280 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
Austin Borger7d2b9232024-07-22 14:17:14 -07002281 "camera id %s", clientPackageName.c_str(), callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07002282 cameraId.c_str());
2283 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2284 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002285 }
2286
Austin Borger65e64642024-06-11 15:58:23 -07002287 userid_t clientUserId = multiuser_get_user_id(clientAttribution.uid);
2288 if (clientAttribution.uid == USE_CALLING_UID) {
Austin Borger9bfa0a72022-08-03 17:50:40 -07002289 clientUserId = multiuser_get_user_id(callingUid);
2290 }
2291
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002292 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2293 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002294 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2295 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002296 std::string msg = "Camera disabled by device policy";
2297 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2298 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002299 }
2300
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002301 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002302 if (oomScoreOffset > 0
2303 && !hasPermissionsForSystemCamera(cameraId, callingPid,
Austin Borger249e6592024-03-10 22:28:11 -07002304 callingUid)
2305 && !isTrustedCallingUid(callingUid)) {
Austin Borgered99f642023-06-01 16:51:35 -07002306 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002307 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borger7d2b9232024-07-22 14:17:14 -07002308 clientPackageName.c_str(), callingPid, cameraId.c_str());
Austin Borgered99f642023-06-01 16:51:35 -07002309 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2310 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002311 }
2312
Austin Borgered99f642023-06-01 16:51:35 -07002313 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
Austin Borger7d2b9232024-07-22 14:17:14 -07002314 cameraId, /*api1CameraId*/-1, clientPackageName, systemNativeClient,
Austin Borgerd1ad6c62024-07-01 11:28:31 -07002315 clientAttribution.attributionTag, clientAttribution.uid, USE_CALLING_PID, API_2,
2316 /*shimUpdateOnly*/ false, oomScoreOffset, targetSdkVersion, rotationOverride,
Austin Borger7d2b9232024-07-22 14:17:14 -07002317 /*forceSlowJpegMode*/false, unresolvedCameraId, isNonSystemNdk, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002318
Biswarup Pal37a75182024-01-16 15:53:35 +00002319 if (!ret.isOk()) {
Austin Borger7d2b9232024-07-22 14:17:14 -07002320 logRejected(cameraId, callingPid, clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002321 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002322 }
2323
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002324 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002325 Mutex::Autolock lock(mServiceLock);
2326
2327 // Clear the previous cached logs and reposition the
2328 // file offset to beginning of the file to log new data.
2329 // If either truncate or lseek fails, close the previous file and create a new one.
2330 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2331 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2332 // Close the previous memfd.
2333 close(mMemFd);
2334 // If failure to wipe the data, then create a new file and
2335 // assign the new value to mMemFd.
2336 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2337 if (mMemFd == -1) {
2338 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2339 }
2340 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002341 const sp<IServiceManager> sm(defaultServiceManager());
2342 const auto& mActivityManager = getActivityManager();
2343 if (mActivityManager) {
2344 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002345 callingUid,
2346 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002347 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002348 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002349}
2350
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002351bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2352 int callingPid, int callingUid) {
2353 if (!isAutomotiveDevice()) {
2354 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2355 }
2356
2357 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2358 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2359 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2360 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2361 "using camera %s", callingUid, cam_id.c_str());
2362 return false;
2363 }
2364
2365 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2366 return true;
2367 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2368 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002369 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2370 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002371 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2372 return false;
2373 } else {
2374 return true;
2375 }
2376 }
2377 return false;
2378}
2379
Austin Borger7d2b9232024-07-22 14:17:14 -07002380std::string CameraService::getPackageNameFromUid(int clientUid) const {
Austin Borgered99f642023-06-01 16:51:35 -07002381 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002382
Avichal Rakesh5788fec2024-03-15 14:39:20 -07002383 sp<IPermissionController> permCtrl;
2384 if (flags::cache_permission_services()) {
2385 permCtrl = getPermissionController();
2386 } else {
2387 sp<IServiceManager> sm = defaultServiceManager();
2388#pragma clang diagnostic push
2389#pragma clang diagnostic ignored "-Wdeprecated-declarations"
2390 // Using deprecated function to preserve functionality until the
2391 // cache_permission_services flag is removed.
2392 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
2393#pragma clang diagnostic pop
2394 if (binder == 0) {
2395 ALOGE("Cannot get permission service");
2396 permCtrl = nullptr;
2397 } else {
2398 permCtrl = interface_cast<IPermissionController>(binder);
2399 }
2400 }
2401
2402 if (permCtrl == nullptr) {
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002403 // Return empty package name and the further interaction
2404 // with camera will likely fail
2405 return packageName;
2406 }
2407
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002408 Vector<String16> packages;
2409
2410 permCtrl->getPackagesForUid(clientUid, packages);
2411
2412 if (packages.isEmpty()) {
2413 ALOGE("No packages for calling UID %d", clientUid);
2414 // Return empty package name and the further interaction
2415 // with camera will likely fail
2416 return packageName;
2417 }
2418
2419 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002420 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002421
2422 return packageName;
2423}
2424
Austin Borger7d2b9232024-07-22 14:17:14 -07002425void CameraService::logConnectionAttempt(int clientPid, const std::string& clientPackageName,
2426 const std::string& cameraId, apiLevel effectiveApiLevel) const {
2427 int packagePid = (clientPid == USE_CALLING_PID) ?
2428 getCallingPid() : clientPid;
2429 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
2430 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
2431 static_cast<int>(effectiveApiLevel));
2432}
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002433
Austin Borger7d2b9232024-07-22 14:17:14 -07002434std::string CameraService::resolvePackageName(int clientUid,
2435 const std::string& clientPackageNameMaybe) const {
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002436 if (clientPackageNameMaybe.size() <= 0) {
Austin Borger7d2b9232024-07-22 14:17:14 -07002437 int packageUid = (clientUid == USE_CALLING_UID) ?
2438 getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002439 // NDK calls don't come with package names, but we need one for various cases.
2440 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2441 // do exist. For all authentication cases, all packages under the same UID get the
2442 // same permissions, so picking any associated package name is sufficient. For some
2443 // other cases, this may give inaccurate names for clients in logs.
Austin Borger7d2b9232024-07-22 14:17:14 -07002444 return getPackageNameFromUid(packageUid);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002445 } else {
Austin Borger7d2b9232024-07-22 14:17:14 -07002446 return clientPackageNameMaybe;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002447 }
Austin Borger7d2b9232024-07-22 14:17:14 -07002448}
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002449
Austin Borger7d2b9232024-07-22 14:17:14 -07002450template<class CALLBACK, class CLIENT>
2451Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2452 int api1CameraId, const std::string& clientPackageName, bool systemNativeClient,
2453 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
2454 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
2455 int rotationOverride, bool forceSlowJpegMode,
2456 const std::string& originalCameraId, bool isNonSystemNdk, /*out*/sp<CLIENT>& device) {
2457 binder::Status ret = binder::Status::ok();
2458
2459 int packageUid = (clientUid == USE_CALLING_UID) ?
2460 getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002461 int packagePid = (clientPid == USE_CALLING_PID) ?
Austin Borger7d2b9232024-07-22 14:17:14 -07002462 getCallingPid() : clientPid;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002463
Shuzhen Wang316781a2020-08-18 18:11:01 -07002464 nsecs_t openTimeNs = systemTime();
2465
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002466 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002467 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002468 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002469
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002470 {
2471 // Acquire mServiceLock and prevent other clients from connecting
2472 std::unique_ptr<AutoConditionLock> lock =
2473 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2474
2475 if (lock == nullptr) {
2476 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2477 , clientPid);
2478 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2479 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002480 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002481 }
2482
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002483 // Enforce client permissions and do basic validity checks
Biswarup Pal37a75182024-01-16 15:53:35 +00002484 if (!(ret = validateConnectLocked(cameraId, clientPackageName,
Austin Borger6e831c42024-07-22 13:07:56 -07002485 /*inout*/clientUid, /*inout*/clientPid)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002486 return ret;
2487 }
2488
2489 // Check the shim parameters after acquiring lock, if they have already been updated and
2490 // we were doing a shim update, return immediately
2491 if (shimUpdateOnly) {
2492 auto cameraState = getCameraState(cameraId);
2493 if (cameraState != nullptr) {
2494 if (!cameraState->getShimParams().isEmpty()) return ret;
2495 }
2496 }
2497
2498 status_t err;
2499
2500 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002501 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Austin Borger6e831c42024-07-22 13:07:56 -07002502 if ((err = handleEvictionsLocked(cameraId, clientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002503 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2504 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002505 switch (err) {
2506 case -ENODEV:
2507 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2508 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002509 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002510 case -EBUSY:
2511 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2512 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002513 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002514 case -EUSERS:
2515 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2516 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002517 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002518 default:
2519 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2520 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002521 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002522 }
2523 }
2524
2525 if (clientTmp.get() != nullptr) {
2526 // Handle special case for API1 MediaRecorder where the existing client is returned
2527 device = static_cast<CLIENT*>(clientTmp.get());
2528 return ret;
2529 }
2530
2531 // give flashlight a chance to close devices if necessary.
2532 mFlashlight->prepareDeviceOpen(cameraId);
2533
Austin Borger18b30a72022-10-27 12:20:29 -07002534 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002535 auto deviceVersionAndTransport =
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002536 getDeviceVersion(cameraId, rotationOverride, /*out*/&portraitRotation,
Austin Borger18b30a72022-10-27 12:20:29 -07002537 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002538 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002539 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002540 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002541 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002542 }
2543
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002544 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002545 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002546 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002547
Austin Borger6e831c42024-07-22 13:07:56 -07002548 // Only use passed in clientPid to check permission. Use calling PID as the client PID
2549 // that's connected to camera service directly.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002550 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002551 clientFeatureId, cameraId, api1CameraId, facing,
Austin Borger7d2b9232024-07-22 14:17:14 -07002552 orientation, getCallingPid(), clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002553 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002554 rotationOverride, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002555 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002556 return ret;
2557 }
2558 client = static_cast<CLIENT*>(tmp.get());
2559
2560 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2561 __FUNCTION__);
2562
Austin Borgered99f642023-06-01 16:51:35 -07002563 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002564 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002565 if (err != OK) {
2566 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002567 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002568 mServiceLock.unlock();
2569 client->disconnect();
2570 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002571 switch(err) {
2572 case BAD_VALUE:
2573 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002574 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002575 case -EBUSY:
2576 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002577 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002578 case -EUSERS:
2579 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2580 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002581 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002582 case PERMISSION_DENIED:
2583 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002584 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002585 case -EACCES:
2586 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002587 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002588 case -ENODEV:
2589 default:
2590 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002591 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002592 strerror(-err), err);
2593 }
2594 }
2595
2596 // Update shim paremeters for legacy clients
2597 if (effectiveApiLevel == API_1) {
2598 // Assume we have always received a Client subclass for API1
2599 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2600 String8 rawParams = shimClient->getParameters();
2601 CameraParameters params(rawParams);
2602
2603 auto cameraState = getCameraState(cameraId);
2604 if (cameraState != nullptr) {
2605 cameraState->setShimParams(params);
2606 } else {
2607 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002608 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002609 }
2610 }
2611
Ravneetaeb20dc2022-03-30 05:33:03 +00002612 // Enable/disable camera service watchdog
2613 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2614
Emilian Peev6d45db82024-01-18 20:11:54 +00002615 CameraMetadata chars;
2616 bool rotateAndCropSupported = true;
2617 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002618 &chars, rotationOverride);
Emilian Peev6d45db82024-01-18 20:11:54 +00002619 if (err == OK) {
2620 auto availableRotateCropEntry = chars.find(
2621 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2622 if (availableRotateCropEntry.count <= 1) {
2623 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002624 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002625 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002626 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2627 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002628 }
2629
Emilian Peev6d45db82024-01-18 20:11:54 +00002630 if (rotateAndCropSupported) {
2631 // Set rotate-and-crop override behavior
2632 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2633 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002634 } else if (rotationOverride != hardware::ICameraService::ROTATION_OVERRIDE_NONE &&
2635 portraitRotation != 0) {
Emilian Peev6d45db82024-01-18 20:11:54 +00002636 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2637 switch (portraitRotation) {
2638 case 90:
2639 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2640 break;
2641 case 180:
2642 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2643 break;
2644 case 270:
2645 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2646 break;
2647 default:
2648 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2649 break;
2650 }
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002651 // Here we're communicating to the client the chosen rotate
2652 // and crop mode to send to the HAL
Emilian Peev6d45db82024-01-18 20:11:54 +00002653 client->setRotateAndCropOverride(rotateAndCropMode);
2654 } else {
2655 client->setRotateAndCropOverride(
2656 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2657 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2658 }
2659 }
2660
2661 bool autoframingSupported = true;
2662 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2663 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2664 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2665 autoframingSupported = false;
2666 }
2667
2668 if (autoframingSupported) {
2669 // Set autoframing override behaviour
2670 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2671 client->setAutoframingOverride(mOverrideAutoframingMode);
2672 } else {
2673 client->setAutoframingOverride(
2674 mCameraServiceProxyWrapper->getAutoframingOverride(
2675 clientPackageName));
2676 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002677 }
2678
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002679 bool isCameraPrivacyEnabled;
2680 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002681 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002682 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2683 toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2684 } else {
2685 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002686 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002687 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002688
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002689 if (client->supportsCameraMute()) {
2690 client->setCameraMute(
2691 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2692 } else if (isCameraPrivacyEnabled) {
2693 // no camera mute supported, but privacy is on! => disconnect
2694 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2695 client->getPackageName().c_str(), cameraId.c_str());
2696 // Do not hold mServiceLock while disconnecting clients, but
2697 // retain the condition blocking other clients from connecting
2698 // in mServiceLockWrapper if held.
2699 mServiceLock.unlock();
2700 // Clear caller identity temporarily so client disconnect PID
2701 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002702 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002703 // Note AppOp to trigger the "Unblock" dialog
2704 client->noteAppOp();
2705 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002706 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002707 // Reacquire mServiceLock
2708 mServiceLock.lock();
2709
2710 return STATUS_ERROR_FMT(ERROR_DISABLED,
2711 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002712 }
2713
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002714 if (shimUpdateOnly) {
2715 // If only updating legacy shim parameters, immediately disconnect client
2716 mServiceLock.unlock();
2717 client->disconnect();
2718 mServiceLock.lock();
2719 } else {
2720 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002721 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002722 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002723
2724 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002725 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002726 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002727 } // lock is destroyed, allow further connect calls
2728
2729 // Important: release the mutex here so the client can call back into the service from its
2730 // destructor (can be at the end of the call)
2731 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002732
2733 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002734 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002735 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002736
Cliff Wud3a05312021-04-26 23:07:31 +08002737 {
2738 Mutex::Autolock lock(mInjectionParametersLock);
2739 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2740 mInjectionInitPending = false;
2741 status_t res = NO_ERROR;
2742 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2743 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002744 sp<BasicClient> clientSp = clientDescriptor->getValue();
2745 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2746 if(res != OK) {
2747 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2748 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002749 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002750 }
2751 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002752 if (res != OK) {
2753 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2754 }
2755 } else {
2756 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002757 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002758 res = NO_INIT;
2759 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2760 }
2761 }
2762 }
2763
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002764 return ret;
2765}
2766
Austin Borgered99f642023-06-01 16:51:35 -07002767status_t CameraService::addOfflineClient(const std::string &cameraId,
2768 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002769 if (offlineClient.get() == nullptr) {
2770 return BAD_VALUE;
2771 }
2772
2773 {
2774 // Acquire mServiceLock and prevent other clients from connecting
2775 std::unique_ptr<AutoConditionLock> lock =
2776 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2777
2778 if (lock == nullptr) {
2779 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2780 , __FUNCTION__, offlineClient->getClientPid());
2781 return TIMED_OUT;
2782 }
2783
2784 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2785 if (onlineClientDesc.get() == nullptr) {
2786 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2787 cameraId.c_str());
2788 return BAD_VALUE;
2789 }
2790
2791 // Offline clients do not evict or conflict with other online devices. Resource sharing
2792 // conflicts are handled by the camera provider which will either succeed or fail before
2793 // reaching this method.
2794 const auto& onlinePriority = onlineClientDesc->getPriority();
2795 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2796 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002797 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002798 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002799 // native clients don't have offline processing support.
2800 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002801 if (offlineClientDesc == nullptr) {
2802 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2803 return BAD_VALUE;
2804 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002805
2806 // Allow only one offline device per camera
2807 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2808 if (!incompatibleClients.empty()) {
2809 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2810 return BAD_VALUE;
2811 }
2812
Austin Borgered99f642023-06-01 16:51:35 -07002813 std::string monitorTags = isClientWatched(offlineClient.get())
2814 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002815 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002816 if (err != OK) {
2817 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2818 return err;
2819 }
2820
2821 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2822 if (evicted.size() > 0) {
2823 for (auto& i : evicted) {
2824 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002825 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002826 }
2827
2828 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2829 "properly", __FUNCTION__);
2830
2831 return BAD_VALUE;
2832 }
2833
2834 logConnectedOffline(offlineClientDesc->getKey(),
2835 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002836 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002837
2838 sp<IBinder> remoteCallback = offlineClient->getRemote();
2839 if (remoteCallback != nullptr) {
2840 remoteCallback->linkToDeath(this);
2841 }
2842 } // lock is destroyed, allow further connect calls
2843
2844 return OK;
2845}
2846
Austin Borgered99f642023-06-01 16:51:35 -07002847Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002848 int32_t torchStrength, const sp<IBinder>& clientBinder,
2849 const AttributionSourceState& clientAttribution, int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002850 Mutex::Autolock lock(mServiceLock);
2851
2852 ATRACE_CALL();
2853 if (clientBinder == nullptr) {
2854 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2855 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2856 "Torch client binder in null.");
2857 }
2858
Austin Borger22c5c852024-03-08 13:31:36 -08002859 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002860 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2861 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002862 if (!cameraIdOptional.has_value()) {
2863 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002864 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002865 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2866 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2867 }
2868 std::string cameraId = cameraIdOptional.value();
2869
Austin Borgered99f642023-06-01 16:51:35 -07002870 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002871 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002872 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002873 }
2874
2875 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002876 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002877 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002878 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002879 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002880 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002881 }
2882
2883 StatusInternal cameraStatus = state->getStatus();
2884 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2885 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002886 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002887 (int)cameraStatus);
2888 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002889 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002890 }
2891
2892 {
2893 Mutex::Autolock al(mTorchStatusMutex);
2894 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002895 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002896 if (err != OK) {
2897 if (err == NAME_NOT_FOUND) {
2898 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002899 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002900 }
2901 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002902 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002903 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2904 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002905 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002906 }
2907
2908 if (status == TorchModeStatus::NOT_AVAILABLE) {
2909 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2910 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002911 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002912 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2913 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002914 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002915 } else {
2916 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002917 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002918 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2919 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002920 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002921 }
2922 }
2923 }
2924
2925 {
2926 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002927 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002928 }
2929 // Check if the current torch strength level is same as the new one.
2930 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002931 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002932
Austin Borgered99f642023-06-01 16:51:35 -07002933 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002934
2935 if (err != OK) {
2936 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002937 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002938 switch (err) {
2939 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002940 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2941 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002942 errorCode = ERROR_ILLEGAL_ARGUMENT;
2943 break;
2944 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002945 msg = fmt::sprintf("Camera \"%s\" is in use",
2946 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002947 errorCode = ERROR_CAMERA_IN_USE;
2948 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002949 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002950 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002951 "valid range.", torchStrength);
2952 errorCode = ERROR_ILLEGAL_ARGUMENT;
2953 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002954 default:
Austin Borgered99f642023-06-01 16:51:35 -07002955 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002956 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002957 }
Austin Borgered99f642023-06-01 16:51:35 -07002958 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2959 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002960 }
2961
2962 {
2963 // update the link to client's death
2964 // Store the last client that turns on each camera's torch mode.
2965 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002966 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002967 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002968 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002969 } else {
2970 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2971 mTorchClientMap.replaceValueAt(index, clientBinder);
2972 }
2973 clientBinder->linkToDeath(this);
2974 }
2975
Austin Borger22c5c852024-03-08 13:31:36 -08002976 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002977 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002978 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002979 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002980 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002981 }
2982 return Status::ok();
2983}
2984
malikakash73125c62023-07-21 22:44:34 +00002985Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Austin Borger65e64642024-06-11 15:58:23 -07002986 const sp<IBinder>& clientBinder, const AttributionSourceState& clientAttribution,
2987 int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002988 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002989
2990 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002991 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002992 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002993 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2994 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002995 }
2996
Austin Borger22c5c852024-03-08 13:31:36 -08002997 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002998 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2999 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00003000 if (!cameraIdOptional.has_value()) {
3001 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07003002 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00003003 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3004 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3005 }
3006 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003007
Austin Borgered99f642023-06-01 16:51:35 -07003008 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003009 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07003010 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003011 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003012 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07003013 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003014 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07003015 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003016 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003017 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003018 }
3019
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003020 StatusInternal cameraStatus = state->getStatus();
3021 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003022 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07003023 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
3024 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003025 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003026 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003027 }
3028
3029 {
3030 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003031 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003032 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003033 if (err != OK) {
3034 if (err == NAME_NOT_FOUND) {
3035 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003036 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003037 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003038 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003039 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003040 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07003041 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003042 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003043 }
3044
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003045 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003046 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003047 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003048 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003049 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3050 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003051 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003052 } else {
3053 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003054 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003055 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3056 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003057 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003058 }
3059 }
3060 }
3061
Ruben Brunk99e69712015-05-26 17:25:07 -07003062 {
3063 // Update UID map - this is used in the torch status changed callbacks, so must be done
3064 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003065 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003066 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003067 }
3068
Austin Borgered99f642023-06-01 16:51:35 -07003069 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003070
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003071 if (err != OK) {
3072 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003073 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003074 switch (err) {
3075 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003076 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3077 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003078 errorCode = ERROR_ILLEGAL_ARGUMENT;
3079 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003080 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003081 msg = fmt::sprintf("Camera \"%s\" is in use",
3082 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003083 errorCode = ERROR_CAMERA_IN_USE;
3084 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003085 default:
Austin Borgered99f642023-06-01 16:51:35 -07003086 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003087 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003088 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003089 errorCode = ERROR_INVALID_OPERATION;
3090 }
Austin Borgered99f642023-06-01 16:51:35 -07003091 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3092 logServiceError(msg, errorCode);
3093 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003094 }
3095
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003096 {
3097 // update the link to client's death
3098 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003099 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003100 if (enabled) {
3101 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003102 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003103 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003104 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003105 mTorchClientMap.replaceValueAt(index, clientBinder);
3106 }
3107 clientBinder->linkToDeath(this);
3108 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003109 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003110 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003111 }
3112
Austin Borger22c5c852024-03-08 13:31:36 -08003113 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003114 std::string torchState = enabled ? "on" : "off";
3115 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3116 torchState.c_str(), clientPid);
3117 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003118 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003119}
3120
Austin Borgered99f642023-06-01 16:51:35 -07003121void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3122 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3123 mTorchUidMap[cameraId].first = uid;
3124 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003125 } else {
3126 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003127 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003128 }
3129}
3130
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003131Status CameraService::notifySystemEvent(int32_t eventId,
3132 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003133 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003134 const int selfPid = getpid();
3135
3136 // Permission checks
3137 if (pid != selfPid) {
3138 // Ensure we're being called by system_server, or similar process with
3139 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003140 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003141 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003142 ALOGE("Permission Denial: cannot send updates to camera service about system"
3143 " events from pid=%d, uid=%d", pid, uid);
3144 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003145 "No permission to send updates to camera service about system events"
3146 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003147 }
3148 }
3149
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003150 ATRACE_CALL();
3151
Ruben Brunk36597b22015-03-20 22:15:57 -07003152 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003153 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003154 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003155 // from a system server crash
3156 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003157 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003158 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003159 break;
3160 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003161 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3162 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003163 if (args.size() != 1) {
3164 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3165 "USB Device Event requires 1 argument");
3166 }
3167
Valentin Iftime29e2e152021-08-13 15:17:33 +02003168 // Notify CameraProviderManager for lazy HALs
3169 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3170 std::to_string(args[0]));
3171 break;
3172 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003173 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003174 default: {
3175 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3176 eventId);
3177 break;
3178 }
3179 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003180 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003181}
3182
Emilian Peev53722fa2019-02-22 17:47:20 -08003183void CameraService::notifyMonitoredUids() {
3184 Mutex::Autolock lock(mStatusListenerLock);
3185
3186 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003187 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003188 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3189 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003190 }
3191}
3192
Austin Borgerdddb7552023-03-30 17:53:01 -07003193void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3194 Mutex::Autolock lock(mStatusListenerLock);
3195
3196 for (const auto& it : mListenerList) {
3197 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3198 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3199 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3200 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3201 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3202 }
3203 }
3204}
3205
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003206Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003207 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003208 const int selfPid = getpid();
3209
3210 // Permission checks
3211 if (pid != selfPid) {
3212 // Ensure we're being called by system_server, or similar process with
3213 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003214 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003215 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003216 ALOGE("Permission Denial: cannot send updates to camera service about device"
3217 " state changes from pid=%d, uid=%d", pid, uid);
3218 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3219 "No permission to send updates to camera service about device state"
3220 " changes from pid=%d, uid=%d", pid, uid);
3221 }
3222 }
3223
3224 ATRACE_CALL();
3225
Austin Borger18b30a72022-10-27 12:20:29 -07003226 {
3227 Mutex::Autolock lock(mServiceLock);
3228 mDeviceState = newState;
3229 }
3230
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003231 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003232
3233 return Status::ok();
3234}
3235
Emilian Peev8b64f282021-03-25 16:49:57 -07003236Status CameraService::notifyDisplayConfigurationChange() {
3237 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003238 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003239 const int selfPid = getpid();
3240
3241 // Permission checks
3242 if (callingPid != selfPid) {
3243 // Ensure we're being called by system_server, or similar process with
3244 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003245 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003246 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003247 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3248 " changes from pid=%d, uid=%d", callingPid, uid);
3249 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3250 "No permission to send updates to camera service about orientation"
3251 " changes from pid=%d, uid=%d", callingPid, uid);
3252 }
3253 }
3254
3255 Mutex::Autolock lock(mServiceLock);
3256
3257 // Don't do anything if rotate-and-crop override via cmd is active
3258 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3259
3260 const auto clients = mActiveClientManager.getAll();
3261 for (auto& current : clients) {
3262 if (current != nullptr) {
3263 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003264 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3265 basicClient->setRotateAndCropOverride(
3266 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3267 basicClient->getPackageName(),
3268 basicClient->getCameraFacing(),
3269 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003270 }
3271 }
3272 }
3273
3274 return Status::ok();
3275}
3276
3277Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003278 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3279 ATRACE_CALL();
3280 if (!concurrentCameraIds) {
3281 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3282 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3283 }
3284
3285 if (!mInitialized) {
3286 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003287 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003288 return STATUS_ERROR(ERROR_DISCONNECTED,
3289 "Camera subsystem is not available");
3290 }
3291 // First call into the provider and get the set of concurrent camera
3292 // combinations
3293 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003294 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003295 for (auto &combination : concurrentCameraCombinations) {
Biswarup Pal7d072862024-04-17 15:24:47 +00003296 std::vector<std::pair<std::string, int32_t>> validCombination;
3297 int32_t firstDeviceId = kInvalidDeviceId;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003298 for (auto &cameraId : combination) {
3299 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003300 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003301 if (state == nullptr) {
3302 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3303 continue;
3304 }
3305 StatusInternal status = state->getStatus();
3306 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3307 continue;
3308 }
Austin Borgered99f642023-06-01 16:51:35 -07003309 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003310 continue;
3311 }
Biswarup Pal7d072862024-04-17 15:24:47 +00003312 auto [cameraOwnerDeviceId, mappedCameraId] =
3313 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
3314 if (firstDeviceId == kInvalidDeviceId) {
3315 firstDeviceId = cameraOwnerDeviceId;
3316 } else if (firstDeviceId != cameraOwnerDeviceId) {
3317 // Found an invalid combination which contains cameras with different device id's,
3318 // hence discard it.
3319 validCombination.clear();
3320 break;
3321 }
3322 validCombination.push_back({mappedCameraId, cameraOwnerDeviceId});
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003323 }
3324 if (validCombination.size() != 0) {
3325 concurrentCameraIds->push_back(std::move(validCombination));
3326 }
3327 }
3328 return Status::ok();
3329}
3330
3331Status CameraService::isConcurrentSessionConfigurationSupported(
3332 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Austin Borger65e64642024-06-11 15:58:23 -07003333 int targetSdkVersion, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal7d072862024-04-17 15:24:47 +00003334 /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003335 if (!isSupported) {
3336 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3337 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3338 }
3339
3340 if (!mInitialized) {
3341 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3342 return STATUS_ERROR(ERROR_DISCONNECTED,
3343 "Camera subsystem is not available");
3344 }
3345
Biswarup Pal7d072862024-04-17 15:24:47 +00003346 for (auto cameraIdAndSessionConfiguration : cameraIdsAndSessionConfigurations) {
3347 std::optional<std::string> cameraIdOptional =
Austin Borger65e64642024-06-11 15:58:23 -07003348 resolveCameraId(cameraIdAndSessionConfiguration.mCameraId,
3349 clientAttribution.deviceId, devicePolicy);
Biswarup Pal7d072862024-04-17 15:24:47 +00003350 if (!cameraIdOptional.has_value()) {
3351 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07003352 cameraIdAndSessionConfiguration.mCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal7d072862024-04-17 15:24:47 +00003353 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3354 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3355 }
3356 cameraIdAndSessionConfiguration.mCameraId = cameraIdOptional.value();
3357 }
3358
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003359 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003360 int callingPid = getCallingPid();
3361 int callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003362 bool hasCameraPermission = ((callingPid == getpid()) ||
Biswarup Pal7d072862024-04-17 15:24:47 +00003363 hasPermissionsForCamera(callingPid, callingUid,
3364 devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT
Austin Borger65e64642024-06-11 15:58:23 -07003365 ? kDefaultDeviceId : clientAttribution.deviceId));
Austin Borger249e6592024-03-10 22:28:11 -07003366 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003367 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3368 "android.permission.CAMERA needed to call"
3369 "isConcurrentSessionConfigurationSupported");
3370 }
3371
3372 status_t res =
3373 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003374 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3375 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003376 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003377 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003378 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003379 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3380 "support %s (%d)", strerror(-res), res);
3381 }
3382 return Status::ok();
3383}
3384
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003385Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3386 /*out*/
3387 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003388 return addListenerHelper(listener, cameraStatuses);
3389}
3390
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003391binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3392 std::vector<hardware::CameraStatus>* cameraStatuses) {
3393 return addListenerHelper(listener, cameraStatuses, false, true);
3394}
3395
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003396Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3397 /*out*/
3398 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003399 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003400 ATRACE_CALL();
3401
Igor Murashkinbfc99152013-02-27 12:55:20 -08003402 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003403
Ruben Brunk3450ba72015-06-16 11:00:37 -07003404 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003405 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003406 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003407 }
3408
Austin Borger22c5c852024-03-08 13:31:36 -08003409 auto clientPid = getCallingPid();
3410 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003411 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003412
Igor Murashkinbfc99152013-02-27 12:55:20 -08003413 Mutex::Autolock lock(mServiceLock);
3414
Ruben Brunkcc776712015-02-17 20:18:47 -08003415 {
3416 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003417 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003418 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003419 ALOGW("%s: Tried to add listener %p which was already subscribed",
3420 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003421 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003422 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003423 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003424
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003425 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003426 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3427 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003428 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003429 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003430 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003431 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003432 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3433 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3434 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003435 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003436 // The listener still needs to be added to the list of listeners, regardless of what
3437 // permissions the listener process has / whether it is a vendor listener. Since it might be
3438 // eligible to listen to other camera ids.
3439 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003440 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003441 }
3442
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003443 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003444 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003445 Mutex::Autolock lock(mCameraStatesLock);
3446 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003447 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3448 auto [deviceId, mappedCameraId] =
3449 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3450
3451 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003452 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003453 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3454 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003455 }
3456 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003457 // Remove the camera statuses that should be hidden from the client, we do
3458 // this after collecting the states in order to avoid holding
3459 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3460 // the same time.
3461 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3462 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003463 std::string cameraId = s.cameraId;
3464 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
malikakash98260df2024-05-10 23:33:57 +00003465 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM);
Biswarup Pal37a75182024-01-16 15:53:35 +00003466 if (!cameraIdOptional.has_value()) {
3467 std::string msg =
3468 fmt::sprintf(
3469 "Camera %s: Invalid camera id for device id %d",
3470 s.cameraId.c_str(), s.deviceId);
3471 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3472 return true;
3473 }
3474 cameraId = cameraIdOptional.value();
3475 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3476 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3477 ALOGE("%s: Invalid camera id %s, skipping status update",
3478 __FUNCTION__, s.cameraId.c_str());
3479 return true;
3480 }
3481 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3482 clientUid);
3483 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003484
Biswarup Pal37a75182024-01-16 15:53:35 +00003485 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003486 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003487 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003488 // Add only default device cameras here, as virtual cameras currently don't support torch
3489 // anyway. Note that this is a simplification of the implementation here, and we should
3490 // change this when virtual cameras support torch.
3491 if (s.deviceId == kDefaultDeviceId) {
3492 idsChosenForCallback.insert(s.cameraId);
3493 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003494 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003495
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003496 /*
3497 * Immediately signal current torch status to this listener only
3498 * This may be a subset of all the devices, so don't include it in the response directly
3499 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003500 {
3501 Mutex::Autolock al(mTorchStatusMutex);
3502 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003503 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003504 // The camera id is visible to the client. Fine to send torch
3505 // callback.
3506 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003507 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3508 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003509 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003510 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003511 }
3512
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003513 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003514}
Ruben Brunkcc776712015-02-17 20:18:47 -08003515
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003516Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003517 ATRACE_CALL();
3518
Igor Murashkinbfc99152013-02-27 12:55:20 -08003519 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3520
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003521 if (listener == 0) {
3522 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003523 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003524 }
3525
Igor Murashkinbfc99152013-02-27 12:55:20 -08003526 Mutex::Autolock lock(mServiceLock);
3527
Ruben Brunkcc776712015-02-17 20:18:47 -08003528 {
3529 Mutex::Autolock lock(mStatusListenerLock);
3530 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003531 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003532 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003533 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003534 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003535 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003536 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003537 }
3538 }
3539
3540 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3541 __FUNCTION__, listener.get());
3542
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003543 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003544}
3545
Austin Borgered99f642023-06-01 16:51:35 -07003546Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003547
3548 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003549 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3550
3551 if (parameters == NULL) {
3552 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003553 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003554 }
3555
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003556 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003557
3558 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003559 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003560 // Error logged by caller
3561 return ret;
3562 }
3563
3564 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003565
Austin Borgered99f642023-06-01 16:51:35 -07003566 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003567
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003568 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003569}
3570
malikakash98260df2024-05-10 23:33:57 +00003571Status CameraService::supportsCameraApi(const std::string& cameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003572 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003573 ATRACE_CALL();
3574
Austin Borgered99f642023-06-01 16:51:35 -07003575 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003576
3577 switch (apiVersion) {
3578 case API_VERSION_1:
3579 case API_VERSION_2:
3580 break;
3581 default:
Austin Borgered99f642023-06-01 16:51:35 -07003582 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3583 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3584 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003585 }
3586
Austin Borger18b30a72022-10-27 12:20:29 -07003587 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00003588 auto deviceVersionAndTransport =
3589 getDeviceVersion(cameraId,
3590 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
3591 &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003592 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003593 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3594 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3595 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003596 }
3597 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3598 int deviceVersion = deviceVersionAndTransport.first;
3599 switch (deviceVersion) {
3600 case CAMERA_DEVICE_API_VERSION_1_0:
3601 case CAMERA_DEVICE_API_VERSION_3_0:
3602 case CAMERA_DEVICE_API_VERSION_3_1:
3603 if (apiVersion == API_VERSION_2) {
3604 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003605 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003606 *isSupported = false;
3607 } else { // if (apiVersion == API_VERSION_1) {
3608 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003609 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003610 *isSupported = true;
3611 }
3612 break;
3613 case CAMERA_DEVICE_API_VERSION_3_2:
3614 case CAMERA_DEVICE_API_VERSION_3_3:
3615 case CAMERA_DEVICE_API_VERSION_3_4:
3616 case CAMERA_DEVICE_API_VERSION_3_5:
3617 case CAMERA_DEVICE_API_VERSION_3_6:
3618 case CAMERA_DEVICE_API_VERSION_3_7:
3619 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003620 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003621 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003622 break;
3623 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003624 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3625 deviceVersion, cameraId.c_str());
3626 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3627 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003628 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003629 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003630 } else {
3631 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003632 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003633 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003634}
3635
malikakash98260df2024-05-10 23:33:57 +00003636Status CameraService::isHiddenPhysicalCamera(const std::string& cameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003637 /*out*/ bool *isSupported) {
3638 ATRACE_CALL();
3639
Austin Borgered99f642023-06-01 16:51:35 -07003640 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3641 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003642
3643 return Status::ok();
3644}
3645
Cliff Wud8cae102021-03-11 01:37:42 +08003646Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003647 const std::string& packageName, const std::string& internalCamId,
3648 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003649 const sp<ICameraInjectionCallback>& callback,
3650 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003651 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003652 ATRACE_CALL();
3653
Austin Borgered99f642023-06-01 16:51:35 -07003654 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003655 const int pid = getCallingPid();
3656 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003657 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3658 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003659 "Permission Denial: no permission to inject camera");
3660 }
3661
3662 // Do not allow any camera injection that injects or replaces a virtual camera.
3663 auto [deviceIdForInternalCamera, _] =
3664 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3665 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3666 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3667 "Cannot replace a virtual camera");
3668 }
3669 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3670 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3671 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3672 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3673 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003674 }
3675
3676 ALOGV(
3677 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3678 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003679 __FUNCTION__, packageName.c_str(),
3680 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003681
Cliff Wud3a05312021-04-26 23:07:31 +08003682 {
3683 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003684 mInjectionInternalCamId = internalCamId;
3685 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003686 mInjectionStatusListener->addListener(callback);
3687 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003688 status_t res = NO_ERROR;
3689 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3690 // If the client already exists, we can directly connect to the camera device through the
3691 // client's injectCamera(), otherwise we need to wait until the client is established
3692 // (execute connectHelper()) before injecting the camera to the camera device.
3693 if (clientDescriptor != nullptr) {
3694 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003695 sp<BasicClient> clientSp = clientDescriptor->getValue();
3696 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3697 if(res != OK) {
3698 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3699 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003700 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003701 }
3702 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003703 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003704 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3705 }
3706 } else {
3707 mInjectionInitPending = true;
3708 }
3709 }
Cliff Wud8cae102021-03-11 01:37:42 +08003710
Cliff Wud3a05312021-04-26 23:07:31 +08003711 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003712}
3713
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003714Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003715 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003716 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3717 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3718 return Status::ok();
3719}
3720
Ruben Brunkcc776712015-02-17 20:18:47 -08003721void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003722 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003723 for (auto& i : mActiveClientManager.getAll()) {
3724 auto clientSp = i->getValue();
3725 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003726 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003727 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003728 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003729 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003730 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003731}
3732
Ruben Brunkcc776712015-02-17 20:18:47 -08003733bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003734 bool ret = false;
3735 {
3736 // Acquire mServiceLock and prevent other clients from connecting
3737 std::unique_ptr<AutoConditionLock> lock =
3738 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003739
Ruben Brunkcc776712015-02-17 20:18:47 -08003740 std::vector<sp<BasicClient>> evicted;
3741 for (auto& i : mActiveClientManager.getAll()) {
3742 auto clientSp = i->getValue();
3743 if (clientSp.get() == nullptr) {
3744 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3745 mActiveClientManager.remove(i);
3746 continue;
3747 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003748 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003749 mActiveClientManager.remove(i);
3750 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003751
Ruben Brunkcc776712015-02-17 20:18:47 -08003752 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003753 clientSp->notifyError(
3754 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003755 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003756 }
3757 }
3758
Ruben Brunkcc776712015-02-17 20:18:47 -08003759 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3760 // other clients from connecting in mServiceLockWrapper if held
3761 mServiceLock.unlock();
3762
Ruben Brunk36597b22015-03-20 22:15:57 -07003763 // Do not clear caller identity, remote caller should be client proccess
3764
Ruben Brunkcc776712015-02-17 20:18:47 -08003765 for (auto& i : evicted) {
3766 if (i.get() != nullptr) {
3767 i->disconnect();
3768 ret = true;
3769 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003770 }
3771
Ruben Brunkcc776712015-02-17 20:18:47 -08003772 // Reacquire mServiceLock
3773 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003774
Ruben Brunkcc776712015-02-17 20:18:47 -08003775 } // lock is destroyed, allow further connect calls
3776
3777 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003778}
3779
Ruben Brunkcc776712015-02-17 20:18:47 -08003780std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003781 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003782 std::shared_ptr<CameraState> state;
3783 {
3784 Mutex::Autolock lock(mCameraStatesLock);
3785 auto iter = mCameraStates.find(cameraId);
3786 if (iter != mCameraStates.end()) {
3787 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003788 }
3789 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003790 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003791}
3792
Austin Borgered99f642023-06-01 16:51:35 -07003793sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003794 // Remove from active clients list
3795 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3796 if (clientDescriptorPtr == nullptr) {
3797 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003798 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003799 return sp<BasicClient>{nullptr};
3800 }
3801
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003802 sp<BasicClient> client = clientDescriptorPtr->getValue();
3803 if (client.get() != nullptr) {
3804 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3805 }
3806 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003807}
3808
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003809void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003810 // Acquire mServiceLock and prevent other clients from connecting
3811 std::unique_ptr<AutoConditionLock> lock =
3812 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3813
Ruben Brunk6267b532015-04-30 17:44:07 -07003814 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003815 for (size_t i = 0; i < newUserIds.size(); i++) {
3816 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003817 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003818 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003819 return;
3820 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003821 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003822 }
3823
Ruben Brunka8ca9152015-04-07 14:23:40 -07003824
Ruben Brunk6267b532015-04-30 17:44:07 -07003825 if (newAllowedUsers == mAllowedUsers) {
3826 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3827 return;
3828 }
3829
3830 logUserSwitch(mAllowedUsers, newAllowedUsers);
3831
3832 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003833
3834 // Current user has switched, evict all current clients.
3835 std::vector<sp<BasicClient>> evicted;
3836 for (auto& i : mActiveClientManager.getAll()) {
3837 auto clientSp = i->getValue();
3838
3839 if (clientSp.get() == nullptr) {
3840 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3841 continue;
3842 }
3843
Ruben Brunk6267b532015-04-30 17:44:07 -07003844 // Don't evict clients that are still allowed.
3845 uid_t clientUid = clientSp->getClientUid();
3846 userid_t clientUserId = multiuser_get_user_id(clientUid);
3847 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3848 continue;
3849 }
3850
Ruben Brunk36597b22015-03-20 22:15:57 -07003851 evicted.push_back(clientSp);
3852
Ruben Brunk36597b22015-03-20 22:15:57 -07003853 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003854 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003855
Ruben Brunk36597b22015-03-20 22:15:57 -07003856 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003857 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003858 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003859 " to user switch.", i->getKey().c_str(),
3860 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003861 i->getOwnerId(), i->getPriority().getScore(),
3862 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003863
3864 }
3865
3866 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3867 // blocking other clients from connecting in mServiceLockWrapper if held.
3868 mServiceLock.unlock();
3869
3870 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08003871 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003872
3873 for (auto& i : evicted) {
3874 i->disconnect();
3875 }
3876
Austin Borger22c5c852024-03-08 13:31:36 -08003877 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003878
3879 // Reacquire mServiceLock
3880 mServiceLock.lock();
3881}
Ruben Brunkcc776712015-02-17 20:18:47 -08003882
Austin Borgered99f642023-06-01 16:51:35 -07003883void CameraService::logEvent(const std::string &event) {
3884 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003885 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003886 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003887 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003888 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003889 mEventLog.add(msg);
3890 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3891 // Error event not added to the dumpsys log before
3892 mEventLog.add(msg);
3893 sServiceErrorEventSet.insert(msg);
3894 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003895}
3896
Austin Borgered99f642023-06-01 16:51:35 -07003897void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3898 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003899 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003900 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3901 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003902}
3903
Austin Borgered99f642023-06-01 16:51:35 -07003904void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3905 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003906 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003907 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3908 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003909}
3910
Austin Borgered99f642023-06-01 16:51:35 -07003911void CameraService::logConnected(const std::string &cameraId, int clientPid,
3912 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003913 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003914 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3915 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003916}
3917
Austin Borgered99f642023-06-01 16:51:35 -07003918void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3919 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003920 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003921 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3922 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003923}
3924
Austin Borgered99f642023-06-01 16:51:35 -07003925void CameraService::logRejected(const std::string &cameraId, int clientPid,
3926 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003927 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003928 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3929 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003930}
3931
Austin Borgered99f642023-06-01 16:51:35 -07003932void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3933 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003934 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003935 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3936 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003937}
3938
Ruben Brunk6267b532015-04-30 17:44:07 -07003939void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3940 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003941 std::string newUsers = toString(newUserIds);
3942 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003943 if (oldUsers.size() == 0) {
3944 oldUsers = "<None>";
3945 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003946 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003947 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3948 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003949}
3950
Austin Borgered99f642023-06-01 16:51:35 -07003951void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003952 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003953 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003954}
3955
Austin Borgered99f642023-06-01 16:51:35 -07003956void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003957 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003958 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003959}
3960
Austin Borgered99f642023-06-01 16:51:35 -07003961void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003962 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003963 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003964}
3965
Austin Borgered99f642023-06-01 16:51:35 -07003966void CameraService::logServiceError(const std::string &msg, int errorCode) {
3967 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3968 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003969}
3970
Ruben Brunk36597b22015-03-20 22:15:57 -07003971status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3972 uint32_t flags) {
3973
Mathias Agopian65ab4712010-07-14 17:59:35 -07003974 // Permission checks
3975 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003976 case SHELL_COMMAND_TRANSACTION: {
3977 int in = data.readFileDescriptor();
3978 int out = data.readFileDescriptor();
3979 int err = data.readFileDescriptor();
3980 int argc = data.readInt32();
3981 Vector<String16> args;
3982 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3983 args.add(data.readString16());
3984 }
3985 sp<IBinder> unusedCallback;
3986 sp<IResultReceiver> resultReceiver;
3987 status_t status;
3988 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3989 return status;
3990 }
3991 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3992 return status;
3993 }
3994 status = shellCommand(in, out, err, args);
3995 if (resultReceiver != nullptr) {
3996 resultReceiver->send(status);
3997 }
3998 return NO_ERROR;
3999 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004000 }
4001
4002 return BnCameraService::onTransact(code, data, reply, flags);
4003}
4004
Mathias Agopian65ab4712010-07-14 17:59:35 -07004005// We share the media players for shutter and recording sound for all clients.
4006// A reference count is kept to determine when we will actually release the
4007// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09004008sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
4009 sp<MediaPlayer> mp = new MediaPlayer();
4010 status_t error;
4011 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08004012 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09004013 error = mp->prepare();
4014 }
4015 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004016 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09004017 mp->disconnect();
4018 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004019 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004020 }
4021 return mp;
4022}
4023
username5755fea2018-12-27 09:48:08 +08004024void CameraService::increaseSoundRef() {
4025 Mutex::Autolock lock(mSoundLock);
4026 mSoundRef++;
4027}
4028
4029void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004030 ATRACE_CALL();
4031
username5755fea2018-12-27 09:48:08 +08004032 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
4033 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
4034 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
4035 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
4036 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4037 }
4038 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
4039 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4040 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4041 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004042 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08004043 }
4044 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4045 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4046 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4047 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4048 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004049 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004050}
4051
username5755fea2018-12-27 09:48:08 +08004052void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004053 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004054 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004055 if (--mSoundRef) return;
4056
4057 for (int i = 0; i < NUM_SOUNDS; i++) {
4058 if (mSoundPlayer[i] != 0) {
4059 mSoundPlayer[i]->disconnect();
4060 mSoundPlayer[i].clear();
4061 }
4062 }
4063}
4064
4065void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004066 ATRACE_CALL();
4067
Mathias Agopian65ab4712010-07-14 17:59:35 -07004068 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004069 if (kind < 0 || kind >= NUM_SOUNDS) {
4070 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4071 return;
4072 }
4073
Mathias Agopian65ab4712010-07-14 17:59:35 -07004074 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004075 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004076 sp<MediaPlayer> player = mSoundPlayer[kind];
4077 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004078 player->seekTo(0);
4079 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004080 }
4081}
4082
4083// ----------------------------------------------------------------------------
4084
4085CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004086 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004087 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004088 const std::string& clientPackageName, bool systemNativeClient,
4089 const std::optional<std::string>& clientFeatureId,
4090 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004091 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004092 int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004093 int servicePid, int rotationOverride) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004094 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004095 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07004096 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004097 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004098 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004099 clientPid, clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004100 servicePid, rotationOverride),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004101 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004102{
Austin Borger22c5c852024-03-08 13:31:36 -08004103 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004104 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004105
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004106 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004107
username5755fea2018-12-27 09:48:08 +08004108 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004109
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004110 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004111}
4112
Mathias Agopian65ab4712010-07-14 17:59:35 -07004113// tear down the client
4114CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004115 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004116 mDestructionStarted = true;
4117
username5755fea2018-12-27 09:48:08 +08004118 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004119 // unconditionally disconnect. function is idempotent
4120 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004121}
4122
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004123sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4124
Igor Murashkin634a5152013-02-20 17:15:11 -08004125CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004126 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004127 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004128 const std::string& clientPackageName, bool nativeClient,
4129 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004130 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004131 int servicePid, int rotationOverride):
Austin Borger249e6592024-03-10 22:28:11 -07004132 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004133 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004134 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004135 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4136 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004137 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004138 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004139 mDisconnected(false), mUidIsTrusted(false),
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004140 mRotationOverride(rotationOverride),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004141 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004142 mRemoteBinder(remoteCallback),
4143 mOpsActive(false),
4144 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004145{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004146 if (sCameraService == nullptr) {
4147 sCameraService = cameraService;
4148 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004149
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004150 // There are 2 scenarios in which a client won't have AppOps operations
4151 // (both scenarios : native clients)
4152 // 1) It's an system native client*, the package name will be empty
4153 // and it will return from this function in the previous if condition
4154 // (This is the same as the previously existing behavior).
4155 // 2) It is a system native client, but its package name has been
4156 // modified for debugging, however it still must not use AppOps since
4157 // the package name is not a real one.
4158 //
4159 // * system native client - native client with UID < AID_APP_START. It
4160 // doesn't exclude clients not on the system partition.
4161 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004162 mAppOpsManager = std::make_unique<AppOpsManager>();
4163 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004164
Charles Chenf075f082024-03-04 23:32:55 +00004165 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004166}
4167
4168CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004169 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004170 mDestructionStarted = true;
4171}
4172
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004173binder::Status CameraService::BasicClient::disconnect() {
4174 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004175 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004176 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004177 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004178 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004179
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004180 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004181 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004182 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004183 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004184
4185 sp<IBinder> remote = getRemote();
4186 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004187 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004188 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004189
4190 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004191 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004192 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004193 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004194 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004195
Igor Murashkincba2c162013-03-20 15:56:31 -07004196 // client shouldn't be able to call into us anymore
4197 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004198
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004199 const auto& mActivityManager = getActivityManager();
4200 if (mActivityManager) {
4201 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004202 getCallingUid(),
4203 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004204 }
4205
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004206 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004207}
4208
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004209status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4210 // No dumping of clients directly over Binder,
4211 // must go through CameraService::dump
4212 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004213 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004214 return OK;
4215}
4216
Austin Borgered99f642023-06-01 16:51:35 -07004217status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004218 // Can't watch tags directly, must go through CameraService::startWatchingTags
4219 return OK;
4220}
4221
4222status_t CameraService::BasicClient::stopWatchingTags(int) {
4223 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4224 return OK;
4225}
4226
4227status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4228 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4229 return OK;
4230}
4231
Austin Borgered99f642023-06-01 16:51:35 -07004232std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004233 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004234}
4235
Emilian Peev8b64f282021-03-25 16:49:57 -07004236int CameraService::BasicClient::getCameraFacing() const {
4237 return mCameraFacing;
4238}
4239
4240int CameraService::BasicClient::getCameraOrientation() const {
4241 return mOrientation;
4242}
Ruben Brunkcc776712015-02-17 20:18:47 -08004243
4244int CameraService::BasicClient::getClientPid() const {
4245 return mClientPid;
4246}
4247
Ruben Brunk6267b532015-04-30 17:44:07 -07004248uid_t CameraService::BasicClient::getClientUid() const {
4249 return mClientUid;
4250}
4251
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004252bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4253 // Defaults to API2.
4254 return level == API_2;
4255}
4256
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004257status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004258 {
4259 Mutex::Autolock l(mAudioRestrictionLock);
4260 mAudioRestriction = mode;
4261 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004262 sCameraService->updateAudioRestriction();
4263 return OK;
4264}
4265
4266int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004267 return sCameraService->updateAudioRestriction();
4268}
4269
4270int32_t CameraService::BasicClient::getAudioRestriction() const {
4271 Mutex::Autolock l(mAudioRestrictionLock);
4272 return mAudioRestriction;
4273}
4274
4275bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4276 switch (mode) {
4277 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4278 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4279 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4280 return true;
4281 default:
4282 return false;
4283 }
4284}
4285
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004286status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4287 if (mode == AppOpsManager::MODE_ERRORED) {
4288 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004289 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004290 return PERMISSION_DENIED;
4291 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4292 // If the calling Uid is trusted (a native service), the AppOpsManager could
4293 // return MODE_IGNORED. Do not treat such case as error.
4294 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4295 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004296
4297 bool isCameraPrivacyEnabled;
4298 if (flags::camera_privacy_allowlist()) {
4299 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4300 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4301 } else {
4302 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004303 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004304 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004305 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4306 // We prefer to successfully open the camera and perform camera muting
4307 // or blocking in connectHelper as handleAppOpMode can be called before the
4308 // connection has been fully established and at that time camera muting
4309 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004310 if (!isUidActive || !isCameraPrivacyEnabled) {
Austin Borgerfd05d982024-04-22 15:54:50 -07004311 ALOGI("Camera %s: Access for \"%s\" has been restricted."
4312 "uid active: %s, privacy enabled: %s", mCameraIdStr.c_str(),
4313 mClientPackageName.c_str(), isUidActive ? "true" : "false",
4314 isCameraPrivacyEnabled ? "true" : "false");
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004315 // Return the same error as for device policy manager rejection
4316 return -EACCES;
4317 }
4318 }
4319 return OK;
4320}
4321
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004322status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004323 ATRACE_CALL();
4324
Igor Murashkine6800ce2013-03-04 17:25:57 -08004325 {
4326 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004327 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004328 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004329 if (mAppOpsManager != nullptr) {
4330 // Notify app ops that the camera is not available
4331 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004332
4333 if (flags::watch_foreground_changes()) {
4334 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4335 toString16(mClientPackageName),
4336 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4337 } else {
4338 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004339 toString16(mClientPackageName), mOpsCallback);
Austin Borgerca1e0062023-06-28 11:32:55 -07004340 }
Igor Murashkine6800ce2013-03-04 17:25:57 -08004341
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004342 // Just check for camera acccess here on open - delay startOp until
4343 // camera frames start streaming in startCameraStreamingOps
4344 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004345 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004346 status_t res = handleAppOpMode(mode);
4347 if (res != OK) {
4348 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004349 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004350 }
4351
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004352 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004353
4354 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004355 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004356
Austin Borgerdddb7552023-03-30 17:53:01 -07004357 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004358
Shuzhen Wang695044d2020-03-06 09:02:23 -08004359 // Notify listeners of camera open/close status
4360 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4361
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004362 return OK;
4363}
4364
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004365status_t CameraService::BasicClient::startCameraStreamingOps() {
4366 ATRACE_CALL();
4367
4368 if (!mOpsActive) {
4369 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4370 return INVALID_OPERATION;
4371 }
4372 if (mOpsStreaming) {
4373 ALOGV("%s: Streaming already active!", __FUNCTION__);
4374 return OK;
4375 }
4376
4377 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004378 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004379
4380 if (mAppOpsManager != nullptr) {
4381 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004382 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4383 toString16(mClientFeatureId),
4384 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004385 status_t res = handleAppOpMode(mode);
4386 if (res != OK) {
4387 return res;
4388 }
4389 }
4390
4391 mOpsStreaming = true;
4392
4393 return OK;
4394}
4395
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004396status_t CameraService::BasicClient::noteAppOp() {
4397 ATRACE_CALL();
4398
4399 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004400 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004401
4402 // noteAppOp is only used for when camera mute is not supported, in order
4403 // to trigger the sensor privacy "Unblock" dialog
4404 if (mAppOpsManager != nullptr) {
4405 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004406 toString16(mClientPackageName), toString16(mClientFeatureId),
4407 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004408 status_t res = handleAppOpMode(mode);
4409 if (res != OK) {
4410 return res;
4411 }
4412 }
4413
4414 return OK;
4415}
4416
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004417status_t CameraService::BasicClient::finishCameraStreamingOps() {
4418 ATRACE_CALL();
4419
4420 if (!mOpsActive) {
4421 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4422 return INVALID_OPERATION;
4423 }
4424 if (!mOpsStreaming) {
4425 ALOGV("%s: Streaming not active!", __FUNCTION__);
4426 return OK;
4427 }
4428
4429 if (mAppOpsManager != nullptr) {
4430 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004431 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004432 mOpsStreaming = false;
4433 }
4434
4435 return OK;
4436}
4437
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004438status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004439 ATRACE_CALL();
4440
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004441 if (mOpsStreaming) {
4442 // Make sure we've notified everyone about camera stopping
4443 finishCameraStreamingOps();
4444 }
4445
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004446 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004447 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004448 mOpsActive = false;
4449
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004450 // This function is called when a client disconnects. This should
4451 // release the camera, but actually only if it was in a proper
4452 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004453 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004454 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004455
Ruben Brunkcc776712015-02-17 20:18:47 -08004456 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004457 sCameraService->updateStatus(StatusInternal::PRESENT,
4458 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004459 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004460 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004461 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4462 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004463 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004464 mOpsCallback.clear();
4465
Austin Borgerdddb7552023-03-30 17:53:01 -07004466 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004467
Shuzhen Wang695044d2020-03-06 09:02:23 -08004468 // Notify listeners of camera open/close status
4469 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4470
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004471 return OK;
4472}
4473
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004474void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004475 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004476 if (mAppOpsManager == nullptr) {
4477 return;
4478 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004479 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004480 if (op != AppOpsManager::OP_CAMERA) {
4481 ALOGW("Unexpected app ops notification received: %d", op);
4482 return;
4483 }
4484
4485 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004486 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004487 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004488 ALOGV("checkOp returns: %d, %s ", res,
4489 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4490 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4491 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4492 "UNKNOWN");
4493
Shuzhen Wang64900852021-02-05 09:03:29 -08004494 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004495 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4496 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004497 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004498 } else if (res == AppOpsManager::MODE_IGNORED) {
4499 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004500
Austin Borgerca1e0062023-06-28 11:32:55 -07004501 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4502 // If not visible, but still active, then we want to block instead of muting the camera.
4503 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4504 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4505
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004506 bool isCameraPrivacyEnabled;
4507 if (flags::camera_privacy_allowlist()) {
4508 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4509 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4510 } else {
4511 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004512 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004513 }
4514
4515 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004516 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4517 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4518 isCameraPrivacyEnabled);
4519 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4520 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4521 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004522 if (!mUidIsTrusted) {
Austin Borgerca1e0062023-06-28 11:32:55 -07004523 if (flags::watch_foreground_changes()) {
4524 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4525 setCameraMute(true);
4526 } else {
4527 block();
4528 }
4529 } else {
4530 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4531 setCameraMute(true);
4532 } else if (!isUidActive
4533 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4534 block();
4535 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004536 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004537 }
Evan Severson09ab4002021-02-10 14:15:19 -08004538 } else if (res == AppOpsManager::MODE_ALLOWED) {
4539 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004540 }
4541}
4542
Svet Ganova453d0d2018-01-11 15:37:58 -08004543void CameraService::BasicClient::block() {
4544 ATRACE_CALL();
4545
4546 // Reset the client PID to allow server-initiated disconnect,
4547 // and to prevent further calls by client.
Austin Borger22c5c852024-03-08 13:31:36 -08004548 mClientPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004549 CaptureResultExtras resultExtras; // a dummy result (invalid)
4550 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4551 disconnect();
4552}
4553
Mathias Agopian65ab4712010-07-14 17:59:35 -07004554// ----------------------------------------------------------------------------
4555
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004556void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004557 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004558 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004559 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4560 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4561 api1ErrorCode = CAMERA_ERROR_DISABLED;
4562 }
4563 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004564 } else {
4565 ALOGE("mRemoteCallback is NULL!!");
4566 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004567}
4568
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004569// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004570binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004571 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004572 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004573}
4574
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004575bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4576 return level == API_1;
4577}
4578
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004579CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4580 mClient(client) {
4581}
4582
4583void CameraService::Client::OpsCallback::opChanged(int32_t op,
4584 const String16& packageName) {
4585 sp<BasicClient> client = mClient.promote();
4586 if (client != NULL) {
4587 client->opChanged(op, packageName);
4588 }
4589}
4590
Mathias Agopian65ab4712010-07-14 17:59:35 -07004591// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004592// UidPolicy
4593// ----------------------------------------------------------------------------
4594
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004595void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004596 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004597 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004598
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004599 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004600 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004601 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004602 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004603 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4604 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004605 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004606 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004607 if (res == OK) {
4608 mRegistered = true;
4609 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004610 } else {
4611 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004612 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004613}
4614
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004615void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004616 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004617 return;
4618 }
4619
4620 registerWithActivityManager();
4621}
4622
4623void CameraService::UidPolicy::registerSelf() {
4624 // Use check service to see if the activity service is available
4625 // If not available then register for notifications, instead of blocking
4626 // till the service is ready
4627 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004628 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004629 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004630 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004631 } else {
4632 registerWithActivityManager();
4633 }
4634}
4635
Svet Ganova453d0d2018-01-11 15:37:58 -08004636void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004637 Mutex::Autolock _l(mUidLock);
4638
Steven Moreland2f348142019-07-02 15:59:07 -07004639 mAm.unregisterUidObserver(this);
4640 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004641 mRegistered = false;
4642 mActiveUids.clear();
4643 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004644}
4645
4646void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4647 onUidIdle(uid, disabled);
4648}
4649
4650void CameraService::UidPolicy::onUidActive(uid_t uid) {
4651 Mutex::Autolock _l(mUidLock);
4652 mActiveUids.insert(uid);
4653}
4654
4655void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4656 bool deleted = false;
4657 {
4658 Mutex::Autolock _l(mUidLock);
4659 if (mActiveUids.erase(uid) > 0) {
4660 deleted = true;
4661 }
4662 }
4663 if (deleted) {
4664 sp<CameraService> service = mService.promote();
4665 if (service != nullptr) {
4666 service->blockClientsForUid(uid);
4667 }
4668 }
4669}
4670
Emilian Peev53722fa2019-02-22 17:47:20 -08004671void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004672 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004673 bool procStateChange = false;
4674 {
4675 Mutex::Autolock _l(mUidLock);
4676 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4677 mMonitoredUids[uid].procState != procState) {
4678 mMonitoredUids[uid].procState = procState;
4679 procStateChange = true;
4680 }
4681 }
4682
4683 if (procStateChange) {
4684 sp<CameraService> service = mService.promote();
4685 if (service != nullptr) {
4686 service->notifyMonitoredUids();
4687 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004688 }
4689}
4690
Austin Borgerdddb7552023-03-30 17:53:01 -07004691/**
4692 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4693 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4694 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4695 * monitoredUids. If it is revised above some other monitoredUid, signal
4696 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4697 * foreground apps in split screen - state changes will capture all other cases.
4698 */
4699void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4700 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004701 {
4702 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004703 auto it = mMonitoredUids.find(uid);
4704
4705 if (it != mMonitoredUids.end()) {
4706 if (it->second.hasCamera) {
4707 for (auto &monitoredUid : mMonitoredUids) {
4708 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004709 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004710 notifyUidSet.emplace(monitoredUid.first);
4711 }
4712 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004713 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004714 notifyUidSet.emplace(uid);
4715 } else {
4716 for (auto &monitoredUid : mMonitoredUids) {
4717 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004718 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004719 notifyUidSet.emplace(uid);
4720 }
4721 }
4722 }
4723 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004724 }
4725 }
4726
Austin Borgerdddb7552023-03-30 17:53:01 -07004727 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004728 sp<CameraService> service = mService.promote();
4729 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004730 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004731 }
4732 }
4733}
4734
Austin Borgerdddb7552023-03-30 17:53:01 -07004735/**
4736 * Register a uid for monitoring, and note whether it owns a camera.
4737 */
4738void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004739 Mutex::Autolock _l(mUidLock);
4740 auto it = mMonitoredUids.find(uid);
4741 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004742 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004743 } else {
Austin Borger65577682022-02-17 00:25:43 +00004744 MonitoredUid monitoredUid;
4745 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004746 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004747 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004748 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004749 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004750 if (res != OK) {
4751 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4752 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004753 }
4754
4755 if (openCamera) {
4756 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004757 }
4758}
4759
Austin Borgerdddb7552023-03-30 17:53:01 -07004760/**
4761 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4762 */
4763void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004764 Mutex::Autolock _l(mUidLock);
4765 auto it = mMonitoredUids.find(uid);
4766 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004767 it->second.refCount--;
4768 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004769 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004770 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004771 if (res != OK) {
4772 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4773 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004774 } else if (closeCamera) {
4775 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004776 }
4777 } else {
4778 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4779 }
4780}
4781
Austin Borgered99f642023-06-01 16:51:35 -07004782bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004783 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004784 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004785}
4786
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004787static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4788static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004789
Austin Borgered99f642023-06-01 16:51:35 -07004790bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004791 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004792 // If activity manager is unreachable, assume everything is active
4793 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004794 return true;
4795 }
4796 auto it = mOverrideUids.find(uid);
4797 if (it != mOverrideUids.end()) {
4798 return it->second;
4799 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004800 bool active = mActiveUids.find(uid) != mActiveUids.end();
4801 if (!active) {
4802 // We want active UIDs to always access camera with their first attempt since
4803 // there is no guarantee the app is robustly written and would retry getting
4804 // the camera on failure. The inverse case is not a problem as we would take
4805 // camera away soon once we get the callback that the uid is no longer active.
4806 ActivityManager am;
4807 // Okay to access with a lock held as UID changes are dispatched without
4808 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004809 int64_t startTimeMillis = 0;
4810 do {
4811 // TODO: Fix this b/109950150!
4812 // Okay this is a hack. There is a race between the UID turning active and
4813 // activity being resumed. The proper fix is very risky, so we temporary add
4814 // some polling which should happen pretty rarely anyway as the race is hard
4815 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004816 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004817 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004818 if (active) {
4819 break;
4820 }
4821 if (startTimeMillis <= 0) {
4822 startTimeMillis = uptimeMillis();
4823 }
4824 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004825 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004826 if (remainingTimeMillis <= 0) {
4827 break;
4828 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004829 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4830
4831 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004832 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004833 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004834 } while (true);
4835
Svet Ganov7b4ab782018-03-25 12:48:10 -07004836 if (active) {
4837 // Now that we found out the UID is actually active, cache that
4838 mActiveUids.insert(uid);
4839 }
4840 }
4841 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004842}
4843
Varun Shahb42f1eb2019-04-16 14:45:13 -07004844int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4845 Mutex::Autolock _l(mUidLock);
4846 return getProcStateLocked(uid);
4847}
4848
4849int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4850 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4851 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004852 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004853 }
4854 return procState;
4855}
4856
Austin Borgered99f642023-06-01 16:51:35 -07004857void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4858 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004859 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004860}
4861
Austin Borgered99f642023-06-01 16:51:35 -07004862void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004863 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004864}
4865
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004866void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4867 Mutex::Autolock _l(mUidLock);
4868 ALOGV("UidPolicy: ActivityManager has died");
4869 mRegistered = false;
4870 mActiveUids.clear();
4871}
4872
Austin Borgered99f642023-06-01 16:51:35 -07004873void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004874 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004875 bool wasActive = false;
4876 bool isActive = false;
4877 {
4878 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004879 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004880 mOverrideUids.erase(uid);
4881 if (insert) {
4882 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4883 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004884 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004885 }
4886 if (wasActive != isActive && !isActive) {
4887 sp<CameraService> service = mService.promote();
4888 if (service != nullptr) {
4889 service->blockClientsForUid(uid);
4890 }
4891 }
4892}
4893
4894// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004895// SensorPrivacyPolicy
4896// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004897
4898void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4899{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004900 Mutex::Autolock _l(mSensorPrivacyLock);
4901 if (mRegistered) {
4902 return;
4903 }
Evan Severson09ab4002021-02-10 14:15:19 -08004904 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004905 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004906 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004907 mSpm.addToggleSensorPrivacyListener(this);
4908 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004909 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004910 if (flags::camera_privacy_allowlist()) {
4911 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
4912 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
4913 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4914 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004915 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004916 if (res == OK) {
4917 mRegistered = true;
4918 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4919 }
4920}
4921
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004922void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4923 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004924 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004925 return;
4926 }
4927
4928 registerWithSensorPrivacyManager();
4929}
4930
4931void CameraService::SensorPrivacyPolicy::registerSelf() {
4932 // Use checkservice to see if the sensor_privacy service is available
4933 // If service is not available then register for notification
4934 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004935 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004936 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004937 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004938 } else {
4939 registerWithSensorPrivacyManager();
4940 }
4941}
4942
Michael Grooverd1d435a2018-12-18 17:39:42 -08004943void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4944 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004945 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004946 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004947 mSpm.removeToggleSensorPrivacyListener(this);
4948 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004949 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004950 mRegistered = false;
4951 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4952}
4953
4954bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004955 if (!mRegistered) {
4956 registerWithSensorPrivacyManager();
4957 }
4958
Michael Grooverd1d435a2018-12-18 17:39:42 -08004959 Mutex::Autolock _l(mSensorPrivacyLock);
4960 return mSensorPrivacyEnabled;
4961}
4962
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004963int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
4964 if (!mRegistered) {
4965 registerWithSensorPrivacyManager();
4966 }
4967
4968 Mutex::Autolock _l(mSensorPrivacyLock);
4969 return mCameraPrivacyState;
4970}
4971
Evan Seversond0b69922022-01-27 10:47:34 -08004972bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004973 if (!hasCameraPrivacyFeature()) {
4974 return false;
4975 }
Evan Seversond0b69922022-01-27 10:47:34 -08004976 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004977}
4978
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004979bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
4980 if (!hasCameraPrivacyFeature()) {
Jyoti Bhayana5882b032024-04-26 11:18:58 -07004981 return false;
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004982 }
4983 return mSpm.isCameraPrivacyEnabled(packageName);
4984}
4985
Evan Seversond0b69922022-01-27 10:47:34 -08004986binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004987 int toggleType, int sensor, bool enabled) {
4988 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
4989 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
4990 {
4991 Mutex::Autolock _l(mSensorPrivacyLock);
4992 mSensorPrivacyEnabled = enabled;
4993 }
4994 // if sensor privacy is enabled then block all clients from accessing the camera
4995 if (enabled) {
4996 sp<CameraService> service = mService.promote();
4997 if (service != nullptr) {
4998 service->blockAllClients();
4999 }
5000 }
5001 }
5002 return binder::Status::ok();
5003}
5004
5005binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
5006 int, int sensor, int state) {
5007 if (!flags::camera_privacy_allowlist()
5008 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
5009 return binder::Status::ok();
5010 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08005011 {
5012 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005013 mCameraPrivacyState = state;
5014 }
5015 sp<CameraService> service = mService.promote();
5016 if (!service) {
5017 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005018 }
5019 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005020 if (state == SensorPrivacyManager::ENABLED) {
5021 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08005022 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005023 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005024 }
5025 return binder::Status::ok();
5026}
5027
5028void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
5029 Mutex::Autolock _l(mSensorPrivacyLock);
5030 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
5031 mRegistered = false;
5032}
5033
Evan Severson09ab4002021-02-10 14:15:19 -08005034bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08005035 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
5036 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5037 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
5038 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5039 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08005040}
5041
Michael Grooverd1d435a2018-12-18 17:39:42 -08005042// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005043// CameraState
5044// ----------------------------------------------------------------------------
5045
Austin Borgered99f642023-06-01 16:51:35 -07005046CameraService::CameraState::CameraState(const std::string& id, int cost,
5047 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005048 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005049 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005050 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005051
5052CameraService::CameraState::~CameraState() {}
5053
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005054CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005055 Mutex::Autolock lock(mStatusLock);
5056 return mStatus;
5057}
5058
Austin Borgered99f642023-06-01 16:51:35 -07005059std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005060 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005061 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005062 return res;
5063}
5064
Ruben Brunkcc776712015-02-17 20:18:47 -08005065CameraParameters CameraService::CameraState::getShimParams() const {
5066 return mShimParams;
5067}
5068
5069void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5070 mShimParams = params;
5071}
5072
5073int CameraService::CameraState::getCost() const {
5074 return mCost;
5075}
5076
Austin Borgered99f642023-06-01 16:51:35 -07005077std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005078 return mConflicting;
5079}
5080
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005081SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5082 return mSystemCameraKind;
5083}
5084
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005085bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5086 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5087 != mPhysicalCameras.end();
5088}
5089
Austin Borgered99f642023-06-01 16:51:35 -07005090bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005091 Mutex::Autolock lock(mStatusLock);
5092 auto result = mUnavailablePhysicalIds.insert(physicalId);
5093 return result.second;
5094}
5095
Austin Borgered99f642023-06-01 16:51:35 -07005096bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005097 Mutex::Autolock lock(mStatusLock);
5098 auto count = mUnavailablePhysicalIds.erase(physicalId);
5099 return count > 0;
5100}
5101
Austin Borgered99f642023-06-01 16:51:35 -07005102void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005103 Mutex::Autolock lock(mStatusLock);
5104 mClientPackage = clientPackage;
5105}
5106
Austin Borgered99f642023-06-01 16:51:35 -07005107std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005108 Mutex::Autolock lock(mStatusLock);
5109 return mClientPackage;
5110}
5111
Ruben Brunkcc776712015-02-17 20:18:47 -08005112// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005113// ClientEventListener
5114// ----------------------------------------------------------------------------
5115
5116void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005117 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005118 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005119 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005120 if (basicClient.get() != nullptr) {
5121 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005122 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005123 static_cast<int>(basicClient->getClientUid()));
5124 }
5125}
5126
5127void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005128 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005129 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005130 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005131 if (basicClient.get() != nullptr) {
5132 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005133 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005134 static_cast<int>(basicClient->getClientUid()));
5135 }
5136}
5137
Ruben Brunk99e69712015-05-26 17:25:07 -07005138// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005139// CameraClientManager
5140// ----------------------------------------------------------------------------
5141
Ruben Brunk99e69712015-05-26 17:25:07 -07005142CameraService::CameraClientManager::CameraClientManager() {
5143 setListener(std::make_shared<ClientEventListener>());
5144}
5145
Ruben Brunkcc776712015-02-17 20:18:47 -08005146CameraService::CameraClientManager::~CameraClientManager() {}
5147
5148sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005149 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005150 auto descriptor = get(id);
5151 if (descriptor == nullptr) {
5152 return sp<BasicClient>{nullptr};
5153 }
5154 return descriptor->getValue();
5155}
5156
Austin Borgered99f642023-06-01 16:51:35 -07005157std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005158 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005159 std::ostringstream ret;
5160 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005161 bool hasAny = false;
5162 for (auto& i : all) {
5163 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005164 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005165 int32_t cost = i->getCost();
5166 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005167 int32_t score = i->getPriority().getScore();
5168 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005169 auto conflicting = i->getConflicting();
5170 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005171 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005172 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005173 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005174 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005175 uid_t clientUid = clientSp->getClientUid();
5176 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005177 }
Austin Borgered99f642023-06-01 16:51:35 -07005178 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5179 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005180
Ruben Brunk6267b532015-04-30 17:44:07 -07005181 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005182 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005183 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005184 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005185 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005186 }
5187
Austin Borgered99f642023-06-01 16:51:35 -07005188 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005189 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005190 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005191 }
Austin Borgered99f642023-06-01 16:51:35 -07005192 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005193 }
Austin Borgered99f642023-06-01 16:51:35 -07005194 if (hasAny) ret << "\n";
5195 ret << "]\n";
5196 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005197}
5198
5199CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005200 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5201 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005202 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005203
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005204 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005205 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005206
Austin Borgered99f642023-06-01 16:51:35 -07005207 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005208 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5209 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005210}
5211
5212CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005213 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005214 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005215 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005216 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005217 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5218 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005219}
5220
5221// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005222// InjectionStatusListener
5223// ----------------------------------------------------------------------------
5224
5225void CameraService::InjectionStatusListener::addListener(
5226 const sp<ICameraInjectionCallback>& callback) {
5227 Mutex::Autolock lock(mListenerLock);
5228 if (mCameraInjectionCallback) return;
5229 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5230 if (res == OK) {
5231 mCameraInjectionCallback = callback;
5232 }
5233}
5234
5235void CameraService::InjectionStatusListener::removeListener() {
5236 Mutex::Autolock lock(mListenerLock);
5237 if (mCameraInjectionCallback == nullptr) {
5238 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5239 return;
5240 }
5241 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5242 mCameraInjectionCallback = nullptr;
5243}
5244
5245void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005246 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005247 if (mCameraInjectionCallback == nullptr) {
5248 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5249 return;
5250 }
Cliff Wud3a05312021-04-26 23:07:31 +08005251
5252 switch (err) {
5253 case -ENODEV:
5254 mCameraInjectionCallback->onInjectionError(
5255 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5256 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005257 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005258 break;
5259 case -EBUSY:
5260 mCameraInjectionCallback->onInjectionError(
5261 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5262 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005263 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005264 break;
5265 case DEAD_OBJECT:
5266 mCameraInjectionCallback->onInjectionError(
5267 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5268 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005269 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005270 break;
5271 case INVALID_OPERATION:
5272 mCameraInjectionCallback->onInjectionError(
5273 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5274 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005275 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005276 break;
5277 case UNKNOWN_TRANSACTION:
5278 mCameraInjectionCallback->onInjectionError(
5279 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5280 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005281 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005282 break;
5283 default:
5284 mCameraInjectionCallback->onInjectionError(
5285 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5286 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005287 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005288 }
Cliff Wud8cae102021-03-11 01:37:42 +08005289}
5290
5291void CameraService::InjectionStatusListener::binderDied(
5292 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005293 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5294 auto parent = mParent.promote();
5295 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005296 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5297 if (clientDescriptor != nullptr) {
5298 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5299 baseClientPtr->stopInjection();
5300 }
Cliff Wu3b268182021-07-06 15:44:43 +08005301 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005302 }
5303}
5304
5305// ----------------------------------------------------------------------------
5306// CameraInjectionSession
5307// ----------------------------------------------------------------------------
5308
5309binder::Status CameraService::CameraInjectionSession::stopInjection() {
5310 Mutex::Autolock lock(mInjectionSessionLock);
5311 auto parent = mParent.promote();
5312 if (parent == nullptr) {
5313 ALOGE("CameraInjectionSession: Parent is gone");
5314 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5315 "Camera service encountered error");
5316 }
Cliff Wud3a05312021-04-26 23:07:31 +08005317
5318 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005319 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5320 if (clientDescriptor != nullptr) {
5321 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5322 res = baseClientPtr->stopInjection();
5323 if (res != OK) {
5324 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5325 " ret != NO_ERROR: %d", res);
5326 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5327 "Camera session encountered error");
5328 }
5329 }
Cliff Wu3b268182021-07-06 15:44:43 +08005330 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005331 return binder::Status::ok();
5332}
5333
5334// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005335
5336static const int kDumpLockRetries = 50;
5337static const int kDumpLockSleep = 60000;
5338
5339static bool tryLock(Mutex& mutex)
5340{
5341 bool locked = false;
5342 for (int i = 0; i < kDumpLockRetries; ++i) {
5343 if (mutex.tryLock() == NO_ERROR) {
5344 locked = true;
5345 break;
5346 }
5347 usleep(kDumpLockSleep);
5348 }
5349 return locked;
5350}
5351
Rucha Katakwardf223072021-06-15 10:21:00 -07005352void CameraService::cacheDump() {
5353 if (mMemFd != -1) {
5354 const Vector<String16> args;
5355 ATRACE_CALL();
5356 // Acquiring service lock here will avoid the deadlock since
5357 // cacheDump will not be called during the second disconnect.
5358 Mutex::Autolock lock(mServiceLock);
5359
5360 Mutex::Autolock l(mCameraStatesLock);
5361 // Start collecting the info for open sessions and store it in temp file.
5362 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005363 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005364 auto clientDescriptor = mActiveClientManager.get(cameraId);
5365 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005366 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005367 // Log the current open session info before device is disconnected.
5368 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5369 }
5370 }
5371 }
5372}
5373
Mathias Agopian65ab4712010-07-14 17:59:35 -07005374status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005375 ATRACE_CALL();
5376
Austin Borgered99f642023-06-01 16:51:35 -07005377 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005378 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005379 getCallingPid(),
5380 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005381 return NO_ERROR;
5382 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005383 bool locked = tryLock(mServiceLock);
5384 // failed to lock - CameraService is probably deadlocked
5385 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005386 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005387 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005388
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005389 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005390 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005391
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005392 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005393 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005394
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005395 if (locked) mServiceLock.unlock();
5396 return NO_ERROR;
5397 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005398 dprintf(fd, "\n== Service global info: ==\n\n");
5399 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005400 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005401 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5402 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005403 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5404 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5405 }
Austin Borgered99f642023-06-01 16:51:35 -07005406 std::string activeClientString = mActiveClientManager.toString();
5407 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5408 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005409 if (mStreamUseCaseOverrides.size() > 0) {
5410 dprintf(fd, "Active stream use case overrides:");
5411 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5412 dprintf(fd, " %" PRId64, useCaseOverride);
5413 }
5414 dprintf(fd, "\n");
5415 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005416
5417 dumpEventLog(fd);
5418
5419 bool stateLocked = tryLock(mCameraStatesLock);
5420 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005421 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005422 }
5423
Emilian Peevbd8c5032018-02-14 23:05:40 +00005424 int argSize = args.size();
5425 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005426 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005427 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005428 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005429 }
5430 break;
5431 }
5432 }
5433
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005434 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005435 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005436
Austin Borgered99f642023-06-01 16:51:35 -07005437 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005438
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005439 CameraParameters p = state.second->getShimParams();
5440 if (!p.isEmpty()) {
5441 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5442 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005443 }
5444
5445 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005446 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005447 // log the current open session info
5448 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005449 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005450 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005451 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005452
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005453 }
5454
5455 if (stateLocked) mCameraStatesLock.unlock();
5456
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005457 if (locked) mServiceLock.unlock();
5458
Emilian Peevf53f66e2017-04-11 14:29:43 +01005459 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005460
5461 dprintf(fd, "\n== Vendor tags: ==\n\n");
5462
5463 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5464 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005465 sp<VendorTagDescriptorCache> cache =
5466 VendorTagDescriptorCache::getGlobalVendorTagCache();
5467 if (cache == NULL) {
5468 dprintf(fd, "No vendor tags.\n");
5469 } else {
5470 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5471 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005472 } else {
5473 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5474 }
5475
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005476 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005477 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005478 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005479
5480 // Process dump arguments, if any
5481 int n = args.size();
5482 String16 verboseOption("-v");
5483 String16 unreachableOption("--unreachable");
5484 for (int i = 0; i < n; i++) {
5485 if (args[i] == verboseOption) {
5486 // change logging level
5487 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005488 std::string levelStr = toStdString(args[i+1]);
5489 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005490 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005491 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005492 } else if (args[i] == unreachableOption) {
5493 // Dump memory analysis
5494 // TODO - should limit be an argument parameter?
5495 UnreachableMemoryInfo info;
5496 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5497 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005498 dprintf(fd, "\n== Unable to dump unreachable memory. "
5499 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005500 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005501 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005502 std::string s = info.ToString(/*log_contents*/ true);
5503 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005504 }
5505 }
5506 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005507
5508 bool serviceLocked = tryLock(mServiceLock);
5509
5510 // Dump info from previous open sessions.
5511 // Reposition the offset to beginning of the file before reading
5512
5513 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5514 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5515 ssize_t size_read;
5516 char buf[4096];
5517 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5518 // Read data from file to a small buffer and write it to fd.
5519 write(fd, buf, size_read);
5520 if (size_read == -1) {
5521 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5522 break;
5523 }
5524 }
5525 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5526 } else {
5527 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5528 }
5529
5530 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005531 return NO_ERROR;
5532}
5533
Rucha Katakwardf223072021-06-15 10:21:00 -07005534void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005535 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005536 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005537 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005538 getFormattedCurrentTime().c_str(),
5539 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005540 dprintf(fd, " Client priority score: %d state: %d\n",
5541 clientDescriptor->getPriority().getScore(),
5542 clientDescriptor->getPriority().getState());
5543 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5544
5545 auto client = clientDescriptor->getValue();
5546 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005547 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005548
5549 client->dumpClient(fd, args);
5550}
5551
Austin Borgered99f642023-06-01 16:51:35 -07005552void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005553 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005554 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005555}
5556
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005557void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005558 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005559
5560 Mutex::Autolock l(mLogLock);
5561 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005562 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005563 }
5564
5565 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005566 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005567 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005568 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005569 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005570 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005571}
5572
Austin Borgered99f642023-06-01 16:51:35 -07005573void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005574 Mutex::Autolock lock(mLogLock);
5575 if (!isClientWatchedLocked(client)) { return; }
5576
5577 std::vector<std::string> dumpVector;
5578 client->dumpWatchedEventsToVector(dumpVector);
5579
5580 if (dumpVector.empty()) { return; }
5581
Austin Borgered99f642023-06-01 16:51:35 -07005582 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005583
Austin Borgered99f642023-06-01 16:51:35 -07005584 std::string currentTime = getFormattedCurrentTime();
5585 dumpString << "Cached @ ";
5586 dumpString << currentTime;
5587 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005588
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005589 size_t i = dumpVector.size();
5590
5591 // Store the string in reverse order (latest last)
5592 while (i > 0) {
5593 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005594 dumpString << cameraId;
5595 dumpString << ":";
5596 dumpString << client->getPackageName();
5597 dumpString << " ";
5598 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005599 }
5600
Austin Borgered99f642023-06-01 16:51:35 -07005601 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005602}
5603
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005604void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005605 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005606 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5607 if (mTorchClientMap[i] == who) {
5608 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005609 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005610 status_t res = mFlashlight->setTorchMode(cameraId, false);
5611 if (res) {
5612 ALOGE("%s: torch client died but couldn't turn off torch: "
5613 "%s (%d)", __FUNCTION__, strerror(-res), res);
5614 return;
5615 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005616 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005617 break;
5618 }
5619 }
5620}
5621
Ruben Brunkcc776712015-02-17 20:18:47 -08005622/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005623
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005624 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005625 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5626 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005627 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005628 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005629 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005630
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005631 // check torch client
5632 handleTorchClientBinderDied(who);
5633
5634 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005635 if(!evictClientIdByRemote(who)) {
5636 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005637 return;
5638 }
5639
Ruben Brunkcc776712015-02-17 20:18:47 -08005640 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5641 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005642}
5643
Austin Borgered99f642023-06-01 16:51:35 -07005644void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005645 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005646}
5647
Austin Borgered99f642023-06-01 16:51:35 -07005648void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005649 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005650 // Do not lock mServiceLock here or can get into a deadlock from
5651 // connect() -> disconnect -> updateStatus
5652
5653 auto state = getCameraState(cameraId);
5654
5655 if (state == nullptr) {
5656 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005657 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005658 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005659 }
5660
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005661 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5662 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5663 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005664 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005665 return;
5666 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005667
Biswarup Pal37a75182024-01-16 15:53:35 +00005668 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5669 CameraMetadata cameraInfo;
5670 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00005671 cameraId, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +00005672 if (res != OK) {
5673 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5674 __FUNCTION__, cameraId.c_str());
5675 } else {
5676 int32_t deviceId = getDeviceId(cameraInfo);
5677 if (deviceId != kDefaultDeviceId) {
5678 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5679 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5680 static_cast<camera_metadata_enum_android_lens_facing_t>(
5681 lensFacingEntry.data.u8[0]);
5682 std::string mappedCameraId;
5683 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5684 mappedCameraId = kVirtualDeviceBackCameraId;
5685 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5686 mappedCameraId = kVirtualDeviceFrontCameraId;
5687 } else {
5688 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5689 __func__);
5690 }
5691 if (!mappedCameraId.empty()) {
5692 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5693 }
5694 }
5695 }
5696 }
5697
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005698 // Collect the logical cameras without holding mStatusLock in updateStatus
5699 // as that can lead to a deadlock(b/162192331).
5700 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005701 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005702 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005703 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005704 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005705 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005706 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5707 auto [deviceId, mappedCameraId] =
5708 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005709
Biswarup Pal37a75182024-01-16 15:53:35 +00005710 if (status != StatusInternal::ENUMERATING) {
5711 // Update torch status if it has a flash unit.
5712 Mutex::Autolock al(mTorchStatusMutex);
5713 TorchModeStatus torchStatus;
5714 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5715 NAME_NOT_FOUND) {
5716 TorchModeStatus newTorchStatus =
5717 status == StatusInternal::PRESENT ?
5718 TorchModeStatus::AVAILABLE_OFF :
5719 TorchModeStatus::NOT_AVAILABLE;
5720 if (torchStatus != newTorchStatus) {
5721 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5722 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005723 }
5724 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005725
Biswarup Pal37a75182024-01-16 15:53:35 +00005726 Mutex::Autolock lock(mStatusListenerLock);
5727 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5728 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005729
Biswarup Pal37a75182024-01-16 15:53:35 +00005730 for (auto& listener : mListenerList) {
5731 bool isVendorListener = listener->isVendorListener();
5732 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5733 listener->getListenerPid(), listener->getListenerUid())) {
5734 ALOGV("Skipping discovery callback for system-only camera device %s",
5735 cameraId.c_str());
5736 continue;
5737 }
5738
5739 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5740 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005741 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005742 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005743 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5744 ret.exceptionCode());
5745 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005746 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005747}
5748
Austin Borgered99f642023-06-01 16:51:35 -07005749void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5750 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005751 auto state = getCameraState(cameraId);
5752 if (state == nullptr) {
5753 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005754 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005755 return;
5756 }
5757 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005758 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005759 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005760 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005761 }
5762
Biswarup Pal37a75182024-01-16 15:53:35 +00005763 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5764 auto [deviceId, mappedCameraId] =
5765 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5766
Shuzhen Wang695044d2020-03-06 09:02:23 -08005767 Mutex::Autolock lock(mStatusListenerLock);
5768
5769 for (const auto& it : mListenerList) {
5770 if (!it->isOpenCloseCallbackAllowed()) {
5771 continue;
5772 }
5773
5774 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005775 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005776 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5777 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005778 } else {
Biswarup Pal37a75182024-01-16 15:53:35 +00005779 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005780 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005781
5782 it->handleBinderStatus(ret,
5783 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5784 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005785 }
5786}
5787
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005788template<class Func>
5789void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005790 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005791 std::initializer_list<StatusInternal> rejectSourceStates,
5792 Func onStatusUpdatedLocked) {
5793 Mutex::Autolock lock(mStatusLock);
5794 StatusInternal oldStatus = mStatus;
5795 mStatus = status;
5796
5797 if (oldStatus == status) {
5798 return;
5799 }
5800
5801 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07005802 cameraId.c_str(), eToI(oldStatus), eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005803
5804 if (oldStatus == StatusInternal::NOT_PRESENT &&
5805 (status != StatusInternal::PRESENT &&
5806 status != StatusInternal::ENUMERATING)) {
5807
5808 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5809 __FUNCTION__);
5810 mStatus = oldStatus;
5811 return;
5812 }
5813
5814 /**
5815 * Sometimes we want to conditionally do a transition.
5816 * For example if a client disconnects, we want to go to PRESENT
5817 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5818 */
5819 for (auto& rejectStatus : rejectSourceStates) {
5820 if (oldStatus == rejectStatus) {
5821 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005822 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005823 mStatus = oldStatus;
5824 return;
5825 }
5826 }
5827
5828 onStatusUpdatedLocked(cameraId, status);
5829}
5830
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005831status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005832 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005833 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005834 if (!status) {
5835 return BAD_VALUE;
5836 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005837 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5838 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005839 // invalid camera ID or the camera doesn't have a flash unit
5840 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005841 }
5842
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005843 *status = mTorchStatusMap.valueAt(index);
5844 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005845}
5846
Austin Borgered99f642023-06-01 16:51:35 -07005847status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005848 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005849 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5850 if (index == NAME_NOT_FOUND) {
5851 return BAD_VALUE;
5852 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005853 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005854
5855 return OK;
5856}
5857
Austin Borgered99f642023-06-01 16:51:35 -07005858std::list<std::string> CameraService::getLogicalCameras(
5859 const std::string& physicalCameraId) {
5860 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005861 Mutex::Autolock lock(mCameraStatesLock);
5862 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005863 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5864 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005865 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005866 }
5867 return retList;
5868}
5869
5870void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005871 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00005872 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005873 // mStatusListenerLock is expected to be locked
5874 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005875 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005876 // Note: we check only the deviceKind of the physical camera id
5877 // since, logical camera ids and their physical camera ids are
5878 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005879 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5880 listener->getListenerPid(), listener->getListenerUid())) {
5881 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005882 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005883 continue;
5884 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005885 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00005886 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005887 listener->handleBinderStatus(ret,
5888 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5889 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5890 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005891 }
5892 }
5893}
5894
Svet Ganova453d0d2018-01-11 15:37:58 -08005895void CameraService::blockClientsForUid(uid_t uid) {
5896 const auto clients = mActiveClientManager.getAll();
5897 for (auto& current : clients) {
5898 if (current != nullptr) {
5899 const auto basicClient = current->getValue();
5900 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5901 basicClient->block();
5902 }
5903 }
5904 }
5905}
5906
Michael Grooverd1d435a2018-12-18 17:39:42 -08005907void CameraService::blockAllClients() {
5908 const auto clients = mActiveClientManager.getAll();
5909 for (auto& current : clients) {
5910 if (current != nullptr) {
5911 const auto basicClient = current->getValue();
5912 if (basicClient.get() != nullptr) {
5913 basicClient->block();
5914 }
5915 }
5916 }
5917}
5918
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005919void CameraService::blockPrivacyEnabledClients() {
5920 const auto clients = mActiveClientManager.getAll();
5921 for (auto& current : clients) {
5922 if (current != nullptr) {
5923 const auto basicClient = current->getValue();
5924 if (basicClient.get() != nullptr) {
5925 std::string pkgName = basicClient->getPackageName();
5926 bool cameraPrivacyEnabled =
5927 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
5928 if (cameraPrivacyEnabled) {
5929 basicClient->block();
5930 }
5931 }
5932 }
5933 }
5934}
5935
Svet Ganova453d0d2018-01-11 15:37:58 -08005936// NOTE: This is a remote API - make sure all args are validated
5937status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005938 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005939 return PERMISSION_DENIED;
5940 }
5941 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5942 return BAD_VALUE;
5943 }
Austin Borgered99f642023-06-01 16:51:35 -07005944 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005945 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005946 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005947 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005948 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005949 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005950 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005951 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005952 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005953 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005954 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005955 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005956 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005957 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005958 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005959 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005960 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005961 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005962 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005963 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005964 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005965 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005966 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005967 handleClearStreamUseCaseOverrides();
5968 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005969 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005970 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07005971 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005972 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07005973 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00005974 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07005975 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005976 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005977 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005978 }
5979 printHelp(err);
5980 return BAD_VALUE;
5981}
5982
5983status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005984 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005985
Svet Ganova453d0d2018-01-11 15:37:58 -08005986 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07005987 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005988 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07005989 } else if ((args[2] != toString16("idle"))) {
5990 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08005991 return BAD_VALUE;
5992 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005993
5994 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005995 if (args.size() >= 5 && args[3] == toString16("--user")) {
5996 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005997 }
5998
5999 uid_t uid;
6000 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
6001 return BAD_VALUE;
6002 }
6003
6004 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08006005 return NO_ERROR;
6006}
6007
6008status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006009 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006010
6011 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006012 if (args.size() >= 4 && args[2] == toString16("--user")) {
6013 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006014 }
6015
6016 uid_t uid;
6017 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006018 return BAD_VALUE;
6019 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006020
6021 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08006022 return NO_ERROR;
6023}
6024
6025status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006026 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006027
6028 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006029 if (args.size() >= 4 && args[2] == toString16("--user")) {
6030 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006031 }
6032
6033 uid_t uid;
6034 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006035 return BAD_VALUE;
6036 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006037
6038 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006039 return dprintf(out, "active\n");
6040 } else {
6041 return dprintf(out, "idle\n");
6042 }
6043}
6044
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006045status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006046 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006047 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
6048 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
6049 Mutex::Autolock lock(mServiceLock);
6050
6051 mOverrideRotateAndCropMode = rotateValue;
6052
6053 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6054
6055 const auto clients = mActiveClientManager.getAll();
6056 for (auto& current : clients) {
6057 if (current != nullptr) {
6058 const auto basicClient = current->getValue();
6059 if (basicClient.get() != nullptr) {
6060 basicClient->setRotateAndCropOverride(rotateValue);
6061 }
6062 }
6063 }
6064
6065 return OK;
6066}
6067
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006068status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6069 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006070 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006071 if ((*end != '\0') ||
6072 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6073 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6074 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6075 return BAD_VALUE;
6076 }
6077
6078 Mutex::Autolock lock(mServiceLock);
6079 mOverrideAutoframingMode = autoframingValue;
6080
6081 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6082
6083 const auto clients = mActiveClientManager.getAll();
6084 for (auto& current : clients) {
6085 if (current != nullptr) {
6086 const auto basicClient = current->getValue();
6087 if (basicClient.get() != nullptr) {
6088 basicClient->setAutoframingOverride(autoframingValue);
6089 }
6090 }
6091 }
6092
6093 return OK;
6094}
6095
Ravneetaeb20dc2022-03-30 05:33:03 +00006096status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006097 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006098
6099 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6100
6101 Mutex::Autolock lock(mServiceLock);
6102
6103 mCameraServiceWatchdogEnabled = enableWatchdog;
6104
6105 const auto clients = mActiveClientManager.getAll();
6106 for (auto& current : clients) {
6107 if (current != nullptr) {
6108 const auto basicClient = current->getValue();
6109 if (basicClient.get() != nullptr) {
6110 basicClient->setCameraServiceWatchdog(enableWatchdog);
6111 }
6112 }
6113 }
6114
6115 return OK;
6116}
6117
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006118status_t CameraService::handleGetRotateAndCrop(int out) {
6119 Mutex::Autolock lock(mServiceLock);
6120
6121 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6122}
6123
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006124status_t CameraService::handleGetAutoframing(int out) {
6125 Mutex::Autolock lock(mServiceLock);
6126
6127 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6128}
6129
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006130status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6131 char *endPtr;
6132 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006133 std::string maskString = toStdString(args[1]);
6134 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006135
6136 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006137 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006138 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6139
6140 Mutex::Autolock lock(mServiceLock);
6141
6142 mImageDumpMask = maskValue;
6143
6144 return OK;
6145}
6146
6147status_t CameraService::handleGetImageDumpMask(int out) {
6148 Mutex::Autolock lock(mServiceLock);
6149
6150 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6151}
6152
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006153status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006154 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006155 if (errno != 0) return BAD_VALUE;
6156
6157 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6158 Mutex::Autolock lock(mServiceLock);
6159
6160 mOverrideCameraMuteMode = (muteValue == 1);
6161
6162 const auto clients = mActiveClientManager.getAll();
6163 for (auto& current : clients) {
6164 if (current != nullptr) {
6165 const auto basicClient = current->getValue();
6166 if (basicClient.get() != nullptr) {
6167 if (basicClient->supportsCameraMute()) {
6168 basicClient->setCameraMute(mOverrideCameraMuteMode);
6169 }
6170 }
6171 }
6172 }
6173
6174 return OK;
6175}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006176
Shuzhen Wang16610a62022-12-15 22:38:07 -08006177status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6178 std::vector<int64_t> useCasesOverride;
6179 for (size_t i = 1; i < args.size(); i++) {
6180 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006181 std::string arg = toStdString(args[i]);
6182 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006183 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006184 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006185 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006186 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006187 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006188 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006189 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006190 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006191 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006192 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006193 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006194 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006195 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6196 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006197 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006198 return BAD_VALUE;
6199 }
6200 useCasesOverride.push_back(useCase);
6201 }
6202
6203 Mutex::Autolock lock(mServiceLock);
6204 mStreamUseCaseOverrides = std::move(useCasesOverride);
6205
6206 return OK;
6207}
6208
6209void CameraService::handleClearStreamUseCaseOverrides() {
6210 Mutex::Autolock lock(mServiceLock);
6211 mStreamUseCaseOverrides.clear();
6212}
6213
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006214status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6215 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006216 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006217 if ((*end != '\0') ||
6218 (zoomOverrideValue != -1 &&
6219 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6220 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6221 return BAD_VALUE;
6222 }
6223
6224 Mutex::Autolock lock(mServiceLock);
6225 mZoomOverrideValue = zoomOverrideValue;
6226
6227 const auto clients = mActiveClientManager.getAll();
6228 for (auto& current : clients) {
6229 if (current != nullptr) {
6230 const auto basicClient = current->getValue();
6231 if (basicClient.get() != nullptr) {
6232 if (basicClient->supportsZoomOverride()) {
6233 basicClient->setZoomOverride(mZoomOverrideValue);
6234 }
6235 }
6236 }
6237 }
6238
6239 return OK;
6240}
6241
Avichal Rakesh84147132021-11-11 17:47:11 -08006242status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006243 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006244 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006245 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006246 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006247 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006248 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006249 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006250 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006251 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006252 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006253 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006254 dprintf(outFd, "Camera service watch commands:\n"
6255 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6256 " starts watching the provided tags for clients with provided package\n"
6257 " recognizes tag shorthands like '3a'\n"
6258 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006259 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006260 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006261 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006262 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006263 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006264 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006265 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006266}
6267
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006268status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6269 Mutex::Autolock lock(mLogLock);
6270 size_t tagsIdx; // index of '-m'
6271 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006272 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006273 if (tagsIdx < args.size() - 1) {
6274 tags = args[tagsIdx + 1];
6275 } else {
6276 dprintf(outFd, "No tags provided.\n");
6277 return BAD_VALUE;
6278 }
6279
6280 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006281 // watch all clients if no clients are provided
6282 String16 clients = toString16(kWatchAllClientsFlag);
6283 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006284 clientsIdx++);
6285 if (clientsIdx < args.size() - 1) {
6286 clients = args[clientsIdx + 1];
6287 }
Austin Borgered99f642023-06-01 16:51:35 -07006288 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006289
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006290 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006291 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006292
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006293 bool serviceLock = tryLock(mServiceLock);
6294 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006295 auto cameraClients = mActiveClientManager.getAll();
6296 for (const auto &clientDescriptor: cameraClients) {
6297 if (clientDescriptor == nullptr) { continue; }
6298 sp<BasicClient> client = clientDescriptor->getValue();
6299 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006300
6301 if (isClientWatchedLocked(client.get())) {
6302 client->startWatchingTags(mMonitorTags, outFd);
6303 numWatchedClients++;
6304 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006305 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006306 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6307
6308 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006309 return OK;
6310}
6311
6312status_t CameraService::stopWatchingTags(int outFd) {
6313 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006314 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006315 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006316
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006317 mWatchedClientPackages.clear();
6318 mWatchedClientsDumpCache.clear();
6319
6320 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006321 auto cameraClients = mActiveClientManager.getAll();
6322 for (const auto &clientDescriptor : cameraClients) {
6323 if (clientDescriptor == nullptr) { continue; }
6324 sp<BasicClient> client = clientDescriptor->getValue();
6325 if (client.get() == nullptr) { continue; }
6326 client->stopWatchingTags(outFd);
6327 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006328 dprintf(outFd, "Stopped watching all clients.\n");
6329 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006330 return OK;
6331}
6332
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006333status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6334 Mutex::Autolock lock(mLogLock);
6335 size_t clearedSize = mWatchedClientsDumpCache.size();
6336 mWatchedClientsDumpCache.clear();
6337 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6338 return OK;
6339}
6340
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006341status_t CameraService::printWatchedTags(int outFd) {
6342 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006343 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006344
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006345 bool printedSomething = false; // tracks if any monitoring information was printed
6346 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006347
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006348 bool serviceLock = tryLock(mServiceLock);
6349 // get all watched clients that are currently connected
6350 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6351 if (clientDescriptor == nullptr) { continue; }
6352
6353 sp<BasicClient> client = clientDescriptor->getValue();
6354 if (client.get() == nullptr) { continue; }
6355 if (!isClientWatchedLocked(client.get())) { continue; }
6356
6357 std::vector<std::string> dumpVector;
6358 client->dumpWatchedEventsToVector(dumpVector);
6359
6360 size_t printIdx = dumpVector.size();
6361 if (printIdx == 0) {
6362 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006363 }
6364
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006365 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006366 const std::string &cameraId = clientDescriptor->getKey();
6367 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006368 while(printIdx > 0) {
6369 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006370 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006371 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006372 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006373 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006374 printedSomething = true;
6375
6376 connectedMonitoredClients.emplace(client->getPackageName());
6377 }
6378 if (serviceLock) { mServiceLock.unlock(); }
6379
6380 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6381 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006382 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006383 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6384 continue;
6385 }
6386
Austin Borgered99f642023-06-01 16:51:35 -07006387 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006388 dprintf(outFd, "%s\n", kv.second.c_str());
6389 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006390 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006391
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006392 if (!printedSomething) {
6393 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006394 }
6395
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006396 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006397}
6398
Avichal Rakesh84147132021-11-11 17:47:11 -08006399// Print all events in vector `events' that came after lastPrintedEvent
6400void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006401 const std::string &cameraId,
6402 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006403 const std::vector<std::string> &events,
6404 const std::string &lastPrintedEvent) {
6405 if (events.empty()) { return; }
6406
6407 // index of lastPrintedEvent in events.
6408 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6409 size_t lastPrintedIdx;
6410 for (lastPrintedIdx = 0;
6411 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6412 lastPrintedIdx++);
6413
6414 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6415
Avichal Rakesh84147132021-11-11 17:47:11 -08006416 // print events in chronological order (latest event last)
6417 size_t idxToPrint = lastPrintedIdx;
6418 do {
6419 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006420 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6421 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006422 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006423}
6424
6425// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6426// command should be interrupted if the user presses the return key, or if user loses any way to
6427// signal interrupt.
6428// If timeoutMs == 0, this function will always return false
6429bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6430 struct timeval startTime;
6431 int startTimeError = gettimeofday(&startTime, nullptr);
6432 if (startTimeError) {
6433 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6434 return true;
6435 }
6436
6437 const nfds_t numFds = 1;
6438 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6439
6440 struct timeval currTime;
6441 char buffer[2];
6442 while(true) {
6443 int currTimeError = gettimeofday(&currTime, nullptr);
6444 if (currTimeError) {
6445 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6446 return true;
6447 }
6448
6449 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6450 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6451 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6452
6453 if (remainingTimeMs <= 0) {
6454 // No user interrupt within timeoutMs, don't interrupt watch command
6455 return false;
6456 }
6457
6458 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6459 if (numFdsUpdated < 0) {
6460 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6461 return true;
6462 }
6463
6464 if (numFdsUpdated == 0) {
6465 // No user input within timeoutMs, don't interrupt watch command
6466 return false;
6467 }
6468
6469 if (!(pollFd.revents & POLLIN)) {
6470 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6471 return true;
6472 }
6473
6474 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6475 if (sizeRead < 0) {
6476 dprintf(outFd, "Error reading user input. Exiting.\n");
6477 return true;
6478 }
6479
6480 if (sizeRead == 0) {
6481 // Reached end of input fd (can happen if input is piped)
6482 // User has no way to signal an interrupt, so interrupt here
6483 return true;
6484 }
6485
6486 if (buffer[0] == '\n') {
6487 // User pressed return, interrupt watch command.
6488 return true;
6489 }
6490 }
6491}
6492
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006493status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6494 int inFd, int outFd) {
6495 // Figure out refresh interval, if present in args
6496 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006497 if (args.size() > 2) {
6498 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006499 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006500 intervalIdx++);
6501
6502 size_t intervalValIdx = intervalIdx + 1;
6503 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006504 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006505 if (errno) { return BAD_VALUE; }
6506 }
6507 }
6508
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006509 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6510 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006511
Avichal Rakesh84147132021-11-11 17:47:11 -08006512 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006513 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006514
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006515 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006516 bool serviceLock = tryLock(mServiceLock);
6517 auto cameraClients = mActiveClientManager.getAll();
6518 if (serviceLock) { mServiceLock.unlock(); }
6519
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006520 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006521 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006522 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006523
6524 sp<BasicClient> client = clientDescriptor->getValue();
6525 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006526 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006527
Austin Borgered99f642023-06-01 16:51:35 -07006528 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006529 // This also initializes the map entries with an empty string
6530 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6531
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006532 std::vector<std::string> latestEvents;
6533 client->dumpWatchedEventsToVector(latestEvents);
6534
6535 if (!latestEvents.empty()) {
6536 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006537 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006538 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006539 latestEvents,
6540 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006541 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006542 }
6543 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006544 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006545 break;
6546 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006547 }
6548 return OK;
6549}
6550
Austin Borgered99f642023-06-01 16:51:35 -07006551void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006552 mWatchedClientPackages.clear();
6553
Austin Borgered99f642023-06-01 16:51:35 -07006554 std::istringstream iss(clients);
6555 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006556
Austin Borgered99f642023-06-01 16:51:35 -07006557 while (std::getline(iss, nextClient, ',')) {
6558 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006559 // Don't need to track any other package if 'all' is present
6560 mWatchedClientPackages.clear();
6561 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6562 break;
6563 }
6564
6565 // track package names
6566 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006567 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006568}
6569
Svet Ganova453d0d2018-01-11 15:37:58 -08006570status_t CameraService::printHelp(int out) {
6571 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006572 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6573 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6574 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006575 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6576 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6577 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006578 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6579 " Valid values 0=false, 1=true, 2=auto\n"
6580 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006581 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6582 " Valid values 0=OFF, 1=ON for JPEG\n"
6583 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006584 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006585 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6586 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6587 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6588 " on. In case the number of usecases is smaller than the number of streams, the\n"
6589 " last use case is assigned to all the remaining streams. In case of multiple\n"
6590 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6591 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6592 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6593 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006594 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6595 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006596 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6597 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006598 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006599 " help print this message\n");
6600}
6601
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006602bool CameraService::isClientWatched(const BasicClient *client) {
6603 Mutex::Autolock lock(mLogLock);
6604 return isClientWatchedLocked(client);
6605}
6606
6607bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6608 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6609 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6610}
6611
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006612int32_t CameraService::updateAudioRestriction() {
6613 Mutex::Autolock lock(mServiceLock);
6614 return updateAudioRestrictionLocked();
6615}
6616
6617int32_t CameraService::updateAudioRestrictionLocked() {
6618 int32_t mode = 0;
6619 // iterate through all active client
6620 for (const auto& i : mActiveClientManager.getAll()) {
6621 const auto clientSp = i->getValue();
6622 mode |= clientSp->getAudioRestriction();
6623 }
6624
6625 bool modeChanged = (mAudioRestriction != mode);
6626 mAudioRestriction = mode;
6627 if (modeChanged) {
6628 mAppOps.setCameraAudioRestriction(mode);
6629 }
6630 return mode;
6631}
6632
Austin Borgered99f642023-06-01 16:51:35 -07006633status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006634 sp<BasicClient> clientSp) {
6635 std::unique_ptr<AutoConditionLock> lock =
6636 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6637 status_t res = NO_ERROR;
6638 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006639 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006640 mInjectionStatusListener->notifyInjectionError(
6641 externalCamId, UNKNOWN_TRANSACTION);
6642 clientSp->notifyError(
6643 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6644 CaptureResultExtras());
6645
6646 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6647 // other clients from connecting in mServiceLockWrapper if held
6648 mServiceLock.unlock();
6649
6650 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006651 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006652 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006653 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006654
6655 // Reacquire mServiceLock
6656 mServiceLock.lock();
6657 }
6658
6659 return res;
6660}
6661
Cliff Wud3a05312021-04-26 23:07:31 +08006662void CameraService::clearInjectionParameters() {
6663 {
6664 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006665 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006666 mInjectionInternalCamId = "";
6667 }
6668 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006669 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006670}
6671
Biswarup Pal37a75182024-01-16 15:53:35 +00006672} // namespace android