blob: 6077e63d67f9f38a6ea14ecffb46e4c939123021 [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
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700831 if (!mInitialized) {
832 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
833 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
834 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
835 }
836
Austin Borger65e64642024-06-11 15:58:23 -0700837 std::optional<std::string> cameraIdOptional =
838 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000839 if (!cameraIdOptional.has_value()) {
840 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700841 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000842 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
843 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
844 }
845 std::string cameraId = cameraIdOptional.value();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700846
847 binder::Status res;
848 if (request == nullptr) {
849 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
850 "Camera %s: Error creating default request", cameraId.c_str());
851 return res;
852 }
853 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
854 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
855 cameraId, templateId, &tempId);
856 if (!res.isOk()) {
857 ALOGE("%s: Camera %s: failed to map request Template %d",
858 __FUNCTION__, cameraId.c_str(), templateId);
859 return res;
860 }
861
862 if (shouldRejectSystemCameraConnection(cameraId)) {
863 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
864 "request for system only device %s: ", cameraId.c_str());
865 }
866
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700867 CameraMetadata metadata;
868 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
869 if (err == OK) {
870 request->swap(metadata);
871 } else if (err == BAD_VALUE) {
872 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
873 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
874 cameraId.c_str(), templateId, strerror(-err), err);
875 } else {
876 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
877 "Camera %s: Error creating default request for template %d: %s (%d)",
878 cameraId.c_str(), templateId, strerror(-err), err);
879 }
880 return res;
881}
882
883Status CameraService::isSessionConfigurationWithParametersSupported(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700884 const std::string& unresolvedCameraId, int targetSdkVersion,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700885 const SessionConfiguration& sessionConfiguration,
Austin Borger65e64642024-06-11 15:58:23 -0700886 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700887 /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700888 ATRACE_CALL();
889
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700890 if (!mInitialized) {
891 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
892 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
893 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
894 }
895
Austin Borger65e64642024-06-11 15:58:23 -0700896 std::optional<std::string> cameraIdOptional =
897 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000898 if (!cameraIdOptional.has_value()) {
899 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700900 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000901 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
902 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
903 }
904 std::string cameraId = cameraIdOptional.value();
905
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700906 if (supported == nullptr) {
907 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
908 unresolvedCameraId.c_str());
909 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
910 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
911 }
912
913 if (shouldRejectSystemCameraConnection(cameraId)) {
914 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
915 "session configuration with parameters support for system only device %s: ",
916 cameraId.c_str());
917 }
918
Avichal Rakeshe005df52024-09-25 17:13:27 -0700919 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700920 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
921
Shuzhen Wange3e8e732024-05-22 17:48:01 -0700922 auto ret = isSessionConfigurationWithParametersSupportedUnsafe(cameraId,
923 sessionConfiguration, overrideForPerfClass, supported);
924 if (flags::analytics_24q3()) {
925 mCameraServiceProxyWrapper->logFeatureCombinationQuery(cameraId,
926 getCallingUid(), sessionConfiguration, ret);
927 }
928 return ret;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700929}
930
931Status CameraService::isSessionConfigurationWithParametersSupportedUnsafe(
932 const std::string& cameraId, const SessionConfiguration& sessionConfiguration,
933 bool overrideForPerfClass, /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700934 *supported = false;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700935 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(
936 cameraId, sessionConfiguration, overrideForPerfClass,
937 /*checkSessionParams=*/true, supported);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700938 binder::Status res;
939 switch (ret) {
940 case OK:
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700941 // Expected. Do Nothing.
942 return Status::ok();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700943 case INVALID_OPERATION: {
944 std::string msg = fmt::sprintf(
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700945 "Camera %s: Session configuration with parameters supported query not "
946 "supported!",
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700947 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700948 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
949 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
950 *supported = false;
951 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700952 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700953 break;
954 case NAME_NOT_FOUND: {
955 std::string msg = fmt::sprintf("Camera %s: Unknown camera ID.", cameraId.c_str());
956 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
957 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
958 *supported = false;
959 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
960 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700961 break;
962 default: {
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700963 std::string msg = fmt::sprintf(
964 "Unable to retrieve session configuration support for camera "
965 "device %s: Error: %s (%d)",
966 cameraId.c_str(), strerror(-ret), ret);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700967 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700968 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
969 *supported = false;
970 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700971 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700972 break;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700973 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700974}
975
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800976Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000977 int targetSdkVersion, int rotationOverride,
Austin Borger65e64642024-06-11 15:58:23 -0700978 const SessionConfiguration& sessionConfiguration,
979 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +0000980 /*out*/ CameraMetadata* outMetadata) {
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800981 ATRACE_CALL();
982
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800983 if (outMetadata == nullptr) {
984 std::string msg =
985 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
986 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
987 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
988 }
989
Avichal Rakesh4baf7262024-03-20 19:16:04 -0700990 if (!mInitialized) {
991 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
992 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
993 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
994 }
995
Austin Borger65e64642024-06-11 15:58:23 -0700996 std::optional<std::string> cameraIdOptional =
997 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000998 if (!cameraIdOptional.has_value()) {
999 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001000 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001001 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1002 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1003 }
1004 std::string cameraId = cameraIdOptional.value();
1005
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001006 if (shouldRejectSystemCameraConnection(cameraId)) {
1007 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1008 "Unable to retrieve camera"
1009 "characteristics for system only device %s: ",
1010 cameraId.c_str());
1011 }
1012
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001013 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1014 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001015 if (flags::check_session_support_before_session_char()) {
1016 bool sessionConfigSupported;
1017 Status res = isSessionConfigurationWithParametersSupportedUnsafe(
1018 cameraId, sessionConfiguration, overrideForPerfClass, &sessionConfigSupported);
1019 if (!res.isOk()) {
1020 // isSessionConfigurationWithParametersSupportedUnsafe should log what went wrong and
1021 // report the correct Status to send to the client. Simply forward the error to
1022 // the client.
1023 outMetadata->clear();
1024 return res;
1025 }
1026 if (!sessionConfigSupported) {
1027 std::string msg = fmt::sprintf(
1028 "Session configuration not supported for camera device %s.", cameraId.c_str());
1029 outMetadata->clear();
1030 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1031 }
1032 }
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001033
1034 status_t ret = mCameraProviderManager->getSessionCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001035 cameraId, sessionConfiguration, overrideForPerfClass, rotationOverride, outMetadata);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001036
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001037 switch (ret) {
1038 case OK:
1039 // Expected, no handling needed.
1040 break;
1041 case INVALID_OPERATION: {
1042 std::string msg = fmt::sprintf(
1043 "Camera %s: Session characteristics query not supported!",
1044 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001045 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001046 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1047 outMetadata->clear();
1048 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1049 }
1050 break;
1051 case NAME_NOT_FOUND: {
1052 std::string msg = fmt::sprintf(
1053 "Camera %s: Unknown camera ID.",
1054 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001055 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001056 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1057 outMetadata->clear();
1058 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001059 }
1060 break;
1061 default: {
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001062 std::string msg = fmt::sprintf(
1063 "Unable to retrieve session characteristics for camera device %s: "
1064 "Error: %s (%d)",
1065 cameraId.c_str(), strerror(-ret), ret);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001066 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001067 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1068 outMetadata->clear();
1069 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001070 }
1071 }
1072
Shuzhen Wange3e8e732024-05-22 17:48:01 -07001073 Status res = filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
1074 if (flags::analytics_24q3()) {
1075 mCameraServiceProxyWrapper->logSessionCharacteristicsQuery(cameraId,
1076 getCallingUid(), sessionConfiguration, res);
1077 }
1078 return res;
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001079}
1080
1081Status CameraService::filterSensitiveMetadataIfNeeded(
1082 const std::string& cameraId, CameraMetadata* metadata) {
1083 int callingPid = getCallingPid();
1084 int callingUid = getCallingUid();
1085
1086 if (callingPid == getpid()) {
1087 // Caller is cameraserver; no need to remove keys
1088 return Status::ok();
1089 }
1090
1091 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1092 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1093 ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
1094 metadata->clear();
1095 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1096 "Unable to retrieve camera kind for device %s", cameraId.c_str());
1097 }
1098 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
1099 // Attempting to query system only camera without system camera permission would have
1100 // failed the shouldRejectSystemCameraConnection in the caller. So if we get here
1101 // for a system only camera, then the caller has the required permission.
1102 // No need to remove keys
1103 return Status::ok();
1104 }
1105
1106 std::vector<int32_t> tagsRemoved;
Biswarup Pale506e732024-03-27 13:46:20 +00001107 // Get the device id that owns this camera.
1108 auto [cameraOwnerDeviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1109 cameraId);
1110 bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid,
1111 cameraOwnerDeviceId);
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001112 if (hasCameraPermission) {
1113 // Caller has camera permission; no need to remove keys
1114 return Status::ok();
1115 }
1116
1117 status_t ret = metadata->removePermissionEntries(
1118 mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1119 if (ret != OK) {
1120 metadata->clear();
1121 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1122 "Failed to remove camera characteristics needing camera permission "
1123 "for device %s:%s (%d)",
1124 cameraId.c_str(), strerror(-ret), ret);
1125 }
1126
1127 if (!tagsRemoved.empty()) {
1128 ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1129 tagsRemoved.data(), tagsRemoved.size());
1130 if (ret != OK) {
1131 metadata->clear();
1132 return STATUS_ERROR_FMT(
1133 ERROR_INVALID_OPERATION,
1134 "Failed to insert camera keys needing permission for device %s: %s (%d)",
1135 cameraId.c_str(), strerror(-ret), ret);
1136 }
1137 }
1138 return Status::ok();
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001139}
1140
malikakash22af94c2023-12-04 18:13:14 +00001141Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001142 const std::string& cameraId,
1143 const CameraMetadata& sessionParams) {
1144 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001145 const int pid = getCallingPid();
1146 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001147 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1148 __FUNCTION__, pid, uid);
1149 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1150 "Permission Denial: no permission to inject session params");
1151 }
1152
Biswarup Pal37a75182024-01-16 15:53:35 +00001153 // Do not allow session params injection for a virtual camera.
1154 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1155 if (deviceId != kDefaultDeviceId) {
1156 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1157 "Cannot inject session params for a virtual camera");
1158 }
1159
malikakash22af94c2023-12-04 18:13:14 +00001160 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1161 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1162
1163 auto clientDescriptor = mActiveClientManager.get(cameraId);
1164 if (clientDescriptor == nullptr) {
1165 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1166 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1167 "No active client for camera id %s", cameraId.c_str());
1168 }
1169
1170 sp<BasicClient> clientSp = clientDescriptor->getValue();
1171 status_t res = clientSp->injectSessionParams(sessionParams);
1172
1173 if (res != OK) {
1174 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1175 "Error injecting session params into camera \"%s\": %s (%d)",
1176 cameraId.c_str(), strerror(-res), res);
1177 }
1178 return Status::ok();
1179}
1180
Biswarup Pal37a75182024-01-16 15:53:35 +00001181std::optional<std::string> CameraService::resolveCameraId(
1182 const std::string& inputCameraId,
1183 int32_t deviceId,
malikakash98260df2024-05-10 23:33:57 +00001184 int32_t devicePolicy) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001185 if ((deviceId == kDefaultDeviceId)
1186 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1187 auto [storedDeviceId, _] =
1188 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1189 if (storedDeviceId != kDefaultDeviceId) {
1190 // Trying to access a virtual camera from default-policy device context, we should fail.
1191 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1192 inputCameraId.c_str(), deviceId);
1193 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1194 return std::nullopt;
1195 }
malikakash98260df2024-05-10 23:33:57 +00001196 return inputCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001197 }
1198
1199 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1200}
1201
Austin Borger65e64642024-06-11 15:58:23 -07001202Status CameraService::getCameraInfo(int cameraId, int rotationOverride,
1203 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
1204 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001205 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001206 Mutex::Autolock l(mServiceLock);
Austin Borger65e64642024-06-11 15:58:23 -07001207 std::string cameraIdStr =
1208 cameraIdIntToStrLocked(cameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001209 if (cameraIdStr.empty()) {
1210 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001211 cameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001212 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1213 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1214 }
malikakashedb38962023-09-06 00:03:35 +00001215
Austin Borgered99f642023-06-01 16:51:35 -07001216 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001217 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1218 "characteristics for system only device %s: ", cameraIdStr.c_str());
1219 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001220
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001221 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001222 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001223 return STATUS_ERROR(ERROR_DISCONNECTED,
1224 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001225 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001226 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001227 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001228 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1229 if (hasSystemCameraPermissions) {
1230 cameraIdBound = mNumberOfCameras;
1231 }
1232 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001233 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1234 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001235 }
1236
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001237 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001238 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001239 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001240 cameraIdStr, rotationOverride, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001241 if (err != OK) {
1242 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1243 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1244 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001245 logServiceError(std::string("Error retrieving camera info from device ")
1246 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001247 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001248
Ruben Brunkcc776712015-02-17 20:18:47 -08001249 return ret;
1250}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001251
Biswarup Pal37a75182024-01-16 15:53:35 +00001252std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1253 int32_t deviceId, int32_t devicePolicy) {
1254 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1255 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1256 std::optional<std::string> cameraIdOptional =
1257 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1258 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1259 }
1260
1261 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001262 auto callingPid = getCallingPid();
1263 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001264 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1265 callingPid, callingUid, /* checkCameraPermissions= */ false);
1266 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001267 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001268 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001269 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1270 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1271 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001272 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001273 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001274
malikakash98260df2024-05-10 23:33:57 +00001275 return (*cameraIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001276}
1277
Biswarup Pal37a75182024-01-16 15:53:35 +00001278std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1279 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001280 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001281 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001282}
1283
Austin Borgered99f642023-06-01 16:51:35 -07001284Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07001285 int targetSdkVersion, int rotationOverride, const AttributionSourceState& clientAttribution,
1286 int32_t devicePolicy, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001287 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001288
Zhijun He2b59be82013-09-25 10:14:30 -07001289 if (!cameraInfo) {
1290 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001291 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001292 }
1293
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001294 if (!mInitialized) {
1295 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001296 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001297 return STATUS_ERROR(ERROR_DISCONNECTED,
1298 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001299 }
1300
Austin Borger65e64642024-06-11 15:58:23 -07001301 std::optional<std::string> cameraIdOptional =
1302 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001303 if (!cameraIdOptional.has_value()) {
1304 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001305 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001306 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1307 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1308 }
1309 std::string cameraId = cameraIdOptional.value();
1310
Austin Borgered99f642023-06-01 16:51:35 -07001311 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001312 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001313 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001314 }
1315
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001316 bool overrideForPerfClass =
1317 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001318 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001319 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001320 cameraId, overrideForPerfClass, cameraInfo, rotationOverride);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001321 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001322 if (res == NAME_NOT_FOUND) {
1323 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001324 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001325 strerror(-res), res);
1326 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001327 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1328 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001329 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001330 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001331 strerror(-res), res);
1332 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001333 }
Emilian Peeve20c6372018-08-14 18:45:53 +01001334
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001335 return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -07001336}
1337
Austin Borger65e64642024-06-11 15:58:23 -07001338Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId,
1339 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00001340 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001341 ATRACE_CALL();
1342 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001343
Austin Borger65e64642024-06-11 15:58:23 -07001344 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
1345 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001346 if (!cameraIdOptional.has_value()) {
1347 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001348 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001349 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1350 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1351 }
1352 std::string cameraId = cameraIdOptional.value();
1353
Rucha Katakwar38284522021-11-10 11:25:21 -08001354 if (!mInitialized) {
1355 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1356 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1357 }
1358
Biswarup Pal37a75182024-01-16 15:53:35 +00001359 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001360 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1361 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1362 }
1363
Austin Borgered99f642023-06-01 16:51:35 -07001364 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001365 if (res != OK) {
1366 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001367 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001368 strerror(-res), res);
1369 }
1370 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1371 return Status::ok();
1372}
1373
Austin Borgered99f642023-06-01 16:51:35 -07001374std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001375 time_t now = time(nullptr);
1376 char formattedTime[64];
1377 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001378 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001379}
1380
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001381Status CameraService::getCameraVendorTagDescriptor(
1382 /*out*/
1383 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001384 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001385 if (!mInitialized) {
1386 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001387 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001388 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001389 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1390 if (globalDescriptor != nullptr) {
1391 *desc = *(globalDescriptor.get());
1392 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001393 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001394}
1395
Emilian Peev71c73a22017-03-21 16:35:51 +00001396Status CameraService::getCameraVendorTagCache(
1397 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1398 ATRACE_CALL();
1399 if (!mInitialized) {
1400 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1401 return STATUS_ERROR(ERROR_DISCONNECTED,
1402 "Camera subsystem not available");
1403 }
1404 sp<VendorTagDescriptorCache> globalCache =
1405 VendorTagDescriptorCache::getGlobalVendorTagCache();
1406 if (globalCache != nullptr) {
1407 *cache = *(globalCache.get());
1408 }
1409 return Status::ok();
1410}
1411
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001412void CameraService::clearCachedVariables() {
1413 BasicClient::BasicClient::sCameraService = nullptr;
1414}
1415
Austin Borgered99f642023-06-01 16:51:35 -07001416std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001417 int rotationOverride, int* portraitRotation, int* facing,
1418 int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001419 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001420
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001421 int deviceVersion = 0;
1422
Emilian Peevf53f66e2017-04-11 14:29:43 +01001423 status_t res;
1424 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001425 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001426 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001427 if (res != OK || transport == IPCTransport::INVALID) {
1428 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001429 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001430 return std::make_pair(-1, IPCTransport::INVALID) ;
1431 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001432 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001433
Emilian Peevf53f66e2017-04-11 14:29:43 +01001434 hardware::CameraInfo info;
1435 if (facing) {
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001436 res = mCameraProviderManager->getCameraInfo(cameraId, rotationOverride,
Austin Borger18b30a72022-10-27 12:20:29 -07001437 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001438 if (res != OK) {
1439 return std::make_pair(-1, IPCTransport::INVALID);
1440 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001441 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001442 if (orientation) {
1443 *orientation = info.orientation;
1444 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001445 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001446
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001447 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001448}
1449
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001450Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001451 switch(err) {
1452 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001453 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001454 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001455 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1456 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001457 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001458 return STATUS_ERROR(ERROR_DISCONNECTED,
1459 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001460 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001461 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1462 "Camera HAL encountered error %d: %s",
1463 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001464 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001465}
1466
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001467Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001468 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1469 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001470 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001471 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001472 apiLevel effectiveApiLevel, bool overrideForPerfClass, int rotationOverride,
malikakash73125c62023-07-21 22:44:34 +00001473 bool forceSlowJpegMode, const std::string& originalCameraId,
1474 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001475 // For HIDL devices
1476 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1477 // Create CameraClient based on device version reported by the HAL.
1478 int deviceVersion = deviceVersionAndTransport.first;
1479 switch(deviceVersion) {
1480 case CAMERA_DEVICE_API_VERSION_1_0:
1481 ALOGE("Camera using old HAL version: %d", deviceVersion);
1482 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1483 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001484 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001485 break;
1486 case CAMERA_DEVICE_API_VERSION_3_0:
1487 case CAMERA_DEVICE_API_VERSION_3_1:
1488 case CAMERA_DEVICE_API_VERSION_3_2:
1489 case CAMERA_DEVICE_API_VERSION_3_3:
1490 case CAMERA_DEVICE_API_VERSION_3_4:
1491 case CAMERA_DEVICE_API_VERSION_3_5:
1492 case CAMERA_DEVICE_API_VERSION_3_6:
1493 case CAMERA_DEVICE_API_VERSION_3_7:
1494 break;
1495 default:
1496 // Should not be reachable
1497 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1498 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1499 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001500 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001501 }
1502 }
1503 if (effectiveApiLevel == API_1) { // Camera1 API route
1504 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001505 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001506 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001507 api1CameraId, facing, sensorOrientation,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001508 clientPid, clientUid, servicePid, overrideForPerfClass, rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00001509 forceSlowJpegMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001510 ALOGI("%s: Camera1 API (legacy), rotationOverride %d, forceSlowJpegMode %d",
1511 __FUNCTION__, rotationOverride, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001512 } else { // Camera2 API route
1513 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1514 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001515 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001516 cameraService->mCameraServiceProxyWrapper,
1517 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001518 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001519 overrideForPerfClass, rotationOverride, originalCameraId);
1520 ALOGI("%s: Camera2 API, rotationOverride %d", __FUNCTION__, rotationOverride);
Ruben Brunkcc776712015-02-17 20:18:47 -08001521 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001522 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001523}
1524
Austin Borgered99f642023-06-01 16:51:35 -07001525std::string CameraService::toString(std::set<userid_t> intSet) {
1526 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001527 bool first = true;
1528 for (userid_t i : intSet) {
1529 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001530 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001531 first = false;
1532 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001533 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001534 }
1535 }
Yi Kong3ac211f2024-08-12 07:31:44 +08001536 return s.str();
Ruben Brunk6267b532015-04-30 17:44:07 -07001537}
1538
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001539int32_t CameraService::mapToInterface(TorchModeStatus status) {
1540 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1541 switch (status) {
1542 case TorchModeStatus::NOT_AVAILABLE:
1543 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1544 break;
1545 case TorchModeStatus::AVAILABLE_OFF:
1546 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1547 break;
1548 case TorchModeStatus::AVAILABLE_ON:
1549 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1550 break;
1551 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001552 ALOGW("Unknown new flash status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001553 }
1554 return serviceStatus;
1555}
1556
1557CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1558 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1559 switch (status) {
1560 case CameraDeviceStatus::NOT_PRESENT:
1561 serviceStatus = StatusInternal::NOT_PRESENT;
1562 break;
1563 case CameraDeviceStatus::PRESENT:
1564 serviceStatus = StatusInternal::PRESENT;
1565 break;
1566 case CameraDeviceStatus::ENUMERATING:
1567 serviceStatus = StatusInternal::ENUMERATING;
1568 break;
1569 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001570 ALOGW("Unknown new HAL device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001571 }
1572 return serviceStatus;
1573}
1574
1575int32_t CameraService::mapToInterface(StatusInternal status) {
1576 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1577 switch (status) {
1578 case StatusInternal::NOT_PRESENT:
1579 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1580 break;
1581 case StatusInternal::PRESENT:
1582 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1583 break;
1584 case StatusInternal::ENUMERATING:
1585 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1586 break;
1587 case StatusInternal::NOT_AVAILABLE:
1588 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1589 break;
1590 case StatusInternal::UNKNOWN:
1591 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1592 break;
1593 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001594 ALOGW("Unknown new internal device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001595 }
1596 return serviceStatus;
1597}
1598
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001599Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001600 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001601
Austin Borgered99f642023-06-01 16:51:35 -07001602 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001603 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001604 sp<Client> tmp = nullptr;
Austin Borger7d2b9232024-07-22 14:17:14 -07001605
Austin Borgerb01a8702024-07-22 16:20:34 -07001606 int callingPid = getCallingPid();
1607 logConnectionAttempt(callingPid, kServiceName, cameraIdStr, API_1);
Austin Borger7d2b9232024-07-22 14:17:14 -07001608
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001609 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001610 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
Austin Borgerb01a8702024-07-22 16:20:34 -07001611 kServiceName, /*systemNativeClient*/ false, {}, uid, callingPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001612 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001613 /*targetSdkVersion*/ __ANDROID_API_FUTURE__,
1614 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_OVERRIDE_TO_PORTRAIT,
Austin Borger7d2b9232024-07-22 14:17:14 -07001615 /*forceSlowJpegMode*/false, cameraIdStr, /*isNonSystemNdk*/ false, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001616 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001617 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001618 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001619 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001620}
1621
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001622Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001623 /*out*/
1624 CameraParameters* parameters) {
1625
1626 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1627
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001628 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001629
1630 if (parameters == NULL) {
1631 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001632 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001633 }
1634
malikakash98260df2024-05-10 23:33:57 +00001635 std::string cameraIdStr = std::to_string(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001636
1637 // Check if we already have parameters
1638 {
1639 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001640 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001641 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001642 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001643 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001644 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001645 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001646 }
1647 CameraParameters p = cameraState->getShimParams();
1648 if (!p.isEmpty()) {
1649 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001650 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001651 }
1652 }
1653
Austin Borger22c5c852024-03-08 13:31:36 -08001654 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001655 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001656 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001657 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001658 // Error already logged by callee
1659 return ret;
1660 }
1661
1662 // Check for parameters again
1663 {
1664 // Scope for service lock
1665 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001666 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001667 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001668 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001669 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001670 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001671 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001672 CameraParameters p = cameraState->getShimParams();
1673 if (!p.isEmpty()) {
1674 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001675 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001676 }
1677 }
1678
Ruben Brunkcc776712015-02-17 20:18:47 -08001679 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1680 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001681 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001682}
1683
Austin Borgered99f642023-06-01 16:51:35 -07001684Status CameraService::validateConnectLocked(const std::string& cameraId,
Austin Borgerb01a8702024-07-22 16:20:34 -07001685 const std::string& clientName8, int clientUid, int clientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001686
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001687#ifdef __BRILLO__
1688 UNUSED(clientName8);
1689 UNUSED(clientUid);
1690 UNUSED(clientPid);
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001691#else
Austin Borger6e831c42024-07-22 13:07:56 -07001692 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001693 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001694 return allowed;
1695 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001696#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001697
Austin Borger22c5c852024-03-08 13:31:36 -08001698 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001699
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001700 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001701 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1702 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001703 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001704 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001705 }
1706
Ruben Brunkcc776712015-02-17 20:18:47 -08001707 if (getCameraState(cameraId) == nullptr) {
1708 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001709 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001710 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001711 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001712 }
1713
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001714 status_t err = checkIfDeviceIsUsable(cameraId);
1715 if (err != NO_ERROR) {
1716 switch(err) {
1717 case -ENODEV:
1718 case -EBUSY:
1719 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001720 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001721 default:
1722 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001723 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001724 }
1725 }
1726 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001727}
1728
Austin Borgerb01a8702024-07-22 16:20:34 -07001729Status CameraService::errorNotTrusted(int clientPid, int clientUid, const std::string& cameraId,
1730 const std::string& clientName, bool isPid) const {
Austin Borger22c5c852024-03-08 13:31:36 -08001731 int callingPid = getCallingPid();
1732 int callingUid = getCallingUid();
Austin Borgerb01a8702024-07-22 16:20:34 -07001733 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1734 "(don't trust %s %d)", callingPid, callingUid, isPid ? "clientPid" : "clientUid",
1735 isPid ? clientPid : clientUid);
1736 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1737 "Untrusted caller (calling PID %d, UID %d) trying to "
1738 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1739 getCallingPid(), getCallingUid(), cameraId.c_str(),
1740 clientName.c_str(), clientPid, clientUid);
1741}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742
Austin Borgerb01a8702024-07-22 16:20:34 -07001743Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1744 const std::string& clientName, int clientUid, int clientPid) const {
1745 int callingPid = getCallingPid();
1746 int callingUid = getCallingUid();
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001747
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001748 if (shouldRejectSystemCameraConnection(cameraId)) {
1749 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1750 cameraId.c_str());
1751 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001752 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001753 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001754 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1755 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001756 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001757 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001758 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001759 }
1760
Biswarup Pale506e732024-03-27 13:46:20 +00001761 // Get the device id that owns this camera.
1762 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1763
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001764 // If it's not calling from cameraserver, check the permission if the
1765 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1766 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001767 bool checkPermissionForCamera =
Biswarup Pale506e732024-03-27 13:46:20 +00001768 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName, deviceId);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001769 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001770 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001771 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001772 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1773 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001774 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001775 }
1776
Svet Ganova453d0d2018-01-11 15:37:58 -08001777 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001778 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001779 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001780 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1781 clientPid, clientUid);
1782 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001783 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1784 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001785 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001786 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001787 }
1788
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001789 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1790 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1791 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1792 if ((!isAutomotivePrivilegedClient(callingUid) ||
1793 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1794 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001795 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1796 return STATUS_ERROR_FMT(ERROR_DISABLED,
1797 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001798 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001799 }
1800
Austin Borger6e831c42024-07-22 13:07:56 -07001801 userid_t clientUserId = multiuser_get_user_id(clientUid);
1802
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001803 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1804 // connected to camera service directly.
Wu-cheng Lia3355432011-05-20 14:54:25 +08001805
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001806 // For non-system clients : Only allow clients who are being used by the current foreground
1807 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08001808 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001809 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001810 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1811 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001812 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001813 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1814 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001815 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001816 }
1817
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001818 if (flags::camera_hsum_permission()) {
1819 // If the System User tries to access the camera when the device is running in
1820 // headless system user mode, ensure that client has the required permission
1821 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07001822 if (isHeadlessSystemUserMode()
1823 && (clientUserId == USER_SYSTEM)
1824 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Austin Borger6e831c42024-07-22 13:07:56 -07001825 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", callingPid, clientUid);
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001826 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1827 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1828 User without camera headless system user permission",
Austin Borger6e831c42024-07-22 13:07:56 -07001829 clientName.c_str(), callingPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001830 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001831 }
1832
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001833 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001834}
1835
Austin Borgered99f642023-06-01 16:51:35 -07001836status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001837 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001838 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001839 if (cameraState == nullptr) {
1840 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001841 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001842 return -ENODEV;
1843 }
1844
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001845 StatusInternal currentStatus = cameraState->getStatus();
1846 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001847 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001848 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001849 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001850 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001851 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001852 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001853 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001854 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001855
Ruben Brunkcc776712015-02-17 20:18:47 -08001856 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001857}
1858
Ruben Brunkcc776712015-02-17 20:18:47 -08001859void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001860 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001861
Ruben Brunkcc776712015-02-17 20:18:47 -08001862 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001863 auto clientDescriptor =
1864 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001865 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001866 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1867
1868 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001869 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001870
1871 if (evicted.size() > 0) {
1872 // This should never happen - clients should already have been removed in disconnect
1873 for (auto& i : evicted) {
1874 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001875 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001876 }
1877
1878 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1879 __FUNCTION__);
1880 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001881
1882 // And register a death notification for the client callback. Do
1883 // this last to avoid Binder policy where a nested Binder
1884 // transaction might be pre-empted to service the client death
1885 // notification if the client process dies before linkToDeath is
1886 // invoked.
1887 sp<IBinder> remoteCallback = client->getRemote();
1888 if (remoteCallback != nullptr) {
1889 remoteCallback->linkToDeath(this);
1890 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001891}
1892
Austin Borgered99f642023-06-01 16:51:35 -07001893status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1894 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1895 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001896 /*out*/
1897 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001898 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001899 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001900 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001901 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001902 DescriptorPtr clientDescriptor;
1903 {
1904 if (effectiveApiLevel == API_1) {
1905 // If we are using API1, any existing client for this camera ID with the same remote
1906 // should be returned rather than evicted to allow MediaRecorder to work properly.
1907
1908 auto current = mActiveClientManager.get(cameraId);
1909 if (current != nullptr) {
1910 auto clientSp = current->getValue();
1911 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001912 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001913 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001914 " API level, evicting prior client...");
1915 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001916 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001917 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001918 *client = clientSp;
1919 return NO_ERROR;
1920 }
1921 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001922 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001923 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001924
Ruben Brunkcc776712015-02-17 20:18:47 -08001925 // Get state for the given cameraId
1926 auto state = getCameraState(cameraId);
1927 if (state == nullptr) {
1928 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001929 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001930 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001931 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001932 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001933
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001934 sp<IServiceManager> sm = defaultServiceManager();
1935 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08001936 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001937 // If processinfo service is not available and the client is automotive privileged
1938 // client used for safety critical uses cases such as rear-view and surround-view which
1939 // needs to be available before android boot completes, then use the hardcoded values
1940 // for the process state and priority score. As this scenario is before android system
1941 // services are up and client is native client, hence using NATIVE_ADJ as the priority
1942 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
1943 // visible on the top.
1944 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1945 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1946 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
1947 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
1948 } else {
1949 // Get current active client PIDs
1950 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1951 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001952
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001953 std::vector<int> priorityScores(ownerPids.size());
1954 std::vector<int> states(ownerPids.size());
1955
1956 // Get priority scores of all active PIDs
1957 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
1958 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
1959 if (err != OK) {
1960 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
1961 return err;
1962 }
1963
1964 // Update all active clients' priorities
1965 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
1966 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1967 pidToPriorityMap.emplace(ownerPids[i],
1968 resource_policy::ClientPriority(priorityScores[i], states[i],
1969 /* isVendorClient won't get copied over*/ false,
1970 /* oomScoreOffset won't get copied over*/ 0));
1971 }
1972 mActiveClientManager.updatePriorities(pidToPriorityMap);
1973
1974 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1975 int32_t actualState = states[states.size() - 1];
1976
1977 // Make descriptor for incoming client. We store the oomScoreOffset
1978 // since we might need it later on new handleEvictionsLocked and
1979 // ProcessInfoService would not take that into account.
1980 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1981 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1982 state->getConflicting(), actualScore, clientPid, actualState,
1983 oomScoreOffset, systemNativeClient);
1984 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001985
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001986 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1987
Ruben Brunkcc776712015-02-17 20:18:47 -08001988 // Find clients that would be evicted
1989 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1990
1991 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1992 // background, so we cannot do evictions
1993 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1994 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1995 " priority).", clientPid);
1996
1997 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07001998 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08001999 auto incompatibleClients =
2000 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2001
Austin Borgered99f642023-06-01 16:51:35 -07002002 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2003 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2004 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002005 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002006
2007 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002008 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002009 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002010 i->getKey().c_str(),
2011 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002012 i->getOwnerId(), i->getPriority().getScore(),
2013 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002014 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002015 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2016 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002017 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002018 }
2019
2020 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002021 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002022 mEventLog.add(msg);
2023
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002024 auto current = mActiveClientManager.get(cameraId);
2025 if (current != nullptr) {
2026 return -EBUSY; // CAMERA_IN_USE
2027 } else {
2028 return -EUSERS; // MAX_CAMERAS_IN_USE
2029 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002030 }
2031
2032 for (auto& i : evicted) {
2033 sp<BasicClient> clientSp = i->getValue();
2034 if (clientSp.get() == nullptr) {
2035 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2036
2037 // TODO: Remove this
2038 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2039 __FUNCTION__);
2040 mActiveClientManager.remove(i);
2041 continue;
2042 }
2043
2044 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002045 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002046 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002047
Ruben Brunkcc776712015-02-17 20:18:47 -08002048 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002049 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002050 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2051 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002052 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002053 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002054 i->getPriority().getState(), cameraId.c_str(),
2055 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002056 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002057
2058 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002059 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002060 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002061 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002062 }
2063
Ruben Brunkcc776712015-02-17 20:18:47 -08002064 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2065 // other clients from connecting in mServiceLockWrapper if held
2066 mServiceLock.unlock();
2067
2068 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002069 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002070
2071 // Destroy evicted clients
2072 for (auto& i : evictedClients) {
2073 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002074 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002075 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002076
Austin Borger22c5c852024-03-08 13:31:36 -08002077 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002078
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002079 for (const auto& i : evictedClients) {
2080 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002081 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002082 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2083 if (ret == TIMED_OUT) {
2084 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002085 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2086 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002087 return -EBUSY;
2088 }
2089 if (ret != NO_ERROR) {
2090 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002091 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2092 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002093 return ret;
2094 }
2095 }
2096
2097 evictedClients.clear();
2098
Ruben Brunkcc776712015-02-17 20:18:47 -08002099 // Once clients have been disconnected, relock
2100 mServiceLock.lock();
2101
2102 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2103 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2104 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002105 }
2106
Ruben Brunkcc776712015-02-17 20:18:47 -08002107 *partial = clientDescriptor;
2108 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002109}
2110
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002111Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002112 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002113 int api1CameraId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002114 int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002115 int rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00002116 bool forceSlowJpegMode,
Austin Borger65e64642024-06-11 15:58:23 -07002117 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00002118 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002119 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002120 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002121 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002122 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002123
Austin Borger65e64642024-06-11 15:58:23 -07002124 std::string cameraIdStr =
2125 cameraIdIntToStr(api1CameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002126 if (cameraIdStr.empty()) {
2127 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002128 api1CameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002129 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2130 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2131 }
malikakashedb38962023-09-06 00:03:35 +00002132
Austin Borger7d2b9232024-07-22 14:17:14 -07002133 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
2134 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
2135 std::string clientPackageName = resolvePackageName(clientAttribution.uid,
2136 clientPackageNameMaybe);
2137 logConnectionAttempt(clientAttribution.pid, clientPackageName, cameraIdStr, API_1);
2138
Austin Borgerb01a8702024-07-22 16:20:34 -07002139 int clientUid = clientAttribution.uid;
2140 int clientPid = clientAttribution.pid;
2141
2142 // Resolve the client identity. In the near future, we will no longer rely on USE_CALLING_*, and
2143 // need a way to guarantee the caller identity early.
2144
2145 // Check if we can trust clientUid
2146 if (!resolveClientUid(clientUid)) {
2147 return errorNotTrusted(clientPid, clientUid, cameraIdStr, clientPackageName,
2148 /* isPid=*/ false);
2149 }
2150
2151 // Check if we can trust clientUid
2152 if (!resolveClientPid(clientPid)) {
2153 return errorNotTrusted(clientPid, clientUid, cameraIdStr, clientPackageName,
2154 /* isPid= */ true);
2155 }
2156
Ruben Brunkcc776712015-02-17 20:18:47 -08002157 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002158 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
Austin Borger7d2b9232024-07-22 14:17:14 -07002159 clientPackageName, /*systemNativeClient*/ false, {},
Austin Borgerb01a8702024-07-22 16:20:34 -07002160 clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002161 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borger7d2b9232024-07-22 14:17:14 -07002162 rotationOverride, forceSlowJpegMode, cameraIdStr, isNonSystemNdk, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002163
Biswarup Pal37a75182024-01-16 15:53:35 +00002164 if (!ret.isOk()) {
Austin Borgerd1ad6c62024-07-01 11:28:31 -07002165 logRejected(cameraIdStr, getCallingPid(), clientAttribution.packageName.value_or(""),
2166 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002167 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002168 }
2169
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002170 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002171
2172 const sp<IServiceManager> sm(defaultServiceManager());
2173 const auto& mActivityManager = getActivityManager();
2174 if (mActivityManager) {
2175 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002176 getCallingUid(),
2177 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002178 }
2179
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002180 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002181}
2182
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002183bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2184 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002185 // If the client is not a vendor client, don't add listener if
2186 // a) the camera is a publicly hidden secure camera OR
2187 // b) the camera is a system only camera and the client doesn't
2188 // have android.permission.SYSTEM_CAMERA permissions.
2189 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2190 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002191 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002192 return true;
2193 }
2194 return false;
2195}
2196
Austin Borgered99f642023-06-01 16:51:35 -07002197bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002198 // Rules for rejection:
2199 // 1) If cameraserver tries to access this camera device, accept the
2200 // connection.
2201 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002202 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002203 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2204 // and the serving thread is a non hwbinder thread, the client must have
2205 // android.permission.SYSTEM_CAMERA permissions to connect.
2206
Austin Borger22c5c852024-03-08 13:31:36 -08002207 int cPid = getCallingPid();
2208 int cUid = getCallingUid();
2209 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002210 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2211 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002212 // This isn't a known camera ID, so it's not a system camera
2213 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2214 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002215 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002216
2217 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002218 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002219 return false;
2220 }
2221 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002222 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002223 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2224 return true;
2225 }
2226 // (3) Here we only check for permissions if it is a system only camera device. This is since
2227 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2228 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2229 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002230 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002231 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002232 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2233 cameraId.c_str());
2234 return true;
2235 }
2236
2237 return false;
2238}
2239
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002240Status CameraService::connectDevice(
2241 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002242 const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002243 int oomScoreOffset, int targetSdkVersion,
2244 int rotationOverride, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Ruben Brunkcc776712015-02-17 20:18:47 -08002245 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002246 sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002247 ATRACE_CALL();
Emilian Peev31bd2422024-04-23 22:24:09 +00002248 RunThreadWithRealtimePriority priorityBump;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002249 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002250 sp<CameraDeviceClient> client = nullptr;
Austin Borger7d2b9232024-07-22 14:17:14 -07002251 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
Austin Borger22c5c852024-03-08 13:31:36 -08002252 int callingPid = getCallingPid();
2253 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002254 bool systemNativeClient = false;
Austin Borger7d2b9232024-07-22 14:17:14 -07002255 if (callerHasSystemUid() && (clientPackageNameMaybe.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002256 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borger7d2b9232024-07-22 14:17:14 -07002257 clientPackageNameMaybe = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002258 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002259 }
Austin Borger249e6592024-03-10 22:28:11 -07002260
Austin Borger65e64642024-06-11 15:58:23 -07002261 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2262 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002263 if (!cameraIdOptional.has_value()) {
2264 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002265 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002266 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2267 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2268 }
2269 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002270
Austin Borger7d2b9232024-07-22 14:17:14 -07002271 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
2272 std::string clientPackageName = resolvePackageName(clientAttribution.uid,
2273 clientPackageNameMaybe);
2274 logConnectionAttempt(clientAttribution.pid, clientPackageName, cameraId, API_2);
2275
Austin Borgerb01a8702024-07-22 16:20:34 -07002276 userid_t clientUserId = multiuser_get_user_id(clientAttribution.uid);
2277 if (clientAttribution.uid == USE_CALLING_UID) {
2278 clientUserId = multiuser_get_user_id(callingUid);
2279 }
2280
2281 // Resolve the client identity. In the near future, we will no longer rely on USE_CALLING_*, and
2282 // need a way to guarantee the caller identity early.
2283
2284 int clientUid = clientAttribution.uid;
2285 int clientPid = callingPid;
2286 // Check if we can trust clientUid
2287 if (!resolveClientUid(clientUid)) {
2288 return errorNotTrusted(clientPid, clientUid, cameraId, clientPackageName,
2289 /* isPid= */ false);
2290 }
2291
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002292 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002293 std::string msg =
2294 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
Austin Borger7d2b9232024-07-22 14:17:14 -07002295 "camera id %s", clientPackageName.c_str(), callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07002296 cameraId.c_str());
2297 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2298 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002299 }
2300
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002301 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2302 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002303 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2304 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002305 std::string msg = "Camera disabled by device policy";
2306 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2307 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002308 }
2309
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002310 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002311 if (oomScoreOffset > 0
2312 && !hasPermissionsForSystemCamera(cameraId, callingPid,
Austin Borger249e6592024-03-10 22:28:11 -07002313 callingUid)
2314 && !isTrustedCallingUid(callingUid)) {
Austin Borgered99f642023-06-01 16:51:35 -07002315 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002316 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borger7d2b9232024-07-22 14:17:14 -07002317 clientPackageName.c_str(), callingPid, cameraId.c_str());
Austin Borgered99f642023-06-01 16:51:35 -07002318 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2319 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002320 }
2321
Austin Borgered99f642023-06-01 16:51:35 -07002322 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
Austin Borger7d2b9232024-07-22 14:17:14 -07002323 cameraId, /*api1CameraId*/-1, clientPackageName, systemNativeClient,
Austin Borgerb01a8702024-07-22 16:20:34 -07002324 clientAttribution.attributionTag, clientUid, clientPid, API_2,
Austin Borgerd1ad6c62024-07-01 11:28:31 -07002325 /*shimUpdateOnly*/ false, oomScoreOffset, targetSdkVersion, rotationOverride,
Austin Borger7d2b9232024-07-22 14:17:14 -07002326 /*forceSlowJpegMode*/false, unresolvedCameraId, isNonSystemNdk, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002327
Biswarup Pal37a75182024-01-16 15:53:35 +00002328 if (!ret.isOk()) {
Austin Borger7d2b9232024-07-22 14:17:14 -07002329 logRejected(cameraId, callingPid, clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002330 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002331 }
2332
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002333 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002334 Mutex::Autolock lock(mServiceLock);
2335
2336 // Clear the previous cached logs and reposition the
2337 // file offset to beginning of the file to log new data.
2338 // If either truncate or lseek fails, close the previous file and create a new one.
2339 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2340 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2341 // Close the previous memfd.
2342 close(mMemFd);
2343 // If failure to wipe the data, then create a new file and
2344 // assign the new value to mMemFd.
2345 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2346 if (mMemFd == -1) {
2347 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2348 }
2349 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002350 const sp<IServiceManager> sm(defaultServiceManager());
2351 const auto& mActivityManager = getActivityManager();
2352 if (mActivityManager) {
2353 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002354 callingUid,
2355 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002356 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002357 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002358}
2359
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002360bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2361 int callingPid, int callingUid) {
2362 if (!isAutomotiveDevice()) {
2363 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2364 }
2365
2366 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2367 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2368 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2369 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2370 "using camera %s", callingUid, cam_id.c_str());
2371 return false;
2372 }
2373
2374 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2375 return true;
2376 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2377 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002378 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2379 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002380 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2381 return false;
2382 } else {
2383 return true;
2384 }
2385 }
2386 return false;
2387}
2388
Austin Borger7d2b9232024-07-22 14:17:14 -07002389std::string CameraService::getPackageNameFromUid(int clientUid) const {
Austin Borgered99f642023-06-01 16:51:35 -07002390 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002391
Avichal Rakesh5788fec2024-03-15 14:39:20 -07002392 sp<IPermissionController> permCtrl;
2393 if (flags::cache_permission_services()) {
2394 permCtrl = getPermissionController();
2395 } else {
2396 sp<IServiceManager> sm = defaultServiceManager();
2397#pragma clang diagnostic push
2398#pragma clang diagnostic ignored "-Wdeprecated-declarations"
2399 // Using deprecated function to preserve functionality until the
2400 // cache_permission_services flag is removed.
2401 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
2402#pragma clang diagnostic pop
2403 if (binder == 0) {
2404 ALOGE("Cannot get permission service");
2405 permCtrl = nullptr;
2406 } else {
2407 permCtrl = interface_cast<IPermissionController>(binder);
2408 }
2409 }
2410
2411 if (permCtrl == nullptr) {
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002412 // Return empty package name and the further interaction
2413 // with camera will likely fail
2414 return packageName;
2415 }
2416
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002417 Vector<String16> packages;
2418
2419 permCtrl->getPackagesForUid(clientUid, packages);
2420
2421 if (packages.isEmpty()) {
2422 ALOGE("No packages for calling UID %d", clientUid);
2423 // Return empty package name and the further interaction
2424 // with camera will likely fail
2425 return packageName;
2426 }
2427
2428 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002429 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002430
2431 return packageName;
2432}
2433
Austin Borger7d2b9232024-07-22 14:17:14 -07002434void CameraService::logConnectionAttempt(int clientPid, const std::string& clientPackageName,
2435 const std::string& cameraId, apiLevel effectiveApiLevel) const {
2436 int packagePid = (clientPid == USE_CALLING_PID) ?
2437 getCallingPid() : clientPid;
2438 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
2439 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
2440 static_cast<int>(effectiveApiLevel));
2441}
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002442
Austin Borger7d2b9232024-07-22 14:17:14 -07002443std::string CameraService::resolvePackageName(int clientUid,
2444 const std::string& clientPackageNameMaybe) const {
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002445 if (clientPackageNameMaybe.size() <= 0) {
Austin Borger7d2b9232024-07-22 14:17:14 -07002446 int packageUid = (clientUid == USE_CALLING_UID) ?
2447 getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002448 // NDK calls don't come with package names, but we need one for various cases.
2449 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2450 // do exist. For all authentication cases, all packages under the same UID get the
2451 // same permissions, so picking any associated package name is sufficient. For some
2452 // other cases, this may give inaccurate names for clients in logs.
Austin Borger7d2b9232024-07-22 14:17:14 -07002453 return getPackageNameFromUid(packageUid);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002454 } else {
Austin Borger7d2b9232024-07-22 14:17:14 -07002455 return clientPackageNameMaybe;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002456 }
Austin Borger7d2b9232024-07-22 14:17:14 -07002457}
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002458
Austin Borger7d2b9232024-07-22 14:17:14 -07002459template<class CALLBACK, class CLIENT>
2460Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2461 int api1CameraId, const std::string& clientPackageName, bool systemNativeClient,
2462 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
2463 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
2464 int rotationOverride, bool forceSlowJpegMode,
2465 const std::string& originalCameraId, bool isNonSystemNdk, /*out*/sp<CLIENT>& device) {
2466 binder::Status ret = binder::Status::ok();
2467
2468 int packageUid = (clientUid == USE_CALLING_UID) ?
2469 getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002470 int packagePid = (clientPid == USE_CALLING_PID) ?
Austin Borger7d2b9232024-07-22 14:17:14 -07002471 getCallingPid() : clientPid;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002472
Shuzhen Wang316781a2020-08-18 18:11:01 -07002473 nsecs_t openTimeNs = systemTime();
2474
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002475 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002476 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002477 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002478
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002479 {
2480 // Acquire mServiceLock and prevent other clients from connecting
2481 std::unique_ptr<AutoConditionLock> lock =
2482 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2483
2484 if (lock == nullptr) {
2485 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2486 , clientPid);
2487 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2488 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002489 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002490 }
2491
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002492 // Enforce client permissions and do basic validity checks
Biswarup Pal37a75182024-01-16 15:53:35 +00002493 if (!(ret = validateConnectLocked(cameraId, clientPackageName,
Austin Borger6e831c42024-07-22 13:07:56 -07002494 /*inout*/clientUid, /*inout*/clientPid)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002495 return ret;
2496 }
2497
2498 // Check the shim parameters after acquiring lock, if they have already been updated and
2499 // we were doing a shim update, return immediately
2500 if (shimUpdateOnly) {
2501 auto cameraState = getCameraState(cameraId);
2502 if (cameraState != nullptr) {
2503 if (!cameraState->getShimParams().isEmpty()) return ret;
2504 }
2505 }
2506
2507 status_t err;
2508
2509 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002510 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Austin Borger6e831c42024-07-22 13:07:56 -07002511 if ((err = handleEvictionsLocked(cameraId, clientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002512 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2513 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002514 switch (err) {
2515 case -ENODEV:
2516 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2517 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002518 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002519 case -EBUSY:
2520 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2521 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002522 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002523 case -EUSERS:
2524 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2525 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002526 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002527 default:
2528 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2529 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002530 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002531 }
2532 }
2533
2534 if (clientTmp.get() != nullptr) {
2535 // Handle special case for API1 MediaRecorder where the existing client is returned
2536 device = static_cast<CLIENT*>(clientTmp.get());
2537 return ret;
2538 }
2539
2540 // give flashlight a chance to close devices if necessary.
2541 mFlashlight->prepareDeviceOpen(cameraId);
2542
Austin Borger18b30a72022-10-27 12:20:29 -07002543 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002544 auto deviceVersionAndTransport =
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002545 getDeviceVersion(cameraId, rotationOverride, /*out*/&portraitRotation,
Austin Borger18b30a72022-10-27 12:20:29 -07002546 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002547 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002548 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002549 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002550 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002551 }
2552
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002553 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002554 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002555 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002556
Austin Borger6e831c42024-07-22 13:07:56 -07002557 // Only use passed in clientPid to check permission. Use calling PID as the client PID
2558 // that's connected to camera service directly.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002559 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002560 clientFeatureId, cameraId, api1CameraId, facing,
Austin Borger7d2b9232024-07-22 14:17:14 -07002561 orientation, getCallingPid(), clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002562 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002563 rotationOverride, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002564 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002565 return ret;
2566 }
2567 client = static_cast<CLIENT*>(tmp.get());
2568
2569 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2570 __FUNCTION__);
2571
Austin Borgered99f642023-06-01 16:51:35 -07002572 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002573 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002574 if (err != OK) {
2575 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002576 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002577 mServiceLock.unlock();
2578 client->disconnect();
2579 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002580 switch(err) {
2581 case BAD_VALUE:
2582 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002583 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002584 case -EBUSY:
2585 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002586 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002587 case -EUSERS:
2588 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2589 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002590 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002591 case PERMISSION_DENIED:
2592 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002593 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002594 case -EACCES:
2595 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002596 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002597 case -ENODEV:
2598 default:
2599 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002600 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002601 strerror(-err), err);
2602 }
2603 }
2604
2605 // Update shim paremeters for legacy clients
2606 if (effectiveApiLevel == API_1) {
2607 // Assume we have always received a Client subclass for API1
2608 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2609 String8 rawParams = shimClient->getParameters();
2610 CameraParameters params(rawParams);
2611
2612 auto cameraState = getCameraState(cameraId);
2613 if (cameraState != nullptr) {
2614 cameraState->setShimParams(params);
2615 } else {
2616 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002617 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002618 }
2619 }
2620
Ravneetaeb20dc2022-03-30 05:33:03 +00002621 // Enable/disable camera service watchdog
2622 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2623
Emilian Peev6d45db82024-01-18 20:11:54 +00002624 CameraMetadata chars;
2625 bool rotateAndCropSupported = true;
2626 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002627 &chars, rotationOverride);
Emilian Peev6d45db82024-01-18 20:11:54 +00002628 if (err == OK) {
2629 auto availableRotateCropEntry = chars.find(
2630 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2631 if (availableRotateCropEntry.count <= 1) {
2632 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002633 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002634 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002635 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2636 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002637 }
2638
Emilian Peev6d45db82024-01-18 20:11:54 +00002639 if (rotateAndCropSupported) {
2640 // Set rotate-and-crop override behavior
2641 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2642 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002643 } else if (rotationOverride != hardware::ICameraService::ROTATION_OVERRIDE_NONE &&
2644 portraitRotation != 0) {
Emilian Peev6d45db82024-01-18 20:11:54 +00002645 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2646 switch (portraitRotation) {
2647 case 90:
2648 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2649 break;
2650 case 180:
2651 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2652 break;
2653 case 270:
2654 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2655 break;
2656 default:
2657 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2658 break;
2659 }
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002660 // Here we're communicating to the client the chosen rotate
2661 // and crop mode to send to the HAL
Emilian Peev6d45db82024-01-18 20:11:54 +00002662 client->setRotateAndCropOverride(rotateAndCropMode);
2663 } else {
2664 client->setRotateAndCropOverride(
2665 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2666 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2667 }
2668 }
2669
2670 bool autoframingSupported = true;
2671 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2672 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2673 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2674 autoframingSupported = false;
2675 }
2676
2677 if (autoframingSupported) {
2678 // Set autoframing override behaviour
2679 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2680 client->setAutoframingOverride(mOverrideAutoframingMode);
2681 } else {
2682 client->setAutoframingOverride(
2683 mCameraServiceProxyWrapper->getAutoframingOverride(
2684 clientPackageName));
2685 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002686 }
2687
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002688 bool isCameraPrivacyEnabled;
2689 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002690 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002691 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2692 toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2693 } else {
2694 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002695 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002696 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002697
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002698 if (client->supportsCameraMute()) {
2699 client->setCameraMute(
2700 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2701 } else if (isCameraPrivacyEnabled) {
2702 // no camera mute supported, but privacy is on! => disconnect
2703 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2704 client->getPackageName().c_str(), cameraId.c_str());
2705 // Do not hold mServiceLock while disconnecting clients, but
2706 // retain the condition blocking other clients from connecting
2707 // in mServiceLockWrapper if held.
2708 mServiceLock.unlock();
2709 // Clear caller identity temporarily so client disconnect PID
2710 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002711 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002712 // Note AppOp to trigger the "Unblock" dialog
2713 client->noteAppOp();
2714 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002715 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002716 // Reacquire mServiceLock
2717 mServiceLock.lock();
2718
2719 return STATUS_ERROR_FMT(ERROR_DISABLED,
2720 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002721 }
2722
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002723 if (shimUpdateOnly) {
2724 // If only updating legacy shim parameters, immediately disconnect client
2725 mServiceLock.unlock();
2726 client->disconnect();
2727 mServiceLock.lock();
2728 } else {
2729 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002730 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002731 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002732
2733 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002734 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002735 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002736 } // lock is destroyed, allow further connect calls
2737
2738 // Important: release the mutex here so the client can call back into the service from its
2739 // destructor (can be at the end of the call)
2740 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002741
2742 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002743 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002744 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002745
Cliff Wud3a05312021-04-26 23:07:31 +08002746 {
2747 Mutex::Autolock lock(mInjectionParametersLock);
2748 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2749 mInjectionInitPending = false;
2750 status_t res = NO_ERROR;
2751 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2752 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002753 sp<BasicClient> clientSp = clientDescriptor->getValue();
2754 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2755 if(res != OK) {
2756 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2757 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002758 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002759 }
2760 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002761 if (res != OK) {
2762 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2763 }
2764 } else {
2765 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002766 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002767 res = NO_INIT;
2768 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2769 }
2770 }
2771 }
2772
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002773 return ret;
2774}
2775
Austin Borgered99f642023-06-01 16:51:35 -07002776status_t CameraService::addOfflineClient(const std::string &cameraId,
2777 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002778 if (offlineClient.get() == nullptr) {
2779 return BAD_VALUE;
2780 }
2781
2782 {
2783 // Acquire mServiceLock and prevent other clients from connecting
2784 std::unique_ptr<AutoConditionLock> lock =
2785 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2786
2787 if (lock == nullptr) {
2788 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2789 , __FUNCTION__, offlineClient->getClientPid());
2790 return TIMED_OUT;
2791 }
2792
2793 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2794 if (onlineClientDesc.get() == nullptr) {
2795 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2796 cameraId.c_str());
2797 return BAD_VALUE;
2798 }
2799
2800 // Offline clients do not evict or conflict with other online devices. Resource sharing
2801 // conflicts are handled by the camera provider which will either succeed or fail before
2802 // reaching this method.
2803 const auto& onlinePriority = onlineClientDesc->getPriority();
2804 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2805 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002806 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002807 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002808 // native clients don't have offline processing support.
2809 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002810 if (offlineClientDesc == nullptr) {
2811 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2812 return BAD_VALUE;
2813 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002814
2815 // Allow only one offline device per camera
2816 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2817 if (!incompatibleClients.empty()) {
2818 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2819 return BAD_VALUE;
2820 }
2821
Austin Borgered99f642023-06-01 16:51:35 -07002822 std::string monitorTags = isClientWatched(offlineClient.get())
2823 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002824 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002825 if (err != OK) {
2826 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2827 return err;
2828 }
2829
2830 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2831 if (evicted.size() > 0) {
2832 for (auto& i : evicted) {
2833 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002834 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002835 }
2836
2837 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2838 "properly", __FUNCTION__);
2839
2840 return BAD_VALUE;
2841 }
2842
2843 logConnectedOffline(offlineClientDesc->getKey(),
2844 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002845 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002846
2847 sp<IBinder> remoteCallback = offlineClient->getRemote();
2848 if (remoteCallback != nullptr) {
2849 remoteCallback->linkToDeath(this);
2850 }
2851 } // lock is destroyed, allow further connect calls
2852
2853 return OK;
2854}
2855
Austin Borgered99f642023-06-01 16:51:35 -07002856Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002857 int32_t torchStrength, const sp<IBinder>& clientBinder,
2858 const AttributionSourceState& clientAttribution, int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002859 Mutex::Autolock lock(mServiceLock);
2860
2861 ATRACE_CALL();
2862 if (clientBinder == nullptr) {
2863 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2864 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2865 "Torch client binder in null.");
2866 }
2867
Austin Borger22c5c852024-03-08 13:31:36 -08002868 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002869 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2870 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002871 if (!cameraIdOptional.has_value()) {
2872 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002873 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002874 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2875 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2876 }
2877 std::string cameraId = cameraIdOptional.value();
2878
Austin Borgered99f642023-06-01 16:51:35 -07002879 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002880 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002881 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002882 }
2883
2884 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002885 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002886 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002887 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002888 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 StatusInternal cameraStatus = state->getStatus();
2893 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2894 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002895 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002896 (int)cameraStatus);
2897 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002898 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002899 }
2900
2901 {
2902 Mutex::Autolock al(mTorchStatusMutex);
2903 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002904 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002905 if (err != OK) {
2906 if (err == NAME_NOT_FOUND) {
2907 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002908 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002909 }
2910 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002911 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002912 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2913 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002914 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002915 }
2916
2917 if (status == TorchModeStatus::NOT_AVAILABLE) {
2918 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2919 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002920 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002921 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2922 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002923 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002924 } else {
2925 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002926 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002927 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2928 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002929 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002930 }
2931 }
2932 }
2933
2934 {
2935 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002936 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002937 }
2938 // Check if the current torch strength level is same as the new one.
2939 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002940 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002941
Austin Borgered99f642023-06-01 16:51:35 -07002942 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002943
2944 if (err != OK) {
2945 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002946 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002947 switch (err) {
2948 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002949 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2950 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002951 errorCode = ERROR_ILLEGAL_ARGUMENT;
2952 break;
2953 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002954 msg = fmt::sprintf("Camera \"%s\" is in use",
2955 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002956 errorCode = ERROR_CAMERA_IN_USE;
2957 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002958 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002959 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002960 "valid range.", torchStrength);
2961 errorCode = ERROR_ILLEGAL_ARGUMENT;
2962 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002963 default:
Austin Borgered99f642023-06-01 16:51:35 -07002964 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002965 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002966 }
Austin Borgered99f642023-06-01 16:51:35 -07002967 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2968 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002969 }
2970
2971 {
2972 // update the link to client's death
2973 // Store the last client that turns on each camera's torch mode.
2974 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002975 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002976 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002977 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002978 } else {
2979 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2980 mTorchClientMap.replaceValueAt(index, clientBinder);
2981 }
2982 clientBinder->linkToDeath(this);
2983 }
2984
Austin Borger22c5c852024-03-08 13:31:36 -08002985 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002986 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002987 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002988 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002989 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002990 }
2991 return Status::ok();
2992}
2993
malikakash73125c62023-07-21 22:44:34 +00002994Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Austin Borger65e64642024-06-11 15:58:23 -07002995 const sp<IBinder>& clientBinder, const AttributionSourceState& clientAttribution,
2996 int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002997 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002998
2999 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07003000 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003001 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003002 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
3003 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003004 }
3005
Austin Borger22c5c852024-03-08 13:31:36 -08003006 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07003007 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
3008 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00003009 if (!cameraIdOptional.has_value()) {
3010 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07003011 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00003012 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3013 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3014 }
3015 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003016
Austin Borgered99f642023-06-01 16:51:35 -07003017 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003018 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07003019 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003020 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003021 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07003022 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003023 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07003024 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
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());
Ruben Brunkcc776712015-02-17 20:18:47 -08003027 }
3028
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003029 StatusInternal cameraStatus = state->getStatus();
3030 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003031 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07003032 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
3033 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003034 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003035 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003036 }
3037
3038 {
3039 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003040 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003041 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003042 if (err != OK) {
3043 if (err == NAME_NOT_FOUND) {
3044 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003045 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003046 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003047 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003048 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003049 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07003050 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003051 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003052 }
3053
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003054 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003055 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003056 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003057 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003058 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3059 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003060 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003061 } else {
3062 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003063 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003064 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3065 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003066 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003067 }
3068 }
3069 }
3070
Ruben Brunk99e69712015-05-26 17:25:07 -07003071 {
3072 // Update UID map - this is used in the torch status changed callbacks, so must be done
3073 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003074 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003075 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003076 }
3077
Austin Borgered99f642023-06-01 16:51:35 -07003078 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003079
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003080 if (err != OK) {
3081 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003082 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003083 switch (err) {
3084 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003085 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3086 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003087 errorCode = ERROR_ILLEGAL_ARGUMENT;
3088 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003089 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003090 msg = fmt::sprintf("Camera \"%s\" is in use",
3091 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003092 errorCode = ERROR_CAMERA_IN_USE;
3093 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003094 default:
Austin Borgered99f642023-06-01 16:51:35 -07003095 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003096 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003097 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003098 errorCode = ERROR_INVALID_OPERATION;
3099 }
Austin Borgered99f642023-06-01 16:51:35 -07003100 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3101 logServiceError(msg, errorCode);
3102 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003103 }
3104
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003105 {
3106 // update the link to client's death
3107 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003108 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003109 if (enabled) {
3110 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003111 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003112 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003113 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003114 mTorchClientMap.replaceValueAt(index, clientBinder);
3115 }
3116 clientBinder->linkToDeath(this);
3117 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003118 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003119 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003120 }
3121
Austin Borger22c5c852024-03-08 13:31:36 -08003122 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003123 std::string torchState = enabled ? "on" : "off";
3124 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3125 torchState.c_str(), clientPid);
3126 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003127 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003128}
3129
Austin Borgered99f642023-06-01 16:51:35 -07003130void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3131 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3132 mTorchUidMap[cameraId].first = uid;
3133 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003134 } else {
3135 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003136 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003137 }
3138}
3139
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003140Status CameraService::notifySystemEvent(int32_t eventId,
3141 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003142 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003143 const int selfPid = getpid();
3144
3145 // Permission checks
3146 if (pid != selfPid) {
3147 // Ensure we're being called by system_server, or similar process with
3148 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003149 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003150 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003151 ALOGE("Permission Denial: cannot send updates to camera service about system"
3152 " events from pid=%d, uid=%d", pid, uid);
3153 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003154 "No permission to send updates to camera service about system events"
3155 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003156 }
3157 }
3158
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003159 ATRACE_CALL();
3160
Ruben Brunk36597b22015-03-20 22:15:57 -07003161 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003162 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003163 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003164 // from a system server crash
3165 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003166 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003167 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003168 break;
3169 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003170 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3171 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003172 if (args.size() != 1) {
3173 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3174 "USB Device Event requires 1 argument");
3175 }
3176
Valentin Iftime29e2e152021-08-13 15:17:33 +02003177 // Notify CameraProviderManager for lazy HALs
3178 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3179 std::to_string(args[0]));
3180 break;
3181 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003182 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003183 default: {
3184 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3185 eventId);
3186 break;
3187 }
3188 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003189 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003190}
3191
Emilian Peev53722fa2019-02-22 17:47:20 -08003192void CameraService::notifyMonitoredUids() {
3193 Mutex::Autolock lock(mStatusListenerLock);
3194
3195 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003196 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003197 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3198 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003199 }
3200}
3201
Austin Borgerdddb7552023-03-30 17:53:01 -07003202void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3203 Mutex::Autolock lock(mStatusListenerLock);
3204
3205 for (const auto& it : mListenerList) {
3206 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3207 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3208 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3209 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3210 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3211 }
3212 }
3213}
3214
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003215Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003216 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003217 const int selfPid = getpid();
3218
3219 // Permission checks
3220 if (pid != selfPid) {
3221 // Ensure we're being called by system_server, or similar process with
3222 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003223 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003224 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003225 ALOGE("Permission Denial: cannot send updates to camera service about device"
3226 " state changes from pid=%d, uid=%d", pid, uid);
3227 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3228 "No permission to send updates to camera service about device state"
3229 " changes from pid=%d, uid=%d", pid, uid);
3230 }
3231 }
3232
3233 ATRACE_CALL();
3234
Austin Borger18b30a72022-10-27 12:20:29 -07003235 {
3236 Mutex::Autolock lock(mServiceLock);
3237 mDeviceState = newState;
3238 }
3239
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003240 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003241
3242 return Status::ok();
3243}
3244
Emilian Peev8b64f282021-03-25 16:49:57 -07003245Status CameraService::notifyDisplayConfigurationChange() {
3246 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003247 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003248 const int selfPid = getpid();
3249
3250 // Permission checks
3251 if (callingPid != selfPid) {
3252 // Ensure we're being called by system_server, or similar process with
3253 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003254 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003255 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003256 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3257 " changes from pid=%d, uid=%d", callingPid, uid);
3258 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3259 "No permission to send updates to camera service about orientation"
3260 " changes from pid=%d, uid=%d", callingPid, uid);
3261 }
3262 }
3263
3264 Mutex::Autolock lock(mServiceLock);
3265
3266 // Don't do anything if rotate-and-crop override via cmd is active
3267 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3268
3269 const auto clients = mActiveClientManager.getAll();
3270 for (auto& current : clients) {
3271 if (current != nullptr) {
3272 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003273 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3274 basicClient->setRotateAndCropOverride(
3275 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3276 basicClient->getPackageName(),
3277 basicClient->getCameraFacing(),
3278 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003279 }
3280 }
3281 }
3282
3283 return Status::ok();
3284}
3285
3286Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003287 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3288 ATRACE_CALL();
3289 if (!concurrentCameraIds) {
3290 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3291 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3292 }
3293
3294 if (!mInitialized) {
3295 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003296 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003297 return STATUS_ERROR(ERROR_DISCONNECTED,
3298 "Camera subsystem is not available");
3299 }
3300 // First call into the provider and get the set of concurrent camera
3301 // combinations
3302 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003303 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003304 for (auto &combination : concurrentCameraCombinations) {
Biswarup Pal7d072862024-04-17 15:24:47 +00003305 std::vector<std::pair<std::string, int32_t>> validCombination;
3306 int32_t firstDeviceId = kInvalidDeviceId;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003307 for (auto &cameraId : combination) {
3308 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003309 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003310 if (state == nullptr) {
3311 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3312 continue;
3313 }
3314 StatusInternal status = state->getStatus();
3315 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3316 continue;
3317 }
Austin Borgered99f642023-06-01 16:51:35 -07003318 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003319 continue;
3320 }
Biswarup Pal7d072862024-04-17 15:24:47 +00003321 auto [cameraOwnerDeviceId, mappedCameraId] =
3322 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
3323 if (firstDeviceId == kInvalidDeviceId) {
3324 firstDeviceId = cameraOwnerDeviceId;
3325 } else if (firstDeviceId != cameraOwnerDeviceId) {
3326 // Found an invalid combination which contains cameras with different device id's,
3327 // hence discard it.
3328 validCombination.clear();
3329 break;
3330 }
3331 validCombination.push_back({mappedCameraId, cameraOwnerDeviceId});
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003332 }
3333 if (validCombination.size() != 0) {
3334 concurrentCameraIds->push_back(std::move(validCombination));
3335 }
3336 }
3337 return Status::ok();
3338}
3339
3340Status CameraService::isConcurrentSessionConfigurationSupported(
3341 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Austin Borger65e64642024-06-11 15:58:23 -07003342 int targetSdkVersion, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal7d072862024-04-17 15:24:47 +00003343 /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003344 if (!isSupported) {
3345 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3346 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3347 }
3348
3349 if (!mInitialized) {
3350 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3351 return STATUS_ERROR(ERROR_DISCONNECTED,
3352 "Camera subsystem is not available");
3353 }
3354
Biswarup Pal7d072862024-04-17 15:24:47 +00003355 for (auto cameraIdAndSessionConfiguration : cameraIdsAndSessionConfigurations) {
3356 std::optional<std::string> cameraIdOptional =
Austin Borger65e64642024-06-11 15:58:23 -07003357 resolveCameraId(cameraIdAndSessionConfiguration.mCameraId,
3358 clientAttribution.deviceId, devicePolicy);
Biswarup Pal7d072862024-04-17 15:24:47 +00003359 if (!cameraIdOptional.has_value()) {
3360 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07003361 cameraIdAndSessionConfiguration.mCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal7d072862024-04-17 15:24:47 +00003362 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3363 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3364 }
3365 cameraIdAndSessionConfiguration.mCameraId = cameraIdOptional.value();
3366 }
3367
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003368 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003369 int callingPid = getCallingPid();
3370 int callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003371 bool hasCameraPermission = ((callingPid == getpid()) ||
Biswarup Pal7d072862024-04-17 15:24:47 +00003372 hasPermissionsForCamera(callingPid, callingUid,
3373 devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT
Austin Borger65e64642024-06-11 15:58:23 -07003374 ? kDefaultDeviceId : clientAttribution.deviceId));
Austin Borger249e6592024-03-10 22:28:11 -07003375 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003376 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3377 "android.permission.CAMERA needed to call"
3378 "isConcurrentSessionConfigurationSupported");
3379 }
3380
3381 status_t res =
3382 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003383 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3384 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003385 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003386 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003387 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003388 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3389 "support %s (%d)", strerror(-res), res);
3390 }
3391 return Status::ok();
3392}
3393
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003394Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3395 /*out*/
3396 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003397 return addListenerHelper(listener, cameraStatuses);
3398}
3399
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003400binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3401 std::vector<hardware::CameraStatus>* cameraStatuses) {
3402 return addListenerHelper(listener, cameraStatuses, false, true);
3403}
3404
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003405Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3406 /*out*/
3407 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003408 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003409 ATRACE_CALL();
3410
Igor Murashkinbfc99152013-02-27 12:55:20 -08003411 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003412
Ruben Brunk3450ba72015-06-16 11:00:37 -07003413 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003414 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003415 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003416 }
3417
Austin Borger22c5c852024-03-08 13:31:36 -08003418 auto clientPid = getCallingPid();
3419 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003420 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003421
Igor Murashkinbfc99152013-02-27 12:55:20 -08003422 Mutex::Autolock lock(mServiceLock);
3423
Ruben Brunkcc776712015-02-17 20:18:47 -08003424 {
3425 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003426 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003427 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003428 ALOGW("%s: Tried to add listener %p which was already subscribed",
3429 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003430 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003431 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003432 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003433
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003434 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003435 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3436 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003437 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003438 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003439 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003440 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003441 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3442 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3443 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003444 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003445 // The listener still needs to be added to the list of listeners, regardless of what
3446 // permissions the listener process has / whether it is a vendor listener. Since it might be
3447 // eligible to listen to other camera ids.
3448 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003449 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003450 }
3451
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003452 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003453 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003454 Mutex::Autolock lock(mCameraStatesLock);
3455 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003456 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3457 auto [deviceId, mappedCameraId] =
3458 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3459
3460 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003461 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003462 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3463 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003464 }
3465 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003466 // Remove the camera statuses that should be hidden from the client, we do
3467 // this after collecting the states in order to avoid holding
3468 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3469 // the same time.
3470 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3471 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003472 std::string cameraId = s.cameraId;
3473 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
malikakash98260df2024-05-10 23:33:57 +00003474 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM);
Biswarup Pal37a75182024-01-16 15:53:35 +00003475 if (!cameraIdOptional.has_value()) {
3476 std::string msg =
3477 fmt::sprintf(
3478 "Camera %s: Invalid camera id for device id %d",
3479 s.cameraId.c_str(), s.deviceId);
3480 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3481 return true;
3482 }
3483 cameraId = cameraIdOptional.value();
3484 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3485 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3486 ALOGE("%s: Invalid camera id %s, skipping status update",
3487 __FUNCTION__, s.cameraId.c_str());
3488 return true;
3489 }
3490 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3491 clientUid);
3492 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003493
Biswarup Pal37a75182024-01-16 15:53:35 +00003494 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003495 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003496 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003497 // Add only default device cameras here, as virtual cameras currently don't support torch
3498 // anyway. Note that this is a simplification of the implementation here, and we should
3499 // change this when virtual cameras support torch.
3500 if (s.deviceId == kDefaultDeviceId) {
3501 idsChosenForCallback.insert(s.cameraId);
3502 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003503 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003504
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003505 /*
3506 * Immediately signal current torch status to this listener only
3507 * This may be a subset of all the devices, so don't include it in the response directly
3508 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003509 {
3510 Mutex::Autolock al(mTorchStatusMutex);
3511 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003512 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003513 // The camera id is visible to the client. Fine to send torch
3514 // callback.
3515 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003516 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3517 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003518 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003519 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003520 }
3521
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003522 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003523}
Ruben Brunkcc776712015-02-17 20:18:47 -08003524
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003525Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003526 ATRACE_CALL();
3527
Igor Murashkinbfc99152013-02-27 12:55:20 -08003528 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3529
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003530 if (listener == 0) {
3531 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003532 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003533 }
3534
Igor Murashkinbfc99152013-02-27 12:55:20 -08003535 Mutex::Autolock lock(mServiceLock);
3536
Ruben Brunkcc776712015-02-17 20:18:47 -08003537 {
3538 Mutex::Autolock lock(mStatusListenerLock);
3539 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003540 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003541 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003542 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003543 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003544 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003545 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003546 }
3547 }
3548
3549 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3550 __FUNCTION__, listener.get());
3551
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003552 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003553}
3554
Austin Borgered99f642023-06-01 16:51:35 -07003555Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003556
3557 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003558 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3559
3560 if (parameters == NULL) {
3561 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003562 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003563 }
3564
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003565 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003566
3567 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003568 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003569 // Error logged by caller
3570 return ret;
3571 }
3572
3573 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003574
Austin Borgered99f642023-06-01 16:51:35 -07003575 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003576
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003577 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003578}
3579
malikakash98260df2024-05-10 23:33:57 +00003580Status CameraService::supportsCameraApi(const std::string& cameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003581 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003582 ATRACE_CALL();
3583
Austin Borgered99f642023-06-01 16:51:35 -07003584 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003585
3586 switch (apiVersion) {
3587 case API_VERSION_1:
3588 case API_VERSION_2:
3589 break;
3590 default:
Austin Borgered99f642023-06-01 16:51:35 -07003591 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3592 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3593 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003594 }
3595
Austin Borger18b30a72022-10-27 12:20:29 -07003596 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00003597 auto deviceVersionAndTransport =
3598 getDeviceVersion(cameraId,
3599 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
3600 &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003601 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003602 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3603 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3604 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003605 }
3606 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3607 int deviceVersion = deviceVersionAndTransport.first;
3608 switch (deviceVersion) {
3609 case CAMERA_DEVICE_API_VERSION_1_0:
3610 case CAMERA_DEVICE_API_VERSION_3_0:
3611 case CAMERA_DEVICE_API_VERSION_3_1:
3612 if (apiVersion == API_VERSION_2) {
3613 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003614 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003615 *isSupported = false;
3616 } else { // if (apiVersion == API_VERSION_1) {
3617 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003618 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003619 *isSupported = true;
3620 }
3621 break;
3622 case CAMERA_DEVICE_API_VERSION_3_2:
3623 case CAMERA_DEVICE_API_VERSION_3_3:
3624 case CAMERA_DEVICE_API_VERSION_3_4:
3625 case CAMERA_DEVICE_API_VERSION_3_5:
3626 case CAMERA_DEVICE_API_VERSION_3_6:
3627 case CAMERA_DEVICE_API_VERSION_3_7:
3628 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003629 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003630 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003631 break;
3632 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003633 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3634 deviceVersion, cameraId.c_str());
3635 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3636 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003637 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003638 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003639 } else {
3640 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003641 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003642 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003643}
3644
malikakash98260df2024-05-10 23:33:57 +00003645Status CameraService::isHiddenPhysicalCamera(const std::string& cameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003646 /*out*/ bool *isSupported) {
3647 ATRACE_CALL();
3648
Austin Borgered99f642023-06-01 16:51:35 -07003649 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3650 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003651
3652 return Status::ok();
3653}
3654
Cliff Wud8cae102021-03-11 01:37:42 +08003655Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003656 const std::string& packageName, const std::string& internalCamId,
3657 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003658 const sp<ICameraInjectionCallback>& callback,
3659 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003660 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003661 ATRACE_CALL();
3662
Austin Borgered99f642023-06-01 16:51:35 -07003663 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003664 const int pid = getCallingPid();
3665 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003666 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3667 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003668 "Permission Denial: no permission to inject camera");
3669 }
3670
3671 // Do not allow any camera injection that injects or replaces a virtual camera.
3672 auto [deviceIdForInternalCamera, _] =
3673 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3674 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3675 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3676 "Cannot replace a virtual camera");
3677 }
3678 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3679 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3680 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3681 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3682 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003683 }
3684
3685 ALOGV(
3686 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3687 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003688 __FUNCTION__, packageName.c_str(),
3689 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003690
Cliff Wud3a05312021-04-26 23:07:31 +08003691 {
3692 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003693 mInjectionInternalCamId = internalCamId;
3694 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003695 mInjectionStatusListener->addListener(callback);
3696 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003697 status_t res = NO_ERROR;
3698 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3699 // If the client already exists, we can directly connect to the camera device through the
3700 // client's injectCamera(), otherwise we need to wait until the client is established
3701 // (execute connectHelper()) before injecting the camera to the camera device.
3702 if (clientDescriptor != nullptr) {
3703 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003704 sp<BasicClient> clientSp = clientDescriptor->getValue();
3705 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3706 if(res != OK) {
3707 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3708 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003709 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003710 }
3711 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003712 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003713 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3714 }
3715 } else {
3716 mInjectionInitPending = true;
3717 }
3718 }
Cliff Wud8cae102021-03-11 01:37:42 +08003719
Cliff Wud3a05312021-04-26 23:07:31 +08003720 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003721}
3722
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003723Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003724 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003725 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3726 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3727 return Status::ok();
3728}
3729
Ruben Brunkcc776712015-02-17 20:18:47 -08003730void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003731 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003732 for (auto& i : mActiveClientManager.getAll()) {
3733 auto clientSp = i->getValue();
3734 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003735 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003736 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003737 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003738 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003739 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003740}
3741
Ruben Brunkcc776712015-02-17 20:18:47 -08003742bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003743 bool ret = false;
3744 {
3745 // Acquire mServiceLock and prevent other clients from connecting
3746 std::unique_ptr<AutoConditionLock> lock =
3747 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003748
Ruben Brunkcc776712015-02-17 20:18:47 -08003749 std::vector<sp<BasicClient>> evicted;
3750 for (auto& i : mActiveClientManager.getAll()) {
3751 auto clientSp = i->getValue();
3752 if (clientSp.get() == nullptr) {
3753 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3754 mActiveClientManager.remove(i);
3755 continue;
3756 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003757 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003758 mActiveClientManager.remove(i);
3759 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003760
Ruben Brunkcc776712015-02-17 20:18:47 -08003761 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003762 clientSp->notifyError(
3763 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003764 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003765 }
3766 }
3767
Ruben Brunkcc776712015-02-17 20:18:47 -08003768 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3769 // other clients from connecting in mServiceLockWrapper if held
3770 mServiceLock.unlock();
3771
Ruben Brunk36597b22015-03-20 22:15:57 -07003772 // Do not clear caller identity, remote caller should be client proccess
3773
Ruben Brunkcc776712015-02-17 20:18:47 -08003774 for (auto& i : evicted) {
3775 if (i.get() != nullptr) {
3776 i->disconnect();
3777 ret = true;
3778 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003779 }
3780
Ruben Brunkcc776712015-02-17 20:18:47 -08003781 // Reacquire mServiceLock
3782 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003783
Ruben Brunkcc776712015-02-17 20:18:47 -08003784 } // lock is destroyed, allow further connect calls
3785
3786 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003787}
3788
Ruben Brunkcc776712015-02-17 20:18:47 -08003789std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003790 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003791 std::shared_ptr<CameraState> state;
3792 {
3793 Mutex::Autolock lock(mCameraStatesLock);
3794 auto iter = mCameraStates.find(cameraId);
3795 if (iter != mCameraStates.end()) {
3796 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003797 }
3798 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003799 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003800}
3801
Austin Borgered99f642023-06-01 16:51:35 -07003802sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003803 // Remove from active clients list
3804 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3805 if (clientDescriptorPtr == nullptr) {
3806 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003807 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003808 return sp<BasicClient>{nullptr};
3809 }
3810
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003811 sp<BasicClient> client = clientDescriptorPtr->getValue();
3812 if (client.get() != nullptr) {
3813 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3814 }
3815 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003816}
3817
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003818void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003819 // Acquire mServiceLock and prevent other clients from connecting
3820 std::unique_ptr<AutoConditionLock> lock =
3821 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3822
Ruben Brunk6267b532015-04-30 17:44:07 -07003823 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003824 for (size_t i = 0; i < newUserIds.size(); i++) {
3825 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003826 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003827 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003828 return;
3829 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003830 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003831 }
3832
Ruben Brunka8ca9152015-04-07 14:23:40 -07003833
Ruben Brunk6267b532015-04-30 17:44:07 -07003834 if (newAllowedUsers == mAllowedUsers) {
3835 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3836 return;
3837 }
3838
3839 logUserSwitch(mAllowedUsers, newAllowedUsers);
3840
3841 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003842
3843 // Current user has switched, evict all current clients.
3844 std::vector<sp<BasicClient>> evicted;
3845 for (auto& i : mActiveClientManager.getAll()) {
3846 auto clientSp = i->getValue();
3847
3848 if (clientSp.get() == nullptr) {
3849 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3850 continue;
3851 }
3852
Ruben Brunk6267b532015-04-30 17:44:07 -07003853 // Don't evict clients that are still allowed.
3854 uid_t clientUid = clientSp->getClientUid();
3855 userid_t clientUserId = multiuser_get_user_id(clientUid);
3856 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3857 continue;
3858 }
3859
Ruben Brunk36597b22015-03-20 22:15:57 -07003860 evicted.push_back(clientSp);
3861
Ruben Brunk36597b22015-03-20 22:15:57 -07003862 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003863 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003864
Ruben Brunk36597b22015-03-20 22:15:57 -07003865 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003866 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003867 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003868 " to user switch.", i->getKey().c_str(),
3869 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003870 i->getOwnerId(), i->getPriority().getScore(),
3871 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003872
3873 }
3874
3875 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3876 // blocking other clients from connecting in mServiceLockWrapper if held.
3877 mServiceLock.unlock();
3878
3879 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08003880 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003881
3882 for (auto& i : evicted) {
3883 i->disconnect();
3884 }
3885
Austin Borger22c5c852024-03-08 13:31:36 -08003886 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003887
3888 // Reacquire mServiceLock
3889 mServiceLock.lock();
3890}
Ruben Brunkcc776712015-02-17 20:18:47 -08003891
Austin Borgered99f642023-06-01 16:51:35 -07003892void CameraService::logEvent(const std::string &event) {
3893 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003894 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003895 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003896 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003897 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003898 mEventLog.add(msg);
3899 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3900 // Error event not added to the dumpsys log before
3901 mEventLog.add(msg);
3902 sServiceErrorEventSet.insert(msg);
3903 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003904}
3905
Austin Borgered99f642023-06-01 16:51:35 -07003906void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3907 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003908 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003909 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3910 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003911}
3912
Austin Borgered99f642023-06-01 16:51:35 -07003913void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3914 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003915 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003916 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3917 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003918}
3919
Austin Borgered99f642023-06-01 16:51:35 -07003920void CameraService::logConnected(const std::string &cameraId, int clientPid,
3921 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003922 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003923 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3924 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003925}
3926
Austin Borgered99f642023-06-01 16:51:35 -07003927void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3928 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003929 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003930 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3931 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003932}
3933
Austin Borgered99f642023-06-01 16:51:35 -07003934void CameraService::logRejected(const std::string &cameraId, int clientPid,
3935 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003936 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003937 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3938 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003939}
3940
Austin Borgered99f642023-06-01 16:51:35 -07003941void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3942 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003943 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003944 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3945 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003946}
3947
Ruben Brunk6267b532015-04-30 17:44:07 -07003948void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3949 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003950 std::string newUsers = toString(newUserIds);
3951 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003952 if (oldUsers.size() == 0) {
3953 oldUsers = "<None>";
3954 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003955 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003956 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3957 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003958}
3959
Austin Borgered99f642023-06-01 16:51:35 -07003960void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003961 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003962 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003963}
3964
Austin Borgered99f642023-06-01 16:51:35 -07003965void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003966 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003967 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003968}
3969
Austin Borgered99f642023-06-01 16:51:35 -07003970void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003971 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003972 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003973}
3974
Austin Borgered99f642023-06-01 16:51:35 -07003975void CameraService::logServiceError(const std::string &msg, int errorCode) {
3976 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3977 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003978}
3979
Ruben Brunk36597b22015-03-20 22:15:57 -07003980status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3981 uint32_t flags) {
3982
Mathias Agopian65ab4712010-07-14 17:59:35 -07003983 // Permission checks
3984 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003985 case SHELL_COMMAND_TRANSACTION: {
3986 int in = data.readFileDescriptor();
3987 int out = data.readFileDescriptor();
3988 int err = data.readFileDescriptor();
3989 int argc = data.readInt32();
3990 Vector<String16> args;
3991 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3992 args.add(data.readString16());
3993 }
3994 sp<IBinder> unusedCallback;
3995 sp<IResultReceiver> resultReceiver;
3996 status_t status;
3997 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3998 return status;
3999 }
4000 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
4001 return status;
4002 }
4003 status = shellCommand(in, out, err, args);
4004 if (resultReceiver != nullptr) {
4005 resultReceiver->send(status);
4006 }
4007 return NO_ERROR;
4008 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004009 }
4010
4011 return BnCameraService::onTransact(code, data, reply, flags);
4012}
4013
Mathias Agopian65ab4712010-07-14 17:59:35 -07004014// We share the media players for shutter and recording sound for all clients.
4015// A reference count is kept to determine when we will actually release the
4016// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09004017sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
4018 sp<MediaPlayer> mp = new MediaPlayer();
4019 status_t error;
4020 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08004021 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09004022 error = mp->prepare();
4023 }
4024 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004025 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09004026 mp->disconnect();
4027 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004028 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004029 }
4030 return mp;
4031}
4032
username5755fea2018-12-27 09:48:08 +08004033void CameraService::increaseSoundRef() {
4034 Mutex::Autolock lock(mSoundLock);
4035 mSoundRef++;
4036}
4037
4038void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004039 ATRACE_CALL();
4040
username5755fea2018-12-27 09:48:08 +08004041 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
4042 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
4043 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
4044 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
4045 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4046 }
4047 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
4048 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4049 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4050 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004051 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08004052 }
4053 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4054 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4055 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4056 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4057 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004058 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004059}
4060
username5755fea2018-12-27 09:48:08 +08004061void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004062 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004063 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004064 if (--mSoundRef) return;
4065
4066 for (int i = 0; i < NUM_SOUNDS; i++) {
4067 if (mSoundPlayer[i] != 0) {
4068 mSoundPlayer[i]->disconnect();
4069 mSoundPlayer[i].clear();
4070 }
4071 }
4072}
4073
4074void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004075 ATRACE_CALL();
4076
Mathias Agopian65ab4712010-07-14 17:59:35 -07004077 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004078 if (kind < 0 || kind >= NUM_SOUNDS) {
4079 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4080 return;
4081 }
4082
Mathias Agopian65ab4712010-07-14 17:59:35 -07004083 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004084 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004085 sp<MediaPlayer> player = mSoundPlayer[kind];
4086 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004087 player->seekTo(0);
4088 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004089 }
4090}
4091
4092// ----------------------------------------------------------------------------
4093
4094CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004095 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004096 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004097 const std::string& clientPackageName, bool systemNativeClient,
4098 const std::optional<std::string>& clientFeatureId,
4099 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004100 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004101 int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004102 int servicePid, int rotationOverride) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004103 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004104 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07004105 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004106 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004107 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004108 clientPid, clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004109 servicePid, rotationOverride),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004110 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004111{
Austin Borger22c5c852024-03-08 13:31:36 -08004112 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004113 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004114
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004115 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004116
username5755fea2018-12-27 09:48:08 +08004117 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004118
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004119 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004120}
4121
Mathias Agopian65ab4712010-07-14 17:59:35 -07004122// tear down the client
4123CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004124 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004125 mDestructionStarted = true;
4126
username5755fea2018-12-27 09:48:08 +08004127 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004128 // unconditionally disconnect. function is idempotent
4129 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004130}
4131
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004132sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4133
Igor Murashkin634a5152013-02-20 17:15:11 -08004134CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004135 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004136 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004137 const std::string& clientPackageName, bool nativeClient,
4138 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004139 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004140 int servicePid, int rotationOverride):
Austin Borger249e6592024-03-10 22:28:11 -07004141 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004142 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004143 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004144 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4145 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004146 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004147 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004148 mDisconnected(false), mUidIsTrusted(false),
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004149 mRotationOverride(rotationOverride),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004150 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004151 mRemoteBinder(remoteCallback),
4152 mOpsActive(false),
4153 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004154{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004155 if (sCameraService == nullptr) {
4156 sCameraService = cameraService;
4157 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004158
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004159 // There are 2 scenarios in which a client won't have AppOps operations
4160 // (both scenarios : native clients)
4161 // 1) It's an system native client*, the package name will be empty
4162 // and it will return from this function in the previous if condition
4163 // (This is the same as the previously existing behavior).
4164 // 2) It is a system native client, but its package name has been
4165 // modified for debugging, however it still must not use AppOps since
4166 // the package name is not a real one.
4167 //
4168 // * system native client - native client with UID < AID_APP_START. It
4169 // doesn't exclude clients not on the system partition.
4170 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004171 mAppOpsManager = std::make_unique<AppOpsManager>();
4172 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004173
Charles Chenf075f082024-03-04 23:32:55 +00004174 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004175}
4176
4177CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004178 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004179 mDestructionStarted = true;
4180}
4181
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004182binder::Status CameraService::BasicClient::disconnect() {
4183 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004184 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004185 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004186 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004187 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004188
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004189 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004190 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004191 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004192 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004193
4194 sp<IBinder> remote = getRemote();
4195 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004196 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004197 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004198
4199 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004200 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004201 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004202 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004203 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004204
Igor Murashkincba2c162013-03-20 15:56:31 -07004205 // client shouldn't be able to call into us anymore
4206 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004207
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004208 const auto& mActivityManager = getActivityManager();
4209 if (mActivityManager) {
4210 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004211 getCallingUid(),
4212 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004213 }
4214
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004215 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004216}
4217
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004218status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4219 // No dumping of clients directly over Binder,
4220 // must go through CameraService::dump
4221 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004222 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004223 return OK;
4224}
4225
Austin Borgered99f642023-06-01 16:51:35 -07004226status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004227 // Can't watch tags directly, must go through CameraService::startWatchingTags
4228 return OK;
4229}
4230
4231status_t CameraService::BasicClient::stopWatchingTags(int) {
4232 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4233 return OK;
4234}
4235
4236status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4237 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4238 return OK;
4239}
4240
Austin Borgered99f642023-06-01 16:51:35 -07004241std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004242 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004243}
4244
Emilian Peev8b64f282021-03-25 16:49:57 -07004245int CameraService::BasicClient::getCameraFacing() const {
4246 return mCameraFacing;
4247}
4248
4249int CameraService::BasicClient::getCameraOrientation() const {
4250 return mOrientation;
4251}
Ruben Brunkcc776712015-02-17 20:18:47 -08004252
4253int CameraService::BasicClient::getClientPid() const {
4254 return mClientPid;
4255}
4256
Ruben Brunk6267b532015-04-30 17:44:07 -07004257uid_t CameraService::BasicClient::getClientUid() const {
4258 return mClientUid;
4259}
4260
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004261bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4262 // Defaults to API2.
4263 return level == API_2;
4264}
4265
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004266status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004267 {
4268 Mutex::Autolock l(mAudioRestrictionLock);
4269 mAudioRestriction = mode;
4270 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004271 sCameraService->updateAudioRestriction();
4272 return OK;
4273}
4274
4275int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004276 return sCameraService->updateAudioRestriction();
4277}
4278
4279int32_t CameraService::BasicClient::getAudioRestriction() const {
4280 Mutex::Autolock l(mAudioRestrictionLock);
4281 return mAudioRestriction;
4282}
4283
4284bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4285 switch (mode) {
4286 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4287 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4288 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4289 return true;
4290 default:
4291 return false;
4292 }
4293}
4294
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004295status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4296 if (mode == AppOpsManager::MODE_ERRORED) {
4297 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004298 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004299 return PERMISSION_DENIED;
4300 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4301 // If the calling Uid is trusted (a native service), the AppOpsManager could
4302 // return MODE_IGNORED. Do not treat such case as error.
4303 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4304 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004305
4306 bool isCameraPrivacyEnabled;
4307 if (flags::camera_privacy_allowlist()) {
4308 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4309 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4310 } else {
4311 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004312 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004313 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004314 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4315 // We prefer to successfully open the camera and perform camera muting
4316 // or blocking in connectHelper as handleAppOpMode can be called before the
4317 // connection has been fully established and at that time camera muting
4318 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004319 if (!isUidActive || !isCameraPrivacyEnabled) {
Austin Borgerfd05d982024-04-22 15:54:50 -07004320 ALOGI("Camera %s: Access for \"%s\" has been restricted."
4321 "uid active: %s, privacy enabled: %s", mCameraIdStr.c_str(),
4322 mClientPackageName.c_str(), isUidActive ? "true" : "false",
4323 isCameraPrivacyEnabled ? "true" : "false");
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004324 // Return the same error as for device policy manager rejection
4325 return -EACCES;
4326 }
4327 }
4328 return OK;
4329}
4330
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004331status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004332 ATRACE_CALL();
4333
Igor Murashkine6800ce2013-03-04 17:25:57 -08004334 {
4335 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004336 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004337 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004338 if (mAppOpsManager != nullptr) {
4339 // Notify app ops that the camera is not available
4340 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004341
Austin Borger5755d9b2024-09-09 11:15:44 -07004342 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4343 toString16(mClientPackageName),
4344 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004345
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004346 // Just check for camera acccess here on open - delay startOp until
4347 // camera frames start streaming in startCameraStreamingOps
4348 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004349 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004350 status_t res = handleAppOpMode(mode);
4351 if (res != OK) {
4352 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004353 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004354 }
4355
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004356 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004357
4358 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004359 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004360
Austin Borgerdddb7552023-03-30 17:53:01 -07004361 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004362
Shuzhen Wang695044d2020-03-06 09:02:23 -08004363 // Notify listeners of camera open/close status
4364 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4365
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004366 return OK;
4367}
4368
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004369status_t CameraService::BasicClient::startCameraStreamingOps() {
4370 ATRACE_CALL();
4371
4372 if (!mOpsActive) {
4373 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4374 return INVALID_OPERATION;
4375 }
4376 if (mOpsStreaming) {
4377 ALOGV("%s: Streaming already active!", __FUNCTION__);
4378 return OK;
4379 }
4380
4381 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004382 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004383
4384 if (mAppOpsManager != nullptr) {
4385 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004386 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4387 toString16(mClientFeatureId),
4388 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004389 status_t res = handleAppOpMode(mode);
4390 if (res != OK) {
4391 return res;
4392 }
4393 }
4394
4395 mOpsStreaming = true;
4396
4397 return OK;
4398}
4399
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004400status_t CameraService::BasicClient::noteAppOp() {
4401 ATRACE_CALL();
4402
4403 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004404 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004405
4406 // noteAppOp is only used for when camera mute is not supported, in order
4407 // to trigger the sensor privacy "Unblock" dialog
4408 if (mAppOpsManager != nullptr) {
4409 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004410 toString16(mClientPackageName), toString16(mClientFeatureId),
4411 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004412 status_t res = handleAppOpMode(mode);
4413 if (res != OK) {
4414 return res;
4415 }
4416 }
4417
4418 return OK;
4419}
4420
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004421status_t CameraService::BasicClient::finishCameraStreamingOps() {
4422 ATRACE_CALL();
4423
4424 if (!mOpsActive) {
4425 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4426 return INVALID_OPERATION;
4427 }
4428 if (!mOpsStreaming) {
4429 ALOGV("%s: Streaming not active!", __FUNCTION__);
4430 return OK;
4431 }
4432
4433 if (mAppOpsManager != nullptr) {
4434 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004435 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004436 mOpsStreaming = false;
4437 }
4438
4439 return OK;
4440}
4441
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004442status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004443 ATRACE_CALL();
4444
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004445 if (mOpsStreaming) {
4446 // Make sure we've notified everyone about camera stopping
4447 finishCameraStreamingOps();
4448 }
4449
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004450 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004451 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004452 mOpsActive = false;
4453
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004454 // This function is called when a client disconnects. This should
4455 // release the camera, but actually only if it was in a proper
4456 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004457 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004458 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004459
Ruben Brunkcc776712015-02-17 20:18:47 -08004460 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004461 sCameraService->updateStatus(StatusInternal::PRESENT,
4462 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004463 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004464 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004465 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4466 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004467 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004468 mOpsCallback.clear();
4469
Austin Borgerdddb7552023-03-30 17:53:01 -07004470 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004471
Shuzhen Wang695044d2020-03-06 09:02:23 -08004472 // Notify listeners of camera open/close status
4473 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4474
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004475 return OK;
4476}
4477
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004478void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004479 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004480 if (mAppOpsManager == nullptr) {
4481 return;
4482 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004483 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004484 if (op != AppOpsManager::OP_CAMERA) {
4485 ALOGW("Unexpected app ops notification received: %d", op);
4486 return;
4487 }
4488
4489 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004490 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004491 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004492 ALOGV("checkOp returns: %d, %s ", res,
4493 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4494 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4495 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4496 "UNKNOWN");
4497
Shuzhen Wang64900852021-02-05 09:03:29 -08004498 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004499 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4500 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004501 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004502 } else if (res == AppOpsManager::MODE_IGNORED) {
4503 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004504
Austin Borgerca1e0062023-06-28 11:32:55 -07004505 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4506 // If not visible, but still active, then we want to block instead of muting the camera.
4507 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4508 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4509
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004510 bool isCameraPrivacyEnabled;
4511 if (flags::camera_privacy_allowlist()) {
4512 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4513 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4514 } else {
4515 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004516 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004517 }
4518
4519 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004520 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4521 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4522 isCameraPrivacyEnabled);
4523 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4524 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4525 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004526 if (!mUidIsTrusted) {
Austin Borger5755d9b2024-09-09 11:15:44 -07004527 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4528 setCameraMute(true);
Austin Borgerca1e0062023-06-28 11:32:55 -07004529 } else {
Austin Borger5755d9b2024-09-09 11:15:44 -07004530 block();
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004531 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004532 }
Evan Severson09ab4002021-02-10 14:15:19 -08004533 } else if (res == AppOpsManager::MODE_ALLOWED) {
4534 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004535 }
4536}
4537
Svet Ganova453d0d2018-01-11 15:37:58 -08004538void CameraService::BasicClient::block() {
4539 ATRACE_CALL();
4540
4541 // Reset the client PID to allow server-initiated disconnect,
4542 // and to prevent further calls by client.
Austin Borger22c5c852024-03-08 13:31:36 -08004543 mClientPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004544 CaptureResultExtras resultExtras; // a dummy result (invalid)
4545 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4546 disconnect();
4547}
4548
Mathias Agopian65ab4712010-07-14 17:59:35 -07004549// ----------------------------------------------------------------------------
4550
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004551void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004552 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004553 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004554 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4555 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4556 api1ErrorCode = CAMERA_ERROR_DISABLED;
4557 }
4558 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004559 } else {
4560 ALOGE("mRemoteCallback is NULL!!");
4561 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004562}
4563
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004564// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004565binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004566 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004567 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004568}
4569
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004570bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4571 return level == API_1;
4572}
4573
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004574CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4575 mClient(client) {
4576}
4577
4578void CameraService::Client::OpsCallback::opChanged(int32_t op,
4579 const String16& packageName) {
4580 sp<BasicClient> client = mClient.promote();
4581 if (client != NULL) {
4582 client->opChanged(op, packageName);
4583 }
4584}
4585
Mathias Agopian65ab4712010-07-14 17:59:35 -07004586// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004587// UidPolicy
4588// ----------------------------------------------------------------------------
4589
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004590void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004591 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004592 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004593
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004594 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004595 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004596 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004597 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004598 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4599 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004600 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004601 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004602 if (res == OK) {
4603 mRegistered = true;
4604 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004605 } else {
4606 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004607 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004608}
4609
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004610void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004611 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004612 return;
4613 }
4614
4615 registerWithActivityManager();
4616}
4617
4618void CameraService::UidPolicy::registerSelf() {
4619 // Use check service to see if the activity service is available
4620 // If not available then register for notifications, instead of blocking
4621 // till the service is ready
4622 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004623 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004624 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004625 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004626 } else {
4627 registerWithActivityManager();
4628 }
4629}
4630
Svet Ganova453d0d2018-01-11 15:37:58 -08004631void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004632 Mutex::Autolock _l(mUidLock);
4633
Steven Moreland2f348142019-07-02 15:59:07 -07004634 mAm.unregisterUidObserver(this);
4635 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004636 mRegistered = false;
4637 mActiveUids.clear();
4638 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004639}
4640
4641void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4642 onUidIdle(uid, disabled);
4643}
4644
4645void CameraService::UidPolicy::onUidActive(uid_t uid) {
4646 Mutex::Autolock _l(mUidLock);
4647 mActiveUids.insert(uid);
4648}
4649
4650void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4651 bool deleted = false;
4652 {
4653 Mutex::Autolock _l(mUidLock);
4654 if (mActiveUids.erase(uid) > 0) {
4655 deleted = true;
4656 }
4657 }
4658 if (deleted) {
4659 sp<CameraService> service = mService.promote();
4660 if (service != nullptr) {
4661 service->blockClientsForUid(uid);
4662 }
4663 }
4664}
4665
Emilian Peev53722fa2019-02-22 17:47:20 -08004666void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004667 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004668 bool procStateChange = false;
4669 {
4670 Mutex::Autolock _l(mUidLock);
4671 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4672 mMonitoredUids[uid].procState != procState) {
4673 mMonitoredUids[uid].procState = procState;
4674 procStateChange = true;
4675 }
4676 }
4677
4678 if (procStateChange) {
4679 sp<CameraService> service = mService.promote();
4680 if (service != nullptr) {
4681 service->notifyMonitoredUids();
4682 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004683 }
4684}
4685
Austin Borgerdddb7552023-03-30 17:53:01 -07004686/**
4687 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4688 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4689 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4690 * monitoredUids. If it is revised above some other monitoredUid, signal
4691 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4692 * foreground apps in split screen - state changes will capture all other cases.
4693 */
4694void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4695 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004696 {
4697 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004698 auto it = mMonitoredUids.find(uid);
4699
4700 if (it != mMonitoredUids.end()) {
4701 if (it->second.hasCamera) {
4702 for (auto &monitoredUid : mMonitoredUids) {
4703 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004704 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004705 notifyUidSet.emplace(monitoredUid.first);
4706 }
4707 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004708 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004709 notifyUidSet.emplace(uid);
4710 } else {
4711 for (auto &monitoredUid : mMonitoredUids) {
4712 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
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 }
4716 }
4717 }
4718 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004719 }
4720 }
4721
Austin Borgerdddb7552023-03-30 17:53:01 -07004722 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004723 sp<CameraService> service = mService.promote();
4724 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004725 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004726 }
4727 }
4728}
4729
Austin Borgerdddb7552023-03-30 17:53:01 -07004730/**
4731 * Register a uid for monitoring, and note whether it owns a camera.
4732 */
4733void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004734 Mutex::Autolock _l(mUidLock);
4735 auto it = mMonitoredUids.find(uid);
4736 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004737 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004738 } else {
Austin Borger65577682022-02-17 00:25:43 +00004739 MonitoredUid monitoredUid;
4740 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004741 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004742 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004743 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004744 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004745 if (res != OK) {
4746 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4747 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004748 }
4749
4750 if (openCamera) {
4751 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004752 }
4753}
4754
Austin Borgerdddb7552023-03-30 17:53:01 -07004755/**
4756 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4757 */
4758void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004759 Mutex::Autolock _l(mUidLock);
4760 auto it = mMonitoredUids.find(uid);
4761 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004762 it->second.refCount--;
4763 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004764 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004765 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004766 if (res != OK) {
4767 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4768 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004769 } else if (closeCamera) {
4770 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004771 }
4772 } else {
4773 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4774 }
4775}
4776
Austin Borgered99f642023-06-01 16:51:35 -07004777bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004778 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004779 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004780}
4781
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004782static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4783static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004784
Austin Borgered99f642023-06-01 16:51:35 -07004785bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004786 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004787 // If activity manager is unreachable, assume everything is active
4788 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004789 return true;
4790 }
4791 auto it = mOverrideUids.find(uid);
4792 if (it != mOverrideUids.end()) {
4793 return it->second;
4794 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004795 bool active = mActiveUids.find(uid) != mActiveUids.end();
4796 if (!active) {
4797 // We want active UIDs to always access camera with their first attempt since
4798 // there is no guarantee the app is robustly written and would retry getting
4799 // the camera on failure. The inverse case is not a problem as we would take
4800 // camera away soon once we get the callback that the uid is no longer active.
4801 ActivityManager am;
4802 // Okay to access with a lock held as UID changes are dispatched without
4803 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004804 int64_t startTimeMillis = 0;
4805 do {
4806 // TODO: Fix this b/109950150!
4807 // Okay this is a hack. There is a race between the UID turning active and
4808 // activity being resumed. The proper fix is very risky, so we temporary add
4809 // some polling which should happen pretty rarely anyway as the race is hard
4810 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004811 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004812 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004813 if (active) {
4814 break;
4815 }
4816 if (startTimeMillis <= 0) {
4817 startTimeMillis = uptimeMillis();
4818 }
4819 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004820 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004821 if (remainingTimeMillis <= 0) {
4822 break;
4823 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004824 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4825
4826 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004827 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004828 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004829 } while (true);
4830
Svet Ganov7b4ab782018-03-25 12:48:10 -07004831 if (active) {
4832 // Now that we found out the UID is actually active, cache that
4833 mActiveUids.insert(uid);
4834 }
4835 }
4836 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004837}
4838
Varun Shahb42f1eb2019-04-16 14:45:13 -07004839int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4840 Mutex::Autolock _l(mUidLock);
4841 return getProcStateLocked(uid);
4842}
4843
4844int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4845 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4846 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004847 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004848 }
4849 return procState;
4850}
4851
Austin Borgered99f642023-06-01 16:51:35 -07004852void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4853 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004854 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004855}
4856
Austin Borgered99f642023-06-01 16:51:35 -07004857void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004858 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004859}
4860
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004861void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4862 Mutex::Autolock _l(mUidLock);
4863 ALOGV("UidPolicy: ActivityManager has died");
4864 mRegistered = false;
4865 mActiveUids.clear();
4866}
4867
Austin Borgered99f642023-06-01 16:51:35 -07004868void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004869 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004870 bool wasActive = false;
4871 bool isActive = false;
4872 {
4873 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004874 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004875 mOverrideUids.erase(uid);
4876 if (insert) {
4877 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4878 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004879 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004880 }
4881 if (wasActive != isActive && !isActive) {
4882 sp<CameraService> service = mService.promote();
4883 if (service != nullptr) {
4884 service->blockClientsForUid(uid);
4885 }
4886 }
4887}
4888
4889// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004890// SensorPrivacyPolicy
4891// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004892
4893void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4894{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004895 Mutex::Autolock _l(mSensorPrivacyLock);
4896 if (mRegistered) {
4897 return;
4898 }
Evan Severson09ab4002021-02-10 14:15:19 -08004899 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004900 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004901 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004902 mSpm.addToggleSensorPrivacyListener(this);
4903 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004904 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004905 if (flags::camera_privacy_allowlist()) {
4906 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
4907 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
4908 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4909 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004910 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004911 if (res == OK) {
4912 mRegistered = true;
4913 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4914 }
4915}
4916
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004917void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4918 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004919 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004920 return;
4921 }
4922
4923 registerWithSensorPrivacyManager();
4924}
4925
4926void CameraService::SensorPrivacyPolicy::registerSelf() {
4927 // Use checkservice to see if the sensor_privacy service is available
4928 // If service is not available then register for notification
4929 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004930 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004931 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004932 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004933 } else {
4934 registerWithSensorPrivacyManager();
4935 }
4936}
4937
Michael Grooverd1d435a2018-12-18 17:39:42 -08004938void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4939 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004940 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004941 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004942 mSpm.removeToggleSensorPrivacyListener(this);
4943 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004944 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004945 mRegistered = false;
4946 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4947}
4948
4949bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004950 if (!mRegistered) {
4951 registerWithSensorPrivacyManager();
4952 }
4953
Michael Grooverd1d435a2018-12-18 17:39:42 -08004954 Mutex::Autolock _l(mSensorPrivacyLock);
4955 return mSensorPrivacyEnabled;
4956}
4957
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004958int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
4959 if (!mRegistered) {
4960 registerWithSensorPrivacyManager();
4961 }
4962
4963 Mutex::Autolock _l(mSensorPrivacyLock);
4964 return mCameraPrivacyState;
4965}
4966
Evan Seversond0b69922022-01-27 10:47:34 -08004967bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004968 if (!hasCameraPrivacyFeature()) {
4969 return false;
4970 }
Evan Seversond0b69922022-01-27 10:47:34 -08004971 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004972}
4973
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004974bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
4975 if (!hasCameraPrivacyFeature()) {
Jyoti Bhayana5882b032024-04-26 11:18:58 -07004976 return false;
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004977 }
4978 return mSpm.isCameraPrivacyEnabled(packageName);
4979}
4980
Evan Seversond0b69922022-01-27 10:47:34 -08004981binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004982 int toggleType, int sensor, bool enabled) {
4983 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
4984 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
4985 {
4986 Mutex::Autolock _l(mSensorPrivacyLock);
4987 mSensorPrivacyEnabled = enabled;
4988 }
4989 // if sensor privacy is enabled then block all clients from accessing the camera
4990 if (enabled) {
4991 sp<CameraService> service = mService.promote();
4992 if (service != nullptr) {
4993 service->blockAllClients();
4994 }
4995 }
4996 }
4997 return binder::Status::ok();
4998}
4999
5000binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
5001 int, int sensor, int state) {
5002 if (!flags::camera_privacy_allowlist()
5003 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
5004 return binder::Status::ok();
5005 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08005006 {
5007 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005008 mCameraPrivacyState = state;
5009 }
5010 sp<CameraService> service = mService.promote();
5011 if (!service) {
5012 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005013 }
5014 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005015 if (state == SensorPrivacyManager::ENABLED) {
5016 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08005017 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005018 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005019 }
5020 return binder::Status::ok();
5021}
5022
5023void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
5024 Mutex::Autolock _l(mSensorPrivacyLock);
5025 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
5026 mRegistered = false;
5027}
5028
Evan Severson09ab4002021-02-10 14:15:19 -08005029bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08005030 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
5031 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5032 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
5033 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5034 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08005035}
5036
Michael Grooverd1d435a2018-12-18 17:39:42 -08005037// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005038// CameraState
5039// ----------------------------------------------------------------------------
5040
Austin Borgered99f642023-06-01 16:51:35 -07005041CameraService::CameraState::CameraState(const std::string& id, int cost,
5042 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005043 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005044 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005045 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005046
5047CameraService::CameraState::~CameraState() {}
5048
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005049CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005050 Mutex::Autolock lock(mStatusLock);
5051 return mStatus;
5052}
5053
Austin Borgered99f642023-06-01 16:51:35 -07005054std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005055 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005056 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005057 return res;
5058}
5059
Ruben Brunkcc776712015-02-17 20:18:47 -08005060CameraParameters CameraService::CameraState::getShimParams() const {
5061 return mShimParams;
5062}
5063
5064void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5065 mShimParams = params;
5066}
5067
5068int CameraService::CameraState::getCost() const {
5069 return mCost;
5070}
5071
Austin Borgered99f642023-06-01 16:51:35 -07005072std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005073 return mConflicting;
5074}
5075
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005076SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5077 return mSystemCameraKind;
5078}
5079
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005080bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5081 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5082 != mPhysicalCameras.end();
5083}
5084
Austin Borgered99f642023-06-01 16:51:35 -07005085bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005086 Mutex::Autolock lock(mStatusLock);
5087 auto result = mUnavailablePhysicalIds.insert(physicalId);
5088 return result.second;
5089}
5090
Austin Borgered99f642023-06-01 16:51:35 -07005091bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005092 Mutex::Autolock lock(mStatusLock);
5093 auto count = mUnavailablePhysicalIds.erase(physicalId);
5094 return count > 0;
5095}
5096
Austin Borgered99f642023-06-01 16:51:35 -07005097void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005098 Mutex::Autolock lock(mStatusLock);
5099 mClientPackage = clientPackage;
5100}
5101
Austin Borgered99f642023-06-01 16:51:35 -07005102std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005103 Mutex::Autolock lock(mStatusLock);
5104 return mClientPackage;
5105}
5106
Ruben Brunkcc776712015-02-17 20:18:47 -08005107// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005108// ClientEventListener
5109// ----------------------------------------------------------------------------
5110
5111void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005112 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005113 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005114 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005115 if (basicClient.get() != nullptr) {
5116 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005117 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005118 static_cast<int>(basicClient->getClientUid()));
5119 }
5120}
5121
5122void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005123 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005124 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005125 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005126 if (basicClient.get() != nullptr) {
5127 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005128 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005129 static_cast<int>(basicClient->getClientUid()));
5130 }
5131}
5132
Ruben Brunk99e69712015-05-26 17:25:07 -07005133// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005134// CameraClientManager
5135// ----------------------------------------------------------------------------
5136
Ruben Brunk99e69712015-05-26 17:25:07 -07005137CameraService::CameraClientManager::CameraClientManager() {
5138 setListener(std::make_shared<ClientEventListener>());
5139}
5140
Ruben Brunkcc776712015-02-17 20:18:47 -08005141CameraService::CameraClientManager::~CameraClientManager() {}
5142
5143sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005144 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005145 auto descriptor = get(id);
5146 if (descriptor == nullptr) {
5147 return sp<BasicClient>{nullptr};
5148 }
5149 return descriptor->getValue();
5150}
5151
Austin Borgered99f642023-06-01 16:51:35 -07005152std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005153 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005154 std::ostringstream ret;
5155 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005156 bool hasAny = false;
5157 for (auto& i : all) {
5158 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005159 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005160 int32_t cost = i->getCost();
5161 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005162 int32_t score = i->getPriority().getScore();
5163 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005164 auto conflicting = i->getConflicting();
5165 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005166 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005167 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005168 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005169 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005170 uid_t clientUid = clientSp->getClientUid();
5171 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005172 }
Austin Borgered99f642023-06-01 16:51:35 -07005173 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5174 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005175
Ruben Brunk6267b532015-04-30 17:44:07 -07005176 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005177 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005178 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005179 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005180 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005181 }
5182
Austin Borgered99f642023-06-01 16:51:35 -07005183 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005184 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005185 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005186 }
Austin Borgered99f642023-06-01 16:51:35 -07005187 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005188 }
Austin Borgered99f642023-06-01 16:51:35 -07005189 if (hasAny) ret << "\n";
5190 ret << "]\n";
Yi Kong3ac211f2024-08-12 07:31:44 +08005191 return ret.str();
Ruben Brunkcc776712015-02-17 20:18:47 -08005192}
5193
5194CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005195 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5196 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005197 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005198
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005199 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005200 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005201
Austin Borgered99f642023-06-01 16:51:35 -07005202 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005203 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5204 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005205}
5206
5207CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005208 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005209 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005210 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005211 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005212 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5213 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005214}
5215
5216// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005217// InjectionStatusListener
5218// ----------------------------------------------------------------------------
5219
5220void CameraService::InjectionStatusListener::addListener(
5221 const sp<ICameraInjectionCallback>& callback) {
5222 Mutex::Autolock lock(mListenerLock);
5223 if (mCameraInjectionCallback) return;
5224 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5225 if (res == OK) {
5226 mCameraInjectionCallback = callback;
5227 }
5228}
5229
5230void CameraService::InjectionStatusListener::removeListener() {
5231 Mutex::Autolock lock(mListenerLock);
5232 if (mCameraInjectionCallback == nullptr) {
5233 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5234 return;
5235 }
5236 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5237 mCameraInjectionCallback = nullptr;
5238}
5239
5240void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005241 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005242 if (mCameraInjectionCallback == nullptr) {
5243 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5244 return;
5245 }
Cliff Wud3a05312021-04-26 23:07:31 +08005246
5247 switch (err) {
5248 case -ENODEV:
5249 mCameraInjectionCallback->onInjectionError(
5250 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5251 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005252 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005253 break;
5254 case -EBUSY:
5255 mCameraInjectionCallback->onInjectionError(
5256 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5257 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005258 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005259 break;
5260 case DEAD_OBJECT:
5261 mCameraInjectionCallback->onInjectionError(
5262 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5263 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005264 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005265 break;
5266 case INVALID_OPERATION:
5267 mCameraInjectionCallback->onInjectionError(
5268 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5269 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005270 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005271 break;
5272 case UNKNOWN_TRANSACTION:
5273 mCameraInjectionCallback->onInjectionError(
5274 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5275 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005276 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005277 break;
5278 default:
5279 mCameraInjectionCallback->onInjectionError(
5280 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5281 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005282 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005283 }
Cliff Wud8cae102021-03-11 01:37:42 +08005284}
5285
5286void CameraService::InjectionStatusListener::binderDied(
5287 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005288 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5289 auto parent = mParent.promote();
5290 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005291 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5292 if (clientDescriptor != nullptr) {
5293 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5294 baseClientPtr->stopInjection();
5295 }
Cliff Wu3b268182021-07-06 15:44:43 +08005296 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005297 }
5298}
5299
5300// ----------------------------------------------------------------------------
5301// CameraInjectionSession
5302// ----------------------------------------------------------------------------
5303
5304binder::Status CameraService::CameraInjectionSession::stopInjection() {
5305 Mutex::Autolock lock(mInjectionSessionLock);
5306 auto parent = mParent.promote();
5307 if (parent == nullptr) {
5308 ALOGE("CameraInjectionSession: Parent is gone");
5309 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5310 "Camera service encountered error");
5311 }
Cliff Wud3a05312021-04-26 23:07:31 +08005312
5313 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005314 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5315 if (clientDescriptor != nullptr) {
5316 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5317 res = baseClientPtr->stopInjection();
5318 if (res != OK) {
5319 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5320 " ret != NO_ERROR: %d", res);
5321 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5322 "Camera session encountered error");
5323 }
5324 }
Cliff Wu3b268182021-07-06 15:44:43 +08005325 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005326 return binder::Status::ok();
5327}
5328
5329// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005330
5331static const int kDumpLockRetries = 50;
5332static const int kDumpLockSleep = 60000;
5333
5334static bool tryLock(Mutex& mutex)
5335{
5336 bool locked = false;
5337 for (int i = 0; i < kDumpLockRetries; ++i) {
5338 if (mutex.tryLock() == NO_ERROR) {
5339 locked = true;
5340 break;
5341 }
5342 usleep(kDumpLockSleep);
5343 }
5344 return locked;
5345}
5346
Rucha Katakwardf223072021-06-15 10:21:00 -07005347void CameraService::cacheDump() {
5348 if (mMemFd != -1) {
5349 const Vector<String16> args;
5350 ATRACE_CALL();
5351 // Acquiring service lock here will avoid the deadlock since
5352 // cacheDump will not be called during the second disconnect.
5353 Mutex::Autolock lock(mServiceLock);
5354
5355 Mutex::Autolock l(mCameraStatesLock);
5356 // Start collecting the info for open sessions and store it in temp file.
5357 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005358 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005359 auto clientDescriptor = mActiveClientManager.get(cameraId);
5360 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005361 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005362 // Log the current open session info before device is disconnected.
5363 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5364 }
5365 }
5366 }
5367}
5368
Mathias Agopian65ab4712010-07-14 17:59:35 -07005369status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005370 ATRACE_CALL();
5371
Austin Borgered99f642023-06-01 16:51:35 -07005372 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005373 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005374 getCallingPid(),
5375 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005376 return NO_ERROR;
5377 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005378 bool locked = tryLock(mServiceLock);
5379 // failed to lock - CameraService is probably deadlocked
5380 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005381 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005382 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005383
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005384 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005385 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005386
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005387 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005388 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005389
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005390 if (locked) mServiceLock.unlock();
5391 return NO_ERROR;
5392 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005393 dprintf(fd, "\n== Service global info: ==\n\n");
5394 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005395 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005396 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5397 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005398 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5399 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5400 }
Austin Borgered99f642023-06-01 16:51:35 -07005401 std::string activeClientString = mActiveClientManager.toString();
5402 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5403 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005404 if (mStreamUseCaseOverrides.size() > 0) {
5405 dprintf(fd, "Active stream use case overrides:");
5406 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5407 dprintf(fd, " %" PRId64, useCaseOverride);
5408 }
5409 dprintf(fd, "\n");
5410 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005411
5412 dumpEventLog(fd);
5413
5414 bool stateLocked = tryLock(mCameraStatesLock);
5415 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005416 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005417 }
5418
Emilian Peevbd8c5032018-02-14 23:05:40 +00005419 int argSize = args.size();
5420 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005421 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005422 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005423 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005424 }
5425 break;
5426 }
5427 }
5428
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005429 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005430 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005431
Austin Borgered99f642023-06-01 16:51:35 -07005432 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005433
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005434 CameraParameters p = state.second->getShimParams();
5435 if (!p.isEmpty()) {
5436 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5437 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005438 }
5439
5440 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005441 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005442 // log the current open session info
5443 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005444 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005445 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005446 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005447
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005448 }
5449
5450 if (stateLocked) mCameraStatesLock.unlock();
5451
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005452 if (locked) mServiceLock.unlock();
5453
Emilian Peevf53f66e2017-04-11 14:29:43 +01005454 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005455
5456 dprintf(fd, "\n== Vendor tags: ==\n\n");
5457
5458 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5459 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005460 sp<VendorTagDescriptorCache> cache =
5461 VendorTagDescriptorCache::getGlobalVendorTagCache();
5462 if (cache == NULL) {
5463 dprintf(fd, "No vendor tags.\n");
5464 } else {
5465 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5466 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005467 } else {
5468 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5469 }
5470
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005471 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005472 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005473 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005474
5475 // Process dump arguments, if any
5476 int n = args.size();
5477 String16 verboseOption("-v");
5478 String16 unreachableOption("--unreachable");
5479 for (int i = 0; i < n; i++) {
5480 if (args[i] == verboseOption) {
5481 // change logging level
5482 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005483 std::string levelStr = toStdString(args[i+1]);
5484 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005485 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005486 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005487 } else if (args[i] == unreachableOption) {
5488 // Dump memory analysis
5489 // TODO - should limit be an argument parameter?
5490 UnreachableMemoryInfo info;
5491 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5492 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005493 dprintf(fd, "\n== Unable to dump unreachable memory. "
5494 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005495 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005496 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005497 std::string s = info.ToString(/*log_contents*/ true);
5498 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005499 }
5500 }
5501 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005502
5503 bool serviceLocked = tryLock(mServiceLock);
5504
5505 // Dump info from previous open sessions.
5506 // Reposition the offset to beginning of the file before reading
5507
5508 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5509 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5510 ssize_t size_read;
5511 char buf[4096];
5512 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5513 // Read data from file to a small buffer and write it to fd.
5514 write(fd, buf, size_read);
5515 if (size_read == -1) {
5516 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5517 break;
5518 }
5519 }
5520 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5521 } else {
5522 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5523 }
5524
5525 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005526 return NO_ERROR;
5527}
5528
Rucha Katakwardf223072021-06-15 10:21:00 -07005529void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005530 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005531 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005532 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005533 getFormattedCurrentTime().c_str(),
5534 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005535 dprintf(fd, " Client priority score: %d state: %d\n",
5536 clientDescriptor->getPriority().getScore(),
5537 clientDescriptor->getPriority().getState());
5538 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5539
5540 auto client = clientDescriptor->getValue();
5541 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005542 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005543
5544 client->dumpClient(fd, args);
5545}
5546
Austin Borgered99f642023-06-01 16:51:35 -07005547void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005548 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005549 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005550}
5551
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005552void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005553 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005554
5555 Mutex::Autolock l(mLogLock);
5556 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005557 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005558 }
5559
5560 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005561 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005562 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005563 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005564 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005565 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005566}
5567
Austin Borgered99f642023-06-01 16:51:35 -07005568void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005569 Mutex::Autolock lock(mLogLock);
5570 if (!isClientWatchedLocked(client)) { return; }
5571
5572 std::vector<std::string> dumpVector;
5573 client->dumpWatchedEventsToVector(dumpVector);
5574
5575 if (dumpVector.empty()) { return; }
5576
Austin Borgered99f642023-06-01 16:51:35 -07005577 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005578
Austin Borgered99f642023-06-01 16:51:35 -07005579 std::string currentTime = getFormattedCurrentTime();
5580 dumpString << "Cached @ ";
5581 dumpString << currentTime;
5582 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005583
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005584 size_t i = dumpVector.size();
5585
5586 // Store the string in reverse order (latest last)
5587 while (i > 0) {
5588 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005589 dumpString << cameraId;
5590 dumpString << ":";
5591 dumpString << client->getPackageName();
5592 dumpString << " ";
5593 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005594 }
5595
Austin Borgered99f642023-06-01 16:51:35 -07005596 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005597}
5598
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005599void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005600 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005601 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5602 if (mTorchClientMap[i] == who) {
5603 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005604 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005605 status_t res = mFlashlight->setTorchMode(cameraId, false);
5606 if (res) {
5607 ALOGE("%s: torch client died but couldn't turn off torch: "
5608 "%s (%d)", __FUNCTION__, strerror(-res), res);
5609 return;
5610 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005611 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005612 break;
5613 }
5614 }
5615}
5616
Ruben Brunkcc776712015-02-17 20:18:47 -08005617/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005618
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005619 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005620 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5621 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005622 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005623 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005624 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005625
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005626 // check torch client
5627 handleTorchClientBinderDied(who);
5628
5629 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005630 if(!evictClientIdByRemote(who)) {
5631 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005632 return;
5633 }
5634
Ruben Brunkcc776712015-02-17 20:18:47 -08005635 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5636 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005637}
5638
Austin Borgered99f642023-06-01 16:51:35 -07005639void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005640 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005641}
5642
Austin Borgered99f642023-06-01 16:51:35 -07005643void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005644 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005645 // Do not lock mServiceLock here or can get into a deadlock from
5646 // connect() -> disconnect -> updateStatus
5647
5648 auto state = getCameraState(cameraId);
5649
5650 if (state == nullptr) {
5651 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005652 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005653 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005654 }
5655
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005656 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5657 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5658 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005659 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005660 return;
5661 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005662
Biswarup Pal37a75182024-01-16 15:53:35 +00005663 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5664 CameraMetadata cameraInfo;
5665 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00005666 cameraId, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +00005667 if (res != OK) {
5668 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5669 __FUNCTION__, cameraId.c_str());
5670 } else {
5671 int32_t deviceId = getDeviceId(cameraInfo);
5672 if (deviceId != kDefaultDeviceId) {
5673 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5674 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5675 static_cast<camera_metadata_enum_android_lens_facing_t>(
5676 lensFacingEntry.data.u8[0]);
5677 std::string mappedCameraId;
5678 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5679 mappedCameraId = kVirtualDeviceBackCameraId;
5680 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5681 mappedCameraId = kVirtualDeviceFrontCameraId;
5682 } else {
5683 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5684 __func__);
5685 }
5686 if (!mappedCameraId.empty()) {
5687 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5688 }
5689 }
5690 }
5691 }
5692
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005693 // Collect the logical cameras without holding mStatusLock in updateStatus
5694 // as that can lead to a deadlock(b/162192331).
5695 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005696 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005697 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005698 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005699 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005700 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005701 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5702 auto [deviceId, mappedCameraId] =
5703 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005704
Biswarup Pal37a75182024-01-16 15:53:35 +00005705 if (status != StatusInternal::ENUMERATING) {
5706 // Update torch status if it has a flash unit.
5707 Mutex::Autolock al(mTorchStatusMutex);
5708 TorchModeStatus torchStatus;
5709 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5710 NAME_NOT_FOUND) {
5711 TorchModeStatus newTorchStatus =
5712 status == StatusInternal::PRESENT ?
5713 TorchModeStatus::AVAILABLE_OFF :
5714 TorchModeStatus::NOT_AVAILABLE;
5715 if (torchStatus != newTorchStatus) {
5716 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5717 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005718 }
5719 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005720
Biswarup Pal37a75182024-01-16 15:53:35 +00005721 Mutex::Autolock lock(mStatusListenerLock);
5722 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5723 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005724
Biswarup Pal37a75182024-01-16 15:53:35 +00005725 for (auto& listener : mListenerList) {
5726 bool isVendorListener = listener->isVendorListener();
5727 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5728 listener->getListenerPid(), listener->getListenerUid())) {
5729 ALOGV("Skipping discovery callback for system-only camera device %s",
5730 cameraId.c_str());
5731 continue;
5732 }
5733
5734 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5735 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005736 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005737 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005738 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5739 ret.exceptionCode());
5740 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005741 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005742}
5743
Austin Borgered99f642023-06-01 16:51:35 -07005744void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5745 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005746 auto state = getCameraState(cameraId);
5747 if (state == nullptr) {
5748 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005749 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005750 return;
5751 }
5752 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005753 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005754 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005755 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005756 }
5757
Biswarup Pal37a75182024-01-16 15:53:35 +00005758 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5759 auto [deviceId, mappedCameraId] =
5760 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5761
Shuzhen Wang695044d2020-03-06 09:02:23 -08005762 Mutex::Autolock lock(mStatusListenerLock);
5763
5764 for (const auto& it : mListenerList) {
5765 if (!it->isOpenCloseCallbackAllowed()) {
5766 continue;
5767 }
5768
5769 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005770 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005771 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5772 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005773 } else {
Biswarup Pal37a75182024-01-16 15:53:35 +00005774 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005775 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005776
5777 it->handleBinderStatus(ret,
5778 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5779 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005780 }
5781}
5782
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005783template<class Func>
5784void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005785 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005786 std::initializer_list<StatusInternal> rejectSourceStates,
5787 Func onStatusUpdatedLocked) {
5788 Mutex::Autolock lock(mStatusLock);
5789 StatusInternal oldStatus = mStatus;
5790 mStatus = status;
5791
5792 if (oldStatus == status) {
5793 return;
5794 }
5795
5796 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07005797 cameraId.c_str(), eToI(oldStatus), eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005798
5799 if (oldStatus == StatusInternal::NOT_PRESENT &&
5800 (status != StatusInternal::PRESENT &&
5801 status != StatusInternal::ENUMERATING)) {
5802
5803 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5804 __FUNCTION__);
5805 mStatus = oldStatus;
5806 return;
5807 }
5808
5809 /**
5810 * Sometimes we want to conditionally do a transition.
5811 * For example if a client disconnects, we want to go to PRESENT
5812 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5813 */
5814 for (auto& rejectStatus : rejectSourceStates) {
5815 if (oldStatus == rejectStatus) {
5816 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005817 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005818 mStatus = oldStatus;
5819 return;
5820 }
5821 }
5822
5823 onStatusUpdatedLocked(cameraId, status);
5824}
5825
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005826status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005827 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005828 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005829 if (!status) {
5830 return BAD_VALUE;
5831 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005832 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5833 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005834 // invalid camera ID or the camera doesn't have a flash unit
5835 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005836 }
5837
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005838 *status = mTorchStatusMap.valueAt(index);
5839 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005840}
5841
Austin Borgered99f642023-06-01 16:51:35 -07005842status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005843 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005844 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5845 if (index == NAME_NOT_FOUND) {
5846 return BAD_VALUE;
5847 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005848 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005849
5850 return OK;
5851}
5852
Austin Borgered99f642023-06-01 16:51:35 -07005853std::list<std::string> CameraService::getLogicalCameras(
5854 const std::string& physicalCameraId) {
5855 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005856 Mutex::Autolock lock(mCameraStatesLock);
5857 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005858 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5859 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005860 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005861 }
5862 return retList;
5863}
5864
5865void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005866 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00005867 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005868 // mStatusListenerLock is expected to be locked
5869 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005870 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005871 // Note: we check only the deviceKind of the physical camera id
5872 // since, logical camera ids and their physical camera ids are
5873 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005874 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5875 listener->getListenerPid(), listener->getListenerUid())) {
5876 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005877 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005878 continue;
5879 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005880 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00005881 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005882 listener->handleBinderStatus(ret,
5883 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5884 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5885 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005886 }
5887 }
5888}
5889
Svet Ganova453d0d2018-01-11 15:37:58 -08005890void CameraService::blockClientsForUid(uid_t uid) {
5891 const auto clients = mActiveClientManager.getAll();
5892 for (auto& current : clients) {
5893 if (current != nullptr) {
5894 const auto basicClient = current->getValue();
5895 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5896 basicClient->block();
5897 }
5898 }
5899 }
5900}
5901
Michael Grooverd1d435a2018-12-18 17:39:42 -08005902void CameraService::blockAllClients() {
5903 const auto clients = mActiveClientManager.getAll();
5904 for (auto& current : clients) {
5905 if (current != nullptr) {
5906 const auto basicClient = current->getValue();
5907 if (basicClient.get() != nullptr) {
5908 basicClient->block();
5909 }
5910 }
5911 }
5912}
5913
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005914void CameraService::blockPrivacyEnabledClients() {
5915 const auto clients = mActiveClientManager.getAll();
5916 for (auto& current : clients) {
5917 if (current != nullptr) {
5918 const auto basicClient = current->getValue();
5919 if (basicClient.get() != nullptr) {
5920 std::string pkgName = basicClient->getPackageName();
5921 bool cameraPrivacyEnabled =
5922 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
5923 if (cameraPrivacyEnabled) {
5924 basicClient->block();
5925 }
5926 }
5927 }
5928 }
5929}
5930
Svet Ganova453d0d2018-01-11 15:37:58 -08005931// NOTE: This is a remote API - make sure all args are validated
5932status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005933 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005934 return PERMISSION_DENIED;
5935 }
5936 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5937 return BAD_VALUE;
5938 }
Austin Borgered99f642023-06-01 16:51:35 -07005939 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005940 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005941 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005942 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005943 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005944 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005945 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005946 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005947 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005948 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005949 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005950 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005951 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005952 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005953 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005954 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005955 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005956 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005957 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005958 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005959 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005960 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005961 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005962 handleClearStreamUseCaseOverrides();
5963 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005964 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005965 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07005966 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005967 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07005968 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00005969 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07005970 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005971 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005972 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005973 }
5974 printHelp(err);
5975 return BAD_VALUE;
5976}
5977
5978status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005979 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005980
Svet Ganova453d0d2018-01-11 15:37:58 -08005981 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07005982 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005983 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07005984 } else if ((args[2] != toString16("idle"))) {
5985 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08005986 return BAD_VALUE;
5987 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005988
5989 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005990 if (args.size() >= 5 && args[3] == toString16("--user")) {
5991 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005992 }
5993
5994 uid_t uid;
5995 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5996 return BAD_VALUE;
5997 }
5998
5999 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08006000 return NO_ERROR;
6001}
6002
6003status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006004 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006005
6006 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006007 if (args.size() >= 4 && args[2] == toString16("--user")) {
6008 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006009 }
6010
6011 uid_t uid;
6012 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006013 return BAD_VALUE;
6014 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006015
6016 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08006017 return NO_ERROR;
6018}
6019
6020status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006021 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006022
6023 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006024 if (args.size() >= 4 && args[2] == toString16("--user")) {
6025 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006026 }
6027
6028 uid_t uid;
6029 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006030 return BAD_VALUE;
6031 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006032
6033 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006034 return dprintf(out, "active\n");
6035 } else {
6036 return dprintf(out, "idle\n");
6037 }
6038}
6039
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006040status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006041 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006042 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
6043 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
6044 Mutex::Autolock lock(mServiceLock);
6045
6046 mOverrideRotateAndCropMode = rotateValue;
6047
6048 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6049
6050 const auto clients = mActiveClientManager.getAll();
6051 for (auto& current : clients) {
6052 if (current != nullptr) {
6053 const auto basicClient = current->getValue();
6054 if (basicClient.get() != nullptr) {
6055 basicClient->setRotateAndCropOverride(rotateValue);
6056 }
6057 }
6058 }
6059
6060 return OK;
6061}
6062
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006063status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6064 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006065 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006066 if ((*end != '\0') ||
6067 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6068 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6069 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6070 return BAD_VALUE;
6071 }
6072
6073 Mutex::Autolock lock(mServiceLock);
6074 mOverrideAutoframingMode = autoframingValue;
6075
6076 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6077
6078 const auto clients = mActiveClientManager.getAll();
6079 for (auto& current : clients) {
6080 if (current != nullptr) {
6081 const auto basicClient = current->getValue();
6082 if (basicClient.get() != nullptr) {
6083 basicClient->setAutoframingOverride(autoframingValue);
6084 }
6085 }
6086 }
6087
6088 return OK;
6089}
6090
Ravneetaeb20dc2022-03-30 05:33:03 +00006091status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006092 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006093
6094 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6095
6096 Mutex::Autolock lock(mServiceLock);
6097
6098 mCameraServiceWatchdogEnabled = enableWatchdog;
6099
6100 const auto clients = mActiveClientManager.getAll();
6101 for (auto& current : clients) {
6102 if (current != nullptr) {
6103 const auto basicClient = current->getValue();
6104 if (basicClient.get() != nullptr) {
6105 basicClient->setCameraServiceWatchdog(enableWatchdog);
6106 }
6107 }
6108 }
6109
6110 return OK;
6111}
6112
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006113status_t CameraService::handleGetRotateAndCrop(int out) {
6114 Mutex::Autolock lock(mServiceLock);
6115
6116 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6117}
6118
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006119status_t CameraService::handleGetAutoframing(int out) {
6120 Mutex::Autolock lock(mServiceLock);
6121
6122 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6123}
6124
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006125status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6126 char *endPtr;
6127 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006128 std::string maskString = toStdString(args[1]);
6129 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006130
6131 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006132 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006133 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6134
6135 Mutex::Autolock lock(mServiceLock);
6136
6137 mImageDumpMask = maskValue;
6138
6139 return OK;
6140}
6141
6142status_t CameraService::handleGetImageDumpMask(int out) {
6143 Mutex::Autolock lock(mServiceLock);
6144
6145 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6146}
6147
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006148status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006149 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006150 if (errno != 0) return BAD_VALUE;
6151
6152 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6153 Mutex::Autolock lock(mServiceLock);
6154
6155 mOverrideCameraMuteMode = (muteValue == 1);
6156
6157 const auto clients = mActiveClientManager.getAll();
6158 for (auto& current : clients) {
6159 if (current != nullptr) {
6160 const auto basicClient = current->getValue();
6161 if (basicClient.get() != nullptr) {
6162 if (basicClient->supportsCameraMute()) {
6163 basicClient->setCameraMute(mOverrideCameraMuteMode);
6164 }
6165 }
6166 }
6167 }
6168
6169 return OK;
6170}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006171
Shuzhen Wang16610a62022-12-15 22:38:07 -08006172status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6173 std::vector<int64_t> useCasesOverride;
6174 for (size_t i = 1; i < args.size(); i++) {
6175 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006176 std::string arg = toStdString(args[i]);
6177 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006178 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006179 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006180 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006181 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006182 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006183 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006184 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006185 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006186 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006187 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006188 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006189 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006190 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6191 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006192 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006193 return BAD_VALUE;
6194 }
6195 useCasesOverride.push_back(useCase);
6196 }
6197
6198 Mutex::Autolock lock(mServiceLock);
6199 mStreamUseCaseOverrides = std::move(useCasesOverride);
6200
6201 return OK;
6202}
6203
6204void CameraService::handleClearStreamUseCaseOverrides() {
6205 Mutex::Autolock lock(mServiceLock);
6206 mStreamUseCaseOverrides.clear();
6207}
6208
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006209status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6210 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006211 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006212 if ((*end != '\0') ||
6213 (zoomOverrideValue != -1 &&
6214 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6215 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6216 return BAD_VALUE;
6217 }
6218
6219 Mutex::Autolock lock(mServiceLock);
6220 mZoomOverrideValue = zoomOverrideValue;
6221
6222 const auto clients = mActiveClientManager.getAll();
6223 for (auto& current : clients) {
6224 if (current != nullptr) {
6225 const auto basicClient = current->getValue();
6226 if (basicClient.get() != nullptr) {
6227 if (basicClient->supportsZoomOverride()) {
6228 basicClient->setZoomOverride(mZoomOverrideValue);
6229 }
6230 }
6231 }
6232 }
6233
6234 return OK;
6235}
6236
Avichal Rakesh84147132021-11-11 17:47:11 -08006237status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006238 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006239 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006240 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006241 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006242 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006243 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006244 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006245 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006246 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006247 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006248 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006249 dprintf(outFd, "Camera service watch commands:\n"
6250 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6251 " starts watching the provided tags for clients with provided package\n"
6252 " recognizes tag shorthands like '3a'\n"
6253 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006254 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006255 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006256 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006257 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006258 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006259 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006260 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006261}
6262
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006263status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6264 Mutex::Autolock lock(mLogLock);
6265 size_t tagsIdx; // index of '-m'
6266 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006267 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006268 if (tagsIdx < args.size() - 1) {
6269 tags = args[tagsIdx + 1];
6270 } else {
6271 dprintf(outFd, "No tags provided.\n");
6272 return BAD_VALUE;
6273 }
6274
6275 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006276 // watch all clients if no clients are provided
6277 String16 clients = toString16(kWatchAllClientsFlag);
6278 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006279 clientsIdx++);
6280 if (clientsIdx < args.size() - 1) {
6281 clients = args[clientsIdx + 1];
6282 }
Austin Borgered99f642023-06-01 16:51:35 -07006283 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006284
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006285 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006286 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006287
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006288 bool serviceLock = tryLock(mServiceLock);
6289 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006290 auto cameraClients = mActiveClientManager.getAll();
6291 for (const auto &clientDescriptor: cameraClients) {
6292 if (clientDescriptor == nullptr) { continue; }
6293 sp<BasicClient> client = clientDescriptor->getValue();
6294 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006295
6296 if (isClientWatchedLocked(client.get())) {
6297 client->startWatchingTags(mMonitorTags, outFd);
6298 numWatchedClients++;
6299 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006300 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006301 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6302
6303 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006304 return OK;
6305}
6306
6307status_t CameraService::stopWatchingTags(int outFd) {
6308 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006309 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006310 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006311
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006312 mWatchedClientPackages.clear();
6313 mWatchedClientsDumpCache.clear();
6314
6315 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006316 auto cameraClients = mActiveClientManager.getAll();
6317 for (const auto &clientDescriptor : cameraClients) {
6318 if (clientDescriptor == nullptr) { continue; }
6319 sp<BasicClient> client = clientDescriptor->getValue();
6320 if (client.get() == nullptr) { continue; }
6321 client->stopWatchingTags(outFd);
6322 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006323 dprintf(outFd, "Stopped watching all clients.\n");
6324 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006325 return OK;
6326}
6327
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006328status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6329 Mutex::Autolock lock(mLogLock);
6330 size_t clearedSize = mWatchedClientsDumpCache.size();
6331 mWatchedClientsDumpCache.clear();
6332 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6333 return OK;
6334}
6335
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006336status_t CameraService::printWatchedTags(int outFd) {
6337 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006338 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006339
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006340 bool printedSomething = false; // tracks if any monitoring information was printed
6341 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006342
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006343 bool serviceLock = tryLock(mServiceLock);
6344 // get all watched clients that are currently connected
6345 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6346 if (clientDescriptor == nullptr) { continue; }
6347
6348 sp<BasicClient> client = clientDescriptor->getValue();
6349 if (client.get() == nullptr) { continue; }
6350 if (!isClientWatchedLocked(client.get())) { continue; }
6351
6352 std::vector<std::string> dumpVector;
6353 client->dumpWatchedEventsToVector(dumpVector);
6354
6355 size_t printIdx = dumpVector.size();
6356 if (printIdx == 0) {
6357 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006358 }
6359
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006360 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006361 const std::string &cameraId = clientDescriptor->getKey();
6362 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006363 while(printIdx > 0) {
6364 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006365 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006366 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006367 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006368 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006369 printedSomething = true;
6370
6371 connectedMonitoredClients.emplace(client->getPackageName());
6372 }
6373 if (serviceLock) { mServiceLock.unlock(); }
6374
6375 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6376 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006377 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006378 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6379 continue;
6380 }
6381
Austin Borgered99f642023-06-01 16:51:35 -07006382 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006383 dprintf(outFd, "%s\n", kv.second.c_str());
6384 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006385 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006386
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006387 if (!printedSomething) {
6388 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006389 }
6390
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006391 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006392}
6393
Avichal Rakesh84147132021-11-11 17:47:11 -08006394// Print all events in vector `events' that came after lastPrintedEvent
6395void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006396 const std::string &cameraId,
6397 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006398 const std::vector<std::string> &events,
6399 const std::string &lastPrintedEvent) {
6400 if (events.empty()) { return; }
6401
6402 // index of lastPrintedEvent in events.
6403 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6404 size_t lastPrintedIdx;
6405 for (lastPrintedIdx = 0;
6406 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6407 lastPrintedIdx++);
6408
6409 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6410
Avichal Rakesh84147132021-11-11 17:47:11 -08006411 // print events in chronological order (latest event last)
6412 size_t idxToPrint = lastPrintedIdx;
6413 do {
6414 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006415 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6416 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006417 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006418}
6419
6420// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6421// command should be interrupted if the user presses the return key, or if user loses any way to
6422// signal interrupt.
6423// If timeoutMs == 0, this function will always return false
6424bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6425 struct timeval startTime;
6426 int startTimeError = gettimeofday(&startTime, nullptr);
6427 if (startTimeError) {
6428 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6429 return true;
6430 }
6431
6432 const nfds_t numFds = 1;
6433 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6434
6435 struct timeval currTime;
6436 char buffer[2];
6437 while(true) {
6438 int currTimeError = gettimeofday(&currTime, nullptr);
6439 if (currTimeError) {
6440 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6441 return true;
6442 }
6443
6444 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6445 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6446 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6447
6448 if (remainingTimeMs <= 0) {
6449 // No user interrupt within timeoutMs, don't interrupt watch command
6450 return false;
6451 }
6452
6453 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6454 if (numFdsUpdated < 0) {
6455 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6456 return true;
6457 }
6458
6459 if (numFdsUpdated == 0) {
6460 // No user input within timeoutMs, don't interrupt watch command
6461 return false;
6462 }
6463
6464 if (!(pollFd.revents & POLLIN)) {
6465 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6466 return true;
6467 }
6468
6469 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6470 if (sizeRead < 0) {
6471 dprintf(outFd, "Error reading user input. Exiting.\n");
6472 return true;
6473 }
6474
6475 if (sizeRead == 0) {
6476 // Reached end of input fd (can happen if input is piped)
6477 // User has no way to signal an interrupt, so interrupt here
6478 return true;
6479 }
6480
6481 if (buffer[0] == '\n') {
6482 // User pressed return, interrupt watch command.
6483 return true;
6484 }
6485 }
6486}
6487
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006488status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6489 int inFd, int outFd) {
6490 // Figure out refresh interval, if present in args
6491 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006492 if (args.size() > 2) {
6493 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006494 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006495 intervalIdx++);
6496
6497 size_t intervalValIdx = intervalIdx + 1;
6498 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006499 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006500 if (errno) { return BAD_VALUE; }
6501 }
6502 }
6503
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006504 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6505 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006506
Avichal Rakesh84147132021-11-11 17:47:11 -08006507 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006508 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006509
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006510 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006511 bool serviceLock = tryLock(mServiceLock);
6512 auto cameraClients = mActiveClientManager.getAll();
6513 if (serviceLock) { mServiceLock.unlock(); }
6514
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006515 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006516 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006517 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006518
6519 sp<BasicClient> client = clientDescriptor->getValue();
6520 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006521 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006522
Austin Borgered99f642023-06-01 16:51:35 -07006523 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006524 // This also initializes the map entries with an empty string
6525 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6526
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006527 std::vector<std::string> latestEvents;
6528 client->dumpWatchedEventsToVector(latestEvents);
6529
6530 if (!latestEvents.empty()) {
6531 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006532 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006533 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006534 latestEvents,
6535 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006536 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006537 }
6538 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006539 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006540 break;
6541 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006542 }
6543 return OK;
6544}
6545
Austin Borgered99f642023-06-01 16:51:35 -07006546void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006547 mWatchedClientPackages.clear();
6548
Austin Borgered99f642023-06-01 16:51:35 -07006549 std::istringstream iss(clients);
6550 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006551
Austin Borgered99f642023-06-01 16:51:35 -07006552 while (std::getline(iss, nextClient, ',')) {
6553 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006554 // Don't need to track any other package if 'all' is present
6555 mWatchedClientPackages.clear();
6556 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6557 break;
6558 }
6559
6560 // track package names
6561 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006562 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006563}
6564
Svet Ganova453d0d2018-01-11 15:37:58 -08006565status_t CameraService::printHelp(int out) {
6566 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006567 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6568 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6569 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006570 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6571 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6572 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006573 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6574 " Valid values 0=false, 1=true, 2=auto\n"
6575 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006576 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6577 " Valid values 0=OFF, 1=ON for JPEG\n"
6578 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006579 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006580 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6581 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6582 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6583 " on. In case the number of usecases is smaller than the number of streams, the\n"
6584 " last use case is assigned to all the remaining streams. In case of multiple\n"
6585 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6586 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6587 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6588 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006589 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6590 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006591 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6592 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006593 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006594 " help print this message\n");
6595}
6596
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006597bool CameraService::isClientWatched(const BasicClient *client) {
6598 Mutex::Autolock lock(mLogLock);
6599 return isClientWatchedLocked(client);
6600}
6601
6602bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6603 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6604 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6605}
6606
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006607int32_t CameraService::updateAudioRestriction() {
6608 Mutex::Autolock lock(mServiceLock);
6609 return updateAudioRestrictionLocked();
6610}
6611
6612int32_t CameraService::updateAudioRestrictionLocked() {
6613 int32_t mode = 0;
6614 // iterate through all active client
6615 for (const auto& i : mActiveClientManager.getAll()) {
6616 const auto clientSp = i->getValue();
6617 mode |= clientSp->getAudioRestriction();
6618 }
6619
6620 bool modeChanged = (mAudioRestriction != mode);
6621 mAudioRestriction = mode;
6622 if (modeChanged) {
6623 mAppOps.setCameraAudioRestriction(mode);
6624 }
6625 return mode;
6626}
6627
Austin Borgered99f642023-06-01 16:51:35 -07006628status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006629 sp<BasicClient> clientSp) {
6630 std::unique_ptr<AutoConditionLock> lock =
6631 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6632 status_t res = NO_ERROR;
6633 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006634 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006635 mInjectionStatusListener->notifyInjectionError(
6636 externalCamId, UNKNOWN_TRANSACTION);
6637 clientSp->notifyError(
6638 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6639 CaptureResultExtras());
6640
6641 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6642 // other clients from connecting in mServiceLockWrapper if held
6643 mServiceLock.unlock();
6644
6645 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006646 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006647 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006648 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006649
6650 // Reacquire mServiceLock
6651 mServiceLock.lock();
6652 }
6653
6654 return res;
6655}
6656
Cliff Wud3a05312021-04-26 23:07:31 +08006657void CameraService::clearInjectionParameters() {
6658 {
6659 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006660 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006661 mInjectionInternalCamId = "";
6662 }
6663 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006664 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006665}
6666
Biswarup Pal37a75182024-01-16 15:53:35 +00006667} // namespace android