blob: 30f16c7636d0167a395fa4b7bf1b8c92cac5b0c2 [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());
Biswarup Pal37a75182024-01-16 15:53:35 +0000345
346 // Only cameras of the default device can be remapped to a different camera (using
347 // remapCameraIds method), so do the following only if the camera is associated with the
348 // default device.
349 if (deviceId == kDefaultDeviceId) {
350 // For the default device, also trigger the torch callbacks for cameras that were
351 // remapped to the current cameraId for the specific package that this listener belongs
352 // to.
353 std::vector<std::string> remappedCameraIds =
354 findOriginalIdsForRemappedCameraId(cameraId, i->getListenerUid());
355 for (auto &remappedCameraId: remappedCameraIds) {
356 ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
357 remappedCameraId, kDefaultDeviceId);
358 i->handleBinderStatus(ret,
359 "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
360 __FUNCTION__, i->getListenerUid(), i->getListenerPid(),
361 ret.exceptionCode());
362 }
malikakash82ed4352023-07-21 22:44:34 +0000363 }
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800364 }
365}
366
Mathias Agopian65ab4712010-07-14 17:59:35 -0700367CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800368 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800369 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800370 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800371 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700372}
373
Emilian Peevaee727d2017-05-04 16:35:48 +0100374void CameraService::onNewProviderRegistered() {
375 enumerateProviders();
376}
377
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700378void CameraService::filterAPI1SystemCameraLocked(
379 const std::vector<std::string> &normalDeviceIds) {
380 mNormalDeviceIdsWithoutSystemCamera.clear();
Biswarup Pal37a75182024-01-16 15:53:35 +0000381 for (auto &cameraId : normalDeviceIds) {
382 if (vd_flags::camera_device_awareness()) {
383 CameraMetadata cameraInfo;
384 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000385 cameraId, false, &cameraInfo,
386 hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +0000387 int32_t deviceId = kDefaultDeviceId;
388 if (res != OK) {
389 ALOGW("%s: Not able to get camera characteristics for camera id %s",
390 __FUNCTION__, cameraId.c_str());
391 } else {
392 deviceId = getDeviceId(cameraInfo);
393 }
394 // Cameras associated with non-default device id's (i.e., virtual cameras) can never be
395 // system cameras, so skip for non-default device id's.
396 if (deviceId != kDefaultDeviceId) {
397 continue;
398 }
399 }
400
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700401 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Biswarup Pal37a75182024-01-16 15:53:35 +0000402 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
403 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700404 continue;
405 }
406 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700407 // All system camera ids will necessarily come after public camera
408 // device ids as per the HAL interface contract.
409 break;
410 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000411 mNormalDeviceIdsWithoutSystemCamera.push_back(cameraId);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700412 }
413 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
414 mNormalDeviceIdsWithoutSystemCamera.size());
415}
416
Austin Borgered99f642023-06-01 16:51:35 -0700417status_t CameraService::getSystemCameraKind(const std::string& cameraId,
418 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700419 auto state = getCameraState(cameraId);
420 if (state != nullptr) {
421 *kind = state->getSystemCameraKind();
422 return OK;
423 }
424 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700425 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700426}
427
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800428void CameraService::updateCameraNumAndIds() {
429 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700430 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
431 // Excludes hidden secure cameras
432 mNumberOfCameras =
433 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
434 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800435 mNormalDeviceIds =
436 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700437 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800438}
439
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700440void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700441 // To claim to be S Performance primary cameras, the cameras must be
442 // backward compatible. So performance class primary camera Ids must be API1
443 // compatible.
444 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
445 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
446 int facing = -1;
447 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800448 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000449 getDeviceVersion(cameraId,
450 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
451 /*out*/&portraitRotation, /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700452 if (facing == -1) {
453 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
454 return;
455 }
456
457 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
458 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700459 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
460 if (res == OK) {
461 mPerfClassPrimaryCameraIds.insert(cameraId);
462 } else {
463 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
464 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
465 break;
466 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700467
468 if (facing == hardware::CAMERA_FACING_BACK) {
469 firstRearCameraSeen = true;
470 }
471 if (facing == hardware::CAMERA_FACING_FRONT) {
472 firstFrontCameraSeen = true;
473 }
474 }
475
476 if (firstRearCameraSeen && firstFrontCameraSeen) {
477 break;
478 }
479 }
480}
481
Austin Borgered99f642023-06-01 16:51:35 -0700482void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700483 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100484 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
485 if (res != OK) {
486 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
487 return;
488 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000489 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700490 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
491 if (res != OK) {
492 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
493 return;
494 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000495 std::vector<std::string> physicalCameraIds;
496 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700497 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100498 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700499 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100500 }
501
502 {
503 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700504 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000505 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100506 }
507
Austin Borgered99f642023-06-01 16:51:35 -0700508 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100509 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700510 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800511
Austin Borgered99f642023-06-01 16:51:35 -0700512 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100513 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800514
515 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700516 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100517}
518
Austin Borgered99f642023-06-01 16:51:35 -0700519void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800520 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700521 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100522 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700523 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100524 }
525
526 {
527 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700528 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100529 }
530}
531
Austin Borgered99f642023-06-01 16:51:35 -0700532void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800533 CameraDeviceStatus newHalStatus) {
534 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700535 cameraId.c_str(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700536
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800537 StatusInternal newStatus = mapToInternal(newHalStatus);
538
Austin Borgered99f642023-06-01 16:51:35 -0700539 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800540
541 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700542 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100543 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700544 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100545
546 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700547 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100548
Austin Borgered99f642023-06-01 16:51:35 -0700549 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700550 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700551 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700552 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700553 return;
554 }
555
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800556 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800557
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800558 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800559 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700560 return;
561 }
562
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800563 if (newStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000564 logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
565 oldStatus, newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800566 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
567 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700568 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000569 mVirtualDeviceCameraIdMapper.removeCamera(cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800570
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800571 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700572 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800573 // Don't do this in updateStatus to avoid deadlock over mServiceLock
574 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700575
Ruben Brunkcc776712015-02-17 20:18:47 -0800576 // Remove cached shim parameters
577 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700578
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800579 // Remove online as well as offline client from the list of active clients,
580 // if they are present
Austin Borgered99f642023-06-01 16:51:35 -0700581 clientToDisconnectOnline = removeClientLocked(cameraId);
582 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700583 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800584
Austin Borgered99f642023-06-01 16:51:35 -0700585 disconnectClient(cameraId, clientToDisconnectOnline);
586 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700587
Austin Borgered99f642023-06-01 16:51:35 -0700588 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800589 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800590 if (oldStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000591 logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
592 oldStatus, newStatus));
Ruben Brunka8ca9152015-04-07 14:23:40 -0700593 }
Austin Borgered99f642023-06-01 16:51:35 -0700594 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700595 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800596}
Igor Murashkincba2c162013-03-20 15:56:31 -0700597
Austin Borgered99f642023-06-01 16:51:35 -0700598void CameraService::onDeviceStatusChanged(const std::string& id,
599 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800600 CameraDeviceStatus newHalStatus) {
601 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700602 __FUNCTION__, id.c_str(), physicalId.c_str(), newHalStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800603
604 StatusInternal newStatus = mapToInternal(newHalStatus);
605
606 std::shared_ptr<CameraState> state = getCameraState(id);
607
608 if (state == nullptr) {
609 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700610 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800611 return;
612 }
613
614 StatusInternal logicalCameraStatus = state->getStatus();
615 if (logicalCameraStatus != StatusInternal::PRESENT &&
616 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
617 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Austin Borgered99f642023-06-01 16:51:35 -0700618 __FUNCTION__, physicalId.c_str(), newHalStatus, logicalCameraStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800619 return;
620 }
621
622 bool updated = false;
623 if (newStatus == StatusInternal::PRESENT) {
624 updated = state->removeUnavailablePhysicalId(physicalId);
625 } else {
626 updated = state->addUnavailablePhysicalId(physicalId);
627 }
628
629 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700630 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800631 if (newStatus == StatusInternal::PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000632 logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800633 } else {
Henri Chataingbcb99452023-11-01 17:40:30 +0000634 logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800635 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700636 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
637 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
638 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700639 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700640 return;
641 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800642 Mutex::Autolock lock(mStatusListenerLock);
643 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700644 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
645 listener->getListenerPid(), listener->getListenerUid())) {
646 ALOGV("Skipping discovery callback for system-only camera device %s",
647 id.c_str());
648 continue;
649 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700650 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Biswarup Pal37a75182024-01-16 15:53:35 +0000651 mapToInterface(newStatus), id, physicalId, kDefaultDeviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700652 listener->handleBinderStatus(ret,
653 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
654 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
655 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800656 }
657 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700658}
659
Austin Borgered99f642023-06-01 16:51:35 -0700660void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800661 if (clientToDisconnect.get() != nullptr) {
662 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700663 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800664 // Notify the client of disconnection
665 clientToDisconnect->notifyError(
666 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
667 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800668 clientToDisconnect->disconnect();
669 }
670}
671
Austin Borgered99f642023-06-01 16:51:35 -0700672void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800673 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700674 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
675 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
676 if (res != OK) {
677 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700678 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700679 return;
680 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800681 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700682 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800683}
684
Austin Borgered99f642023-06-01 16:51:35 -0700685void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700686 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
687 Mutex::Autolock al(mTorchStatusMutex);
688 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
689}
690
Austin Borgered99f642023-06-01 16:51:35 -0700691void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800692 int32_t newStrengthLevel) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000693 // Get the device id and app-visible camera id for the given HAL-visible camera id.
694 auto [deviceId, mappedCameraId] =
695 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
696
Rucha Katakwar38284522021-11-10 11:25:21 -0800697 Mutex::Autolock lock(mStatusListenerLock);
698 for (auto& i : mListenerList) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000699 auto ret = i->getListener()->onTorchStrengthLevelChanged(mappedCameraId,
700 newStrengthLevel, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700701 i->handleBinderStatus(ret,
702 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
703 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800704 }
705}
706
Austin Borgered99f642023-06-01 16:51:35 -0700707void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700708 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800709 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700710 __FUNCTION__, cameraId.c_str(), newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800711
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800712 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800713 status_t res = getTorchStatusLocked(cameraId, &status);
714 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700715 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700716 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800717 return;
718 }
719 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800720 return;
721 }
722
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800723 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800724 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800725 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
726 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800727 return;
728 }
729
Ruben Brunkcc776712015-02-17 20:18:47 -0800730 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700731 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700732 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700733 auto iter = mTorchUidMap.find(cameraId);
734 if (iter != mTorchUidMap.end()) {
735 int oldUid = iter->second.second;
736 int newUid = iter->second.first;
737 BatteryNotifier& notifier(BatteryNotifier::getInstance());
738 if (oldUid != newUid) {
739 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800740 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700741 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700742 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800743 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700744 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700745 }
746 iter->second.second = newUid;
747 } else {
748 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800749 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700750 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700751 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700752 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700753 }
754 }
755 }
756 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700757 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800758}
759
Austin Borger249e6592024-03-10 22:28:11 -0700760bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700761 // Returns false if this is not an automotive device type.
762 if (!isAutomotiveDevice())
763 return false;
764
765 // Returns false if no camera id is provided.
Austin Borger1c1bee02023-06-01 16:51:35 -0700766 if (cam_id.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700767 return false;
768
769 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
770 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
771 // This isn't a known camera ID, so it's not a system camera.
772 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
773 return false;
774 }
775
776 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
777 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
778 return false;
779 }
780
781 CameraMetadata cameraInfo;
782 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000783 cam_id, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700784 if (res != OK){
785 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
786 cam_id.c_str());
787 return false;
788 }
789
790 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
791 if (auto_location.count != 1)
792 return false;
793
794 uint8_t location = auto_location.data.u8[0];
795 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
796 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
797 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
798 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
799 return false;
800 }
801
802 return true;
803}
804
Biswarup Pal37a75182024-01-16 15:53:35 +0000805Status CameraService::getNumberOfCameras(int32_t type, int32_t deviceId, int32_t devicePolicy,
806 int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700807 ATRACE_CALL();
Biswarup Pal37a75182024-01-16 15:53:35 +0000808 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
809 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
810 *numCameras = mVirtualDeviceCameraIdMapper.getNumberOfCameras(deviceId);
811 return Status::ok();
812 }
813
Emilian Peevaee727d2017-05-04 16:35:48 +0100814 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700815 bool hasSystemCameraPermissions =
Austin Borger22c5c852024-03-08 13:31:36 -0800816 hasPermissionsForSystemCamera(std::string(), getCallingPid(),
817 getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700818 switch (type) {
819 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700820 if (hasSystemCameraPermissions) {
821 *numCameras = static_cast<int>(mNormalDeviceIds.size());
822 } else {
823 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
824 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800825 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700826 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700827 if (hasSystemCameraPermissions) {
828 *numCameras = mNumberOfCameras;
829 } else {
830 *numCameras = mNumberOfCamerasWithoutSystemCamera;
831 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800832 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700833 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800834 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700835 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800836 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
837 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700838 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800839 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700840}
841
malikakash73125c62023-07-21 22:44:34 +0000842Status CameraService::remapCameraIds(const hardware::CameraIdRemapping& cameraIdRemapping) {
Austin Borgered99f642023-06-01 16:51:35 -0700843 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -0800844 const int pid = getCallingPid();
845 const int uid = getCallingUid();
malikakash82ed4352023-07-21 22:44:34 +0000846 ALOGE("%s: Permission Denial: can't configure camera ID mapping pid=%d, uid=%d",
847 __FUNCTION__, pid, uid);
848 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
849 "Permission Denial: no permission to configure camera id mapping");
850 }
851 TCameraIdRemapping cameraIdRemappingMap{};
malikakash214f6e62023-08-10 23:50:56 +0000852 binder::Status parseStatus = parseCameraIdRemapping(cameraIdRemapping, &cameraIdRemappingMap);
malikakash82ed4352023-07-21 22:44:34 +0000853 if (!parseStatus.isOk()) {
854 return parseStatus;
855 }
856 remapCameraIds(cameraIdRemappingMap);
857 return Status::ok();
858}
859
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700860Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
Biswarup Pal37a75182024-01-16 15:53:35 +0000861 int32_t deviceId, int32_t devicePolicy,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700862 /* out */
863 hardware::camera2::impl::CameraMetadataNative* request) {
864 ATRACE_CALL();
865
866 if (!flags::feature_combination_query()) {
867 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
868 "Camera subsystem doesn't support this method!");
869 }
870 if (!mInitialized) {
871 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
872 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
873 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
874 }
875
Biswarup Pal37a75182024-01-16 15:53:35 +0000876 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
877 devicePolicy, getCallingUid());
878 if (!cameraIdOptional.has_value()) {
879 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
880 unresolvedCameraId.c_str(), deviceId);
881 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
882 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
883 }
884 std::string cameraId = cameraIdOptional.value();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700885
886 binder::Status res;
887 if (request == nullptr) {
888 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
889 "Camera %s: Error creating default request", cameraId.c_str());
890 return res;
891 }
892 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
893 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
894 cameraId, templateId, &tempId);
895 if (!res.isOk()) {
896 ALOGE("%s: Camera %s: failed to map request Template %d",
897 __FUNCTION__, cameraId.c_str(), templateId);
898 return res;
899 }
900
901 if (shouldRejectSystemCameraConnection(cameraId)) {
902 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
903 "request for system only device %s: ", cameraId.c_str());
904 }
905
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700906 CameraMetadata metadata;
907 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
908 if (err == OK) {
909 request->swap(metadata);
910 } else if (err == BAD_VALUE) {
911 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
912 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
913 cameraId.c_str(), templateId, strerror(-err), err);
914 } else {
915 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
916 "Camera %s: Error creating default request for template %d: %s (%d)",
917 cameraId.c_str(), templateId, strerror(-err), err);
918 }
919 return res;
920}
921
922Status CameraService::isSessionConfigurationWithParametersSupported(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700923 const std::string& unresolvedCameraId, int targetSdkVersion,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700924 const SessionConfiguration& sessionConfiguration,
Biswarup Pal37a75182024-01-16 15:53:35 +0000925 int32_t deviceId, int32_t devicePolicy,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700926 /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700927 ATRACE_CALL();
928
929 if (!flags::feature_combination_query()) {
930 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
931 "Camera subsystem doesn't support this method!");
932 }
933 if (!mInitialized) {
934 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
935 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
936 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
937 }
938
Biswarup Pal37a75182024-01-16 15:53:35 +0000939 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
940 devicePolicy, getCallingUid());
941 if (!cameraIdOptional.has_value()) {
942 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
943 unresolvedCameraId.c_str(), deviceId);
944 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
945 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
946 }
947 std::string cameraId = cameraIdOptional.value();
948
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700949 if (supported == nullptr) {
950 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
951 unresolvedCameraId.c_str());
952 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
953 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
954 }
955
956 if (shouldRejectSystemCameraConnection(cameraId)) {
957 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
958 "session configuration with parameters support for system only device %s: ",
959 cameraId.c_str());
960 }
961
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700962 bool overrideForPerfClass = flags::calculate_perf_override_during_session_support() &&
963 SessionConfigurationUtils::targetPerfClassPrimaryCamera(
964 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
965
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700966 return isSessionConfigurationWithParametersSupportedUnsafe(cameraId, sessionConfiguration,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700967 overrideForPerfClass, supported);
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700968}
969
970Status CameraService::isSessionConfigurationWithParametersSupportedUnsafe(
971 const std::string& cameraId, const SessionConfiguration& sessionConfiguration,
972 bool overrideForPerfClass, /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700973 *supported = false;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700974 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(
975 cameraId, sessionConfiguration, overrideForPerfClass,
976 /*checkSessionParams=*/true, supported);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700977 binder::Status res;
978 switch (ret) {
979 case OK:
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700980 // Expected. Do Nothing.
981 return Status::ok();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700982 case INVALID_OPERATION: {
983 std::string msg = fmt::sprintf(
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700984 "Camera %s: Session configuration with parameters supported query not "
985 "supported!",
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700986 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700987 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
988 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
989 *supported = false;
990 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700991 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700992 break;
993 case NAME_NOT_FOUND: {
994 std::string msg = fmt::sprintf("Camera %s: Unknown camera ID.", cameraId.c_str());
995 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
996 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
997 *supported = false;
998 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
999 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001000 break;
1001 default: {
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001002 std::string msg = fmt::sprintf(
1003 "Unable to retrieve session configuration support for camera "
1004 "device %s: Error: %s (%d)",
1005 cameraId.c_str(), strerror(-ret), ret);
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001006 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001007 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1008 *supported = false;
1009 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001010 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001011 break;
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001012 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001013}
1014
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001015Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001016 int targetSdkVersion, int rotationOverride,
Biswarup Pal37a75182024-01-16 15:53:35 +00001017 const SessionConfiguration& sessionConfiguration, int32_t deviceId, int32_t devicePolicy,
1018 /*out*/ CameraMetadata* outMetadata) {
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001019 ATRACE_CALL();
1020
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001021 if (outMetadata == nullptr) {
1022 std::string msg =
1023 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
1024 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1025 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1026 }
1027
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001028 if (!mInitialized) {
1029 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1030 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
1031 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
1032 }
1033
Biswarup Pal37a75182024-01-16 15:53:35 +00001034 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001035 devicePolicy, getCallingUid());
Biswarup Pal37a75182024-01-16 15:53:35 +00001036 if (!cameraIdOptional.has_value()) {
1037 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001038 unresolvedCameraId.c_str(), deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001039 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1040 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1041 }
1042 std::string cameraId = cameraIdOptional.value();
1043
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001044 if (shouldRejectSystemCameraConnection(cameraId)) {
1045 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1046 "Unable to retrieve camera"
1047 "characteristics for system only device %s: ",
1048 cameraId.c_str());
1049 }
1050
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001051 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1052 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001053 if (flags::check_session_support_before_session_char()) {
1054 bool sessionConfigSupported;
1055 Status res = isSessionConfigurationWithParametersSupportedUnsafe(
1056 cameraId, sessionConfiguration, overrideForPerfClass, &sessionConfigSupported);
1057 if (!res.isOk()) {
1058 // isSessionConfigurationWithParametersSupportedUnsafe should log what went wrong and
1059 // report the correct Status to send to the client. Simply forward the error to
1060 // the client.
1061 outMetadata->clear();
1062 return res;
1063 }
1064 if (!sessionConfigSupported) {
1065 std::string msg = fmt::sprintf(
1066 "Session configuration not supported for camera device %s.", cameraId.c_str());
1067 outMetadata->clear();
1068 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1069 }
1070 }
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001071
1072 status_t ret = mCameraProviderManager->getSessionCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001073 cameraId, sessionConfiguration, overrideForPerfClass, rotationOverride, outMetadata);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001074
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001075 switch (ret) {
1076 case OK:
1077 // Expected, no handling needed.
1078 break;
1079 case INVALID_OPERATION: {
1080 std::string msg = fmt::sprintf(
1081 "Camera %s: Session characteristics query not supported!",
1082 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001083 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001084 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1085 outMetadata->clear();
1086 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1087 }
1088 break;
1089 case NAME_NOT_FOUND: {
1090 std::string msg = fmt::sprintf(
1091 "Camera %s: Unknown camera ID.",
1092 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001093 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001094 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1095 outMetadata->clear();
1096 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001097 }
1098 break;
1099 default: {
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001100 std::string msg = fmt::sprintf(
1101 "Unable to retrieve session characteristics for camera device %s: "
1102 "Error: %s (%d)",
1103 cameraId.c_str(), strerror(-ret), ret);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001104 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001105 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1106 outMetadata->clear();
1107 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001108 }
1109 }
1110
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001111 return filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
1112}
1113
1114Status CameraService::filterSensitiveMetadataIfNeeded(
1115 const std::string& cameraId, CameraMetadata* metadata) {
1116 int callingPid = getCallingPid();
1117 int callingUid = getCallingUid();
1118
1119 if (callingPid == getpid()) {
1120 // Caller is cameraserver; no need to remove keys
1121 return Status::ok();
1122 }
1123
1124 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1125 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1126 ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
1127 metadata->clear();
1128 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1129 "Unable to retrieve camera kind for device %s", cameraId.c_str());
1130 }
1131 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
1132 // Attempting to query system only camera without system camera permission would have
1133 // failed the shouldRejectSystemCameraConnection in the caller. So if we get here
1134 // for a system only camera, then the caller has the required permission.
1135 // No need to remove keys
1136 return Status::ok();
1137 }
1138
1139 std::vector<int32_t> tagsRemoved;
Biswarup Pale506e732024-03-27 13:46:20 +00001140 // Get the device id that owns this camera.
1141 auto [cameraOwnerDeviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1142 cameraId);
1143 bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid,
1144 cameraOwnerDeviceId);
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001145 if (hasCameraPermission) {
1146 // Caller has camera permission; no need to remove keys
1147 return Status::ok();
1148 }
1149
1150 status_t ret = metadata->removePermissionEntries(
1151 mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1152 if (ret != OK) {
1153 metadata->clear();
1154 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1155 "Failed to remove camera characteristics needing camera permission "
1156 "for device %s:%s (%d)",
1157 cameraId.c_str(), strerror(-ret), ret);
1158 }
1159
1160 if (!tagsRemoved.empty()) {
1161 ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1162 tagsRemoved.data(), tagsRemoved.size());
1163 if (ret != OK) {
1164 metadata->clear();
1165 return STATUS_ERROR_FMT(
1166 ERROR_INVALID_OPERATION,
1167 "Failed to insert camera keys needing permission for device %s: %s (%d)",
1168 cameraId.c_str(), strerror(-ret), ret);
1169 }
1170 }
1171 return Status::ok();
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001172}
1173
malikakash82ed4352023-07-21 22:44:34 +00001174Status CameraService::parseCameraIdRemapping(
1175 const hardware::CameraIdRemapping& cameraIdRemapping,
malikakash214f6e62023-08-10 23:50:56 +00001176 /* out */ TCameraIdRemapping* cameraIdRemappingMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001177 std::string packageName;
1178 std::string cameraIdToReplace, updatedCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001179 for (const auto& packageIdRemapping: cameraIdRemapping.packageIdRemappings) {
malikakash82ed4352023-07-21 22:44:34 +00001180 packageName = packageIdRemapping.packageName;
malikakash0894f5b2023-08-10 22:46:47 +00001181 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001182 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1183 "CameraIdRemapping: Package name cannot be empty");
1184 }
malikakash214f6e62023-08-10 23:50:56 +00001185 if (packageIdRemapping.cameraIdsToReplace.size()
1186 != packageIdRemapping.updatedCameraIds.size()) {
malikakash82ed4352023-07-21 22:44:34 +00001187 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1188 "CameraIdRemapping: Mismatch in CameraId Remapping lists sizes for package %s",
malikakash73125c62023-07-21 22:44:34 +00001189 packageName.c_str());
malikakash82ed4352023-07-21 22:44:34 +00001190 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001191 for (size_t i = 0; i < packageIdRemapping.cameraIdsToReplace.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -07001192 cameraIdToReplace = packageIdRemapping.cameraIdsToReplace[i];
1193 updatedCameraId = packageIdRemapping.updatedCameraIds[i];
malikakash0894f5b2023-08-10 22:46:47 +00001194 if (cameraIdToReplace.empty() || updatedCameraId.empty()) {
malikakash214f6e62023-08-10 23:50:56 +00001195 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1196 "CameraIdRemapping: Camera Id cannot be empty for package %s",
Austin Borgered99f642023-06-01 16:51:35 -07001197 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001198 }
1199 if (cameraIdToReplace == updatedCameraId) {
1200 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1201 "CameraIdRemapping: CameraIdToReplace cannot be the same"
1202 " as updatedCameraId for %s",
Austin Borgered99f642023-06-01 16:51:35 -07001203 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001204 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001205
1206 // Do not allow any camera remapping that involves a virtual camera.
1207 auto [deviceIdForCameraToReplace, _] =
1208 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1209 cameraIdToReplace);
1210 if (deviceIdForCameraToReplace != kDefaultDeviceId) {
1211 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1212 "CameraIdRemapping: CameraIdToReplace cannot be a virtual camera");
1213 }
1214 [[maybe_unused]] auto [deviceIdForUpdatedCamera, unusedMappedCameraId] =
1215 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(updatedCameraId);
1216 if (deviceIdForUpdatedCamera != kDefaultDeviceId) {
1217 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1218 "CameraIdRemapping: UpdatedCameraId cannot be a virtual camera");
1219 }
1220
malikakash214f6e62023-08-10 23:50:56 +00001221 (*cameraIdRemappingMap)[packageName][cameraIdToReplace] = updatedCameraId;
malikakash82ed4352023-07-21 22:44:34 +00001222 }
1223 }
1224 return Status::ok();
1225}
1226
1227void CameraService::remapCameraIds(const TCameraIdRemapping& cameraIdRemapping) {
1228 // Acquire mServiceLock and prevent other clients from connecting
1229 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1230 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1231
malikakashedb38962023-09-06 00:03:35 +00001232 // Collect all existing clients for camera Ids that are being
1233 // remapped in the new cameraIdRemapping, but only if they were being used by a
1234 // targeted packageName.
malikakash82ed4352023-07-21 22:44:34 +00001235 std::vector<sp<BasicClient>> clientsToDisconnect;
Austin Borgered99f642023-06-01 16:51:35 -07001236 std::vector<std::string> cameraIdsToUpdate;
malikakash82ed4352023-07-21 22:44:34 +00001237 for (const auto& [packageName, injectionMap] : cameraIdRemapping) {
1238 for (auto& [id0, id1] : injectionMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001239 ALOGI("%s: UPDATE:= %s: %s: %s", __FUNCTION__, packageName.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001240 id0.c_str(), id1.c_str());
1241 auto clientDescriptor = mActiveClientManager.get(id0);
1242 if (clientDescriptor != nullptr) {
1243 sp<BasicClient> clientSp = clientDescriptor->getValue();
1244 if (clientSp->getPackageName() == packageName) {
malikakashedb38962023-09-06 00:03:35 +00001245 // This camera is being used by a targeted packageName and
1246 // being remapped to a new camera Id. We should disconnect it.
malikakash82ed4352023-07-21 22:44:34 +00001247 clientsToDisconnect.push_back(clientSp);
1248 cameraIdsToUpdate.push_back(id0);
1249 }
1250 }
1251 }
1252 }
1253
malikakashedb38962023-09-06 00:03:35 +00001254 for (auto& clientSp : clientsToDisconnect) {
malikakashf4c80f22023-09-25 21:50:28 +00001255 // Notify the clients about the disconnection.
1256 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
malikakashedb38962023-09-06 00:03:35 +00001257 CaptureResultExtras{});
1258 }
malikakash82ed4352023-07-21 22:44:34 +00001259
1260 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1261 // blocking other clients from connecting in mServiceLockWrapper if held.
1262 mServiceLock.unlock();
1263
malikakashedb38962023-09-06 00:03:35 +00001264 // Clear calling identity for disconnect() PID checks.
Austin Borger22c5c852024-03-08 13:31:36 -08001265 int64_t token = clearCallingIdentity();
malikakashedb38962023-09-06 00:03:35 +00001266
malikakash82ed4352023-07-21 22:44:34 +00001267 // Disconnect clients.
1268 for (auto& clientSp : clientsToDisconnect) {
malikakashedb38962023-09-06 00:03:35 +00001269 // This also triggers a call to updateStatus() which also reads mCameraIdRemapping
1270 // and requires mCameraIdRemappingLock.
malikakash82ed4352023-07-21 22:44:34 +00001271 clientSp->disconnect();
1272 }
1273
malikakashedb38962023-09-06 00:03:35 +00001274 // Invoke destructors (which call disconnect()) now while we don't hold the mServiceLock.
1275 clientsToDisconnect.clear();
1276
Austin Borger22c5c852024-03-08 13:31:36 -08001277 restoreCallingIdentity(token);
malikakash82ed4352023-07-21 22:44:34 +00001278 mServiceLock.lock();
malikakashedb38962023-09-06 00:03:35 +00001279
1280 {
1281 Mutex::Autolock lock(mCameraIdRemappingLock);
1282 // Update mCameraIdRemapping.
1283 mCameraIdRemapping.clear();
1284 mCameraIdRemapping.insert(cameraIdRemapping.begin(), cameraIdRemapping.end());
1285 }
malikakash82ed4352023-07-21 22:44:34 +00001286}
1287
malikakash22af94c2023-12-04 18:13:14 +00001288Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001289 const std::string& cameraId,
1290 const CameraMetadata& sessionParams) {
1291 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001292 const int pid = getCallingPid();
1293 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001294 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1295 __FUNCTION__, pid, uid);
1296 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1297 "Permission Denial: no permission to inject session params");
1298 }
1299
Biswarup Pal37a75182024-01-16 15:53:35 +00001300 // Do not allow session params injection for a virtual camera.
1301 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1302 if (deviceId != kDefaultDeviceId) {
1303 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1304 "Cannot inject session params for a virtual camera");
1305 }
1306
malikakash22af94c2023-12-04 18:13:14 +00001307 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1308 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1309
1310 auto clientDescriptor = mActiveClientManager.get(cameraId);
1311 if (clientDescriptor == nullptr) {
1312 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1313 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1314 "No active client for camera id %s", cameraId.c_str());
1315 }
1316
1317 sp<BasicClient> clientSp = clientDescriptor->getValue();
1318 status_t res = clientSp->injectSessionParams(sessionParams);
1319
1320 if (res != OK) {
1321 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1322 "Error injecting session params into camera \"%s\": %s (%d)",
1323 cameraId.c_str(), strerror(-res), res);
1324 }
1325 return Status::ok();
1326}
1327
Austin Borgered99f642023-06-01 16:51:35 -07001328std::vector<std::string> CameraService::findOriginalIdsForRemappedCameraId(
1329 const std::string& inputCameraId, int clientUid) {
1330 std::string packageName = getPackageNameFromUid(clientUid);
1331 std::vector<std::string> cameraIds;
malikakash82ed4352023-07-21 22:44:34 +00001332 Mutex::Autolock lock(mCameraIdRemappingLock);
1333 if (auto packageMapIter = mCameraIdRemapping.find(packageName);
1334 packageMapIter != mCameraIdRemapping.end()) {
1335 for (auto& [id0, id1]: packageMapIter->second) {
1336 if (id1 == inputCameraId) {
1337 cameraIds.push_back(id0);
1338 }
1339 }
1340 }
1341 return cameraIds;
1342}
1343
Austin Borgered99f642023-06-01 16:51:35 -07001344std::string CameraService::resolveCameraId(
1345 const std::string& inputCameraId,
malikakashedb38962023-09-06 00:03:35 +00001346 int clientUid,
Austin Borgered99f642023-06-01 16:51:35 -07001347 const std::string& packageName) {
1348 std::string packageNameVal = packageName;
malikakashedb38962023-09-06 00:03:35 +00001349 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001350 packageNameVal = getPackageNameFromUid(clientUid);
1351 }
malikakash65d20692023-09-07 01:06:33 +00001352 if (clientUid < AID_APP_START || packageNameVal.empty()) {
malikakashedb38962023-09-06 00:03:35 +00001353 // We shouldn't remap cameras for processes with system/vendor UIDs.
1354 return inputCameraId;
1355 }
malikakash82ed4352023-07-21 22:44:34 +00001356 Mutex::Autolock lock(mCameraIdRemappingLock);
1357 if (auto packageMapIter = mCameraIdRemapping.find(packageNameVal);
1358 packageMapIter != mCameraIdRemapping.end()) {
malikakash82ed4352023-07-21 22:44:34 +00001359 auto packageMap = packageMapIter->second;
1360 if (auto replacementIdIter = packageMap.find(inputCameraId);
1361 replacementIdIter != packageMap.end()) {
malikakashedb38962023-09-06 00:03:35 +00001362 ALOGI("%s: resolveCameraId: remapping cameraId %s for %s to %s",
malikakash82ed4352023-07-21 22:44:34 +00001363 __FUNCTION__, inputCameraId.c_str(),
malikakashedb38962023-09-06 00:03:35 +00001364 packageNameVal.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001365 replacementIdIter->second.c_str());
1366 return replacementIdIter->second;
1367 }
1368 }
1369 return inputCameraId;
1370}
1371
Biswarup Pal37a75182024-01-16 15:53:35 +00001372std::optional<std::string> CameraService::resolveCameraId(
1373 const std::string& inputCameraId,
1374 int32_t deviceId,
1375 int32_t devicePolicy,
1376 int clientUid,
1377 const std::string& packageName) {
1378 if ((deviceId == kDefaultDeviceId)
1379 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1380 auto [storedDeviceId, _] =
1381 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1382 if (storedDeviceId != kDefaultDeviceId) {
1383 // Trying to access a virtual camera from default-policy device context, we should fail.
1384 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1385 inputCameraId.c_str(), deviceId);
1386 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1387 return std::nullopt;
1388 }
1389 return resolveCameraId(inputCameraId, clientUid, packageName);
1390 }
1391
1392 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1393}
1394
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001395Status CameraService::getCameraInfo(int cameraId, int rotationOverride, int32_t deviceId,
Biswarup Pal37a75182024-01-16 15:53:35 +00001396 int32_t devicePolicy, CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001397 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001398 Mutex::Autolock l(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001399 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId, deviceId, devicePolicy);
1400 if (cameraIdStr.empty()) {
1401 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
1402 cameraId, deviceId);
1403 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1404 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1405 }
malikakashedb38962023-09-06 00:03:35 +00001406
Austin Borgered99f642023-06-01 16:51:35 -07001407 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001408 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1409 "characteristics for system only device %s: ", cameraIdStr.c_str());
1410 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001411
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001412 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001413 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001414 return STATUS_ERROR(ERROR_DISCONNECTED,
1415 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001416 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001417 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001418 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001419 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1420 if (hasSystemCameraPermissions) {
1421 cameraIdBound = mNumberOfCameras;
1422 }
1423 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001424 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1425 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001426 }
1427
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001428 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001429 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001430 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001431 cameraIdStr, rotationOverride, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001432 if (err != OK) {
1433 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1434 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1435 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001436 logServiceError(std::string("Error retrieving camera info from device ")
1437 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001438 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001439
Ruben Brunkcc776712015-02-17 20:18:47 -08001440 return ret;
1441}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001442
Biswarup Pal37a75182024-01-16 15:53:35 +00001443std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1444 int32_t deviceId, int32_t devicePolicy) {
1445 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1446 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1447 std::optional<std::string> cameraIdOptional =
1448 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1449 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1450 }
1451
1452 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001453 auto callingPid = getCallingPid();
1454 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001455 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1456 callingPid, callingUid, /* checkCameraPermissions= */ false);
1457 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001458 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001459 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001460 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1461 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1462 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001463 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001464 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001465
Biswarup Pal37a75182024-01-16 15:53:35 +00001466 std::string unresolvedCameraId = (*cameraIds)[cameraIdInt];
1467 return resolveCameraId(unresolvedCameraId, getCallingUid());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001468}
1469
Biswarup Pal37a75182024-01-16 15:53:35 +00001470std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1471 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001472 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001473 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001474}
1475
Austin Borgered99f642023-06-01 16:51:35 -07001476Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001477 int targetSdkVersion, int rotationOverride, int32_t deviceId, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +00001478 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001479 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001480
Zhijun He2b59be82013-09-25 10:14:30 -07001481 if (!cameraInfo) {
1482 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001483 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001484 }
1485
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001486 if (!mInitialized) {
1487 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001488 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001489 return STATUS_ERROR(ERROR_DISCONNECTED,
1490 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001491 }
1492
Biswarup Pal37a75182024-01-16 15:53:35 +00001493 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
1494 devicePolicy, getCallingUid());
1495 if (!cameraIdOptional.has_value()) {
1496 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1497 unresolvedCameraId.c_str(), deviceId);
1498 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1499 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1500 }
1501 std::string cameraId = cameraIdOptional.value();
1502
Austin Borgered99f642023-06-01 16:51:35 -07001503 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001504 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001505 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001506 }
1507
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001508 bool overrideForPerfClass =
1509 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001510 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001511 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001512 cameraId, overrideForPerfClass, cameraInfo, rotationOverride);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001513 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001514 if (res == NAME_NOT_FOUND) {
1515 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001516 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001517 strerror(-res), res);
1518 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001519 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1520 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001521 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001522 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001523 strerror(-res), res);
1524 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001525 }
Emilian Peeve20c6372018-08-14 18:45:53 +01001526
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001527 return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -07001528}
1529
Biswarup Pal37a75182024-01-16 15:53:35 +00001530Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId, int32_t deviceId,
1531 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001532 ATRACE_CALL();
1533 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001534
Biswarup Pal37a75182024-01-16 15:53:35 +00001535 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
1536 devicePolicy, getCallingUid());
1537 if (!cameraIdOptional.has_value()) {
1538 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1539 unresolvedCameraId.c_str(), deviceId);
1540 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1541 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1542 }
1543 std::string cameraId = cameraIdOptional.value();
1544
Rucha Katakwar38284522021-11-10 11:25:21 -08001545 if (!mInitialized) {
1546 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1547 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1548 }
1549
Biswarup Pal37a75182024-01-16 15:53:35 +00001550 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001551 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1552 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1553 }
1554
Austin Borgered99f642023-06-01 16:51:35 -07001555 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001556 if (res != OK) {
1557 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001558 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001559 strerror(-res), res);
1560 }
1561 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1562 return Status::ok();
1563}
1564
Austin Borgered99f642023-06-01 16:51:35 -07001565std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001566 time_t now = time(nullptr);
1567 char formattedTime[64];
1568 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001569 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001570}
1571
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001572Status CameraService::getCameraVendorTagDescriptor(
1573 /*out*/
1574 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001575 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001576 if (!mInitialized) {
1577 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001578 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001579 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001580 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1581 if (globalDescriptor != nullptr) {
1582 *desc = *(globalDescriptor.get());
1583 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001584 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001585}
1586
Emilian Peev71c73a22017-03-21 16:35:51 +00001587Status CameraService::getCameraVendorTagCache(
1588 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1589 ATRACE_CALL();
1590 if (!mInitialized) {
1591 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1592 return STATUS_ERROR(ERROR_DISCONNECTED,
1593 "Camera subsystem not available");
1594 }
1595 sp<VendorTagDescriptorCache> globalCache =
1596 VendorTagDescriptorCache::getGlobalVendorTagCache();
1597 if (globalCache != nullptr) {
1598 *cache = *(globalCache.get());
1599 }
1600 return Status::ok();
1601}
1602
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001603void CameraService::clearCachedVariables() {
1604 BasicClient::BasicClient::sCameraService = nullptr;
1605}
1606
Austin Borgered99f642023-06-01 16:51:35 -07001607std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001608 int rotationOverride, int* portraitRotation, int* facing,
1609 int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001610 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001611
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001612 int deviceVersion = 0;
1613
Emilian Peevf53f66e2017-04-11 14:29:43 +01001614 status_t res;
1615 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001616 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001617 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001618 if (res != OK || transport == IPCTransport::INVALID) {
1619 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001620 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001621 return std::make_pair(-1, IPCTransport::INVALID) ;
1622 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001623 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001624
Emilian Peevf53f66e2017-04-11 14:29:43 +01001625 hardware::CameraInfo info;
1626 if (facing) {
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001627 res = mCameraProviderManager->getCameraInfo(cameraId, rotationOverride,
Austin Borger18b30a72022-10-27 12:20:29 -07001628 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001629 if (res != OK) {
1630 return std::make_pair(-1, IPCTransport::INVALID);
1631 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001632 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001633 if (orientation) {
1634 *orientation = info.orientation;
1635 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001636 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001637
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001638 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001639}
1640
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001641Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001642 switch(err) {
1643 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001644 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001645 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001646 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1647 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001648 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001649 return STATUS_ERROR(ERROR_DISCONNECTED,
1650 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001651 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001652 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1653 "Camera HAL encountered error %d: %s",
1654 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001655 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001656}
1657
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001658Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001659 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1660 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001661 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001662 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001663 apiLevel effectiveApiLevel, bool overrideForPerfClass, int rotationOverride,
malikakash73125c62023-07-21 22:44:34 +00001664 bool forceSlowJpegMode, const std::string& originalCameraId,
1665 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001666 // For HIDL devices
1667 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1668 // Create CameraClient based on device version reported by the HAL.
1669 int deviceVersion = deviceVersionAndTransport.first;
1670 switch(deviceVersion) {
1671 case CAMERA_DEVICE_API_VERSION_1_0:
1672 ALOGE("Camera using old HAL version: %d", deviceVersion);
1673 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1674 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001675 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001676 break;
1677 case CAMERA_DEVICE_API_VERSION_3_0:
1678 case CAMERA_DEVICE_API_VERSION_3_1:
1679 case CAMERA_DEVICE_API_VERSION_3_2:
1680 case CAMERA_DEVICE_API_VERSION_3_3:
1681 case CAMERA_DEVICE_API_VERSION_3_4:
1682 case CAMERA_DEVICE_API_VERSION_3_5:
1683 case CAMERA_DEVICE_API_VERSION_3_6:
1684 case CAMERA_DEVICE_API_VERSION_3_7:
1685 break;
1686 default:
1687 // Should not be reachable
1688 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1689 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1690 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001691 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001692 }
1693 }
1694 if (effectiveApiLevel == API_1) { // Camera1 API route
1695 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001696 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001697 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001698 api1CameraId, facing, sensorOrientation,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001699 clientPid, clientUid, servicePid, overrideForPerfClass, rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00001700 forceSlowJpegMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001701 ALOGI("%s: Camera1 API (legacy), rotationOverride %d, forceSlowJpegMode %d",
1702 __FUNCTION__, rotationOverride, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001703 } else { // Camera2 API route
1704 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1705 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001706 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001707 cameraService->mCameraServiceProxyWrapper,
1708 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001709 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001710 overrideForPerfClass, rotationOverride, originalCameraId);
1711 ALOGI("%s: Camera2 API, rotationOverride %d", __FUNCTION__, rotationOverride);
Ruben Brunkcc776712015-02-17 20:18:47 -08001712 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001713 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001714}
1715
Austin Borgered99f642023-06-01 16:51:35 -07001716std::string CameraService::toString(std::set<userid_t> intSet) {
1717 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001718 bool first = true;
1719 for (userid_t i : intSet) {
1720 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001721 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001722 first = false;
1723 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001724 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001725 }
1726 }
Austin Borgered99f642023-06-01 16:51:35 -07001727 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001728}
1729
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001730int32_t CameraService::mapToInterface(TorchModeStatus status) {
1731 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1732 switch (status) {
1733 case TorchModeStatus::NOT_AVAILABLE:
1734 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1735 break;
1736 case TorchModeStatus::AVAILABLE_OFF:
1737 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1738 break;
1739 case TorchModeStatus::AVAILABLE_ON:
1740 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1741 break;
1742 default:
1743 ALOGW("Unknown new flash status: %d", status);
1744 }
1745 return serviceStatus;
1746}
1747
1748CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1749 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1750 switch (status) {
1751 case CameraDeviceStatus::NOT_PRESENT:
1752 serviceStatus = StatusInternal::NOT_PRESENT;
1753 break;
1754 case CameraDeviceStatus::PRESENT:
1755 serviceStatus = StatusInternal::PRESENT;
1756 break;
1757 case CameraDeviceStatus::ENUMERATING:
1758 serviceStatus = StatusInternal::ENUMERATING;
1759 break;
1760 default:
1761 ALOGW("Unknown new HAL device status: %d", status);
1762 }
1763 return serviceStatus;
1764}
1765
1766int32_t CameraService::mapToInterface(StatusInternal status) {
1767 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1768 switch (status) {
1769 case StatusInternal::NOT_PRESENT:
1770 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1771 break;
1772 case StatusInternal::PRESENT:
1773 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1774 break;
1775 case StatusInternal::ENUMERATING:
1776 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1777 break;
1778 case StatusInternal::NOT_AVAILABLE:
1779 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1780 break;
1781 case StatusInternal::UNKNOWN:
1782 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1783 break;
1784 default:
1785 ALOGW("Unknown new internal device status: %d", status);
1786 }
1787 return serviceStatus;
1788}
1789
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001790Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001791 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001792
Austin Borgered99f642023-06-01 16:51:35 -07001793 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001794 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001795 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001796 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001797 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1798 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001799 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001800 /*targetSdkVersion*/ __ANDROID_API_FUTURE__,
1801 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_OVERRIDE_TO_PORTRAIT,
Austin Borgered99f642023-06-01 16:51:35 -07001802 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001803 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001804 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001805 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001806 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001807}
1808
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001809Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001810 /*out*/
1811 CameraParameters* parameters) {
1812
1813 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1814
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001815 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001816
1817 if (parameters == NULL) {
1818 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001819 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001820 }
1821
malikakashedb38962023-09-06 00:03:35 +00001822 std::string unresolvedCameraId = std::to_string(cameraId);
1823 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08001824 getCallingUid());
Ruben Brunkcc776712015-02-17 20:18:47 -08001825
1826 // Check if we already have parameters
1827 {
1828 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001829 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001830 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001831 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001832 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001833 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001834 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001835 }
1836 CameraParameters p = cameraState->getShimParams();
1837 if (!p.isEmpty()) {
1838 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001839 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001840 }
1841 }
1842
Austin Borger22c5c852024-03-08 13:31:36 -08001843 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001844 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001845 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001846 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001847 // Error already logged by callee
1848 return ret;
1849 }
1850
1851 // Check for parameters again
1852 {
1853 // Scope for service lock
1854 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001855 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001856 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001857 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001858 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001859 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001860 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001861 CameraParameters p = cameraState->getShimParams();
1862 if (!p.isEmpty()) {
1863 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001864 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001865 }
1866 }
1867
Ruben Brunkcc776712015-02-17 20:18:47 -08001868 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1869 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001870 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001871}
1872
Austin Borgered99f642023-06-01 16:51:35 -07001873Status CameraService::validateConnectLocked(const std::string& cameraId,
1874 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001875 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001876
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001877#ifdef __BRILLO__
1878 UNUSED(clientName8);
1879 UNUSED(clientUid);
1880 UNUSED(clientPid);
1881 UNUSED(originalClientPid);
1882#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001883 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1884 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001885 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001886 return allowed;
1887 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001888#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001889
Austin Borger22c5c852024-03-08 13:31:36 -08001890 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001891
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001892 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001893 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1894 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001895 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001896 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001897 }
1898
Ruben Brunkcc776712015-02-17 20:18:47 -08001899 if (getCameraState(cameraId) == nullptr) {
1900 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001901 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001902 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001903 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001904 }
1905
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001906 status_t err = checkIfDeviceIsUsable(cameraId);
1907 if (err != NO_ERROR) {
1908 switch(err) {
1909 case -ENODEV:
1910 case -EBUSY:
1911 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001912 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001913 default:
1914 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001915 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001916 }
1917 }
1918 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001919}
1920
Austin Borgered99f642023-06-01 16:51:35 -07001921Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1922 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001923 /*out*/int& originalClientPid) const {
Austin Borger22c5c852024-03-08 13:31:36 -08001924 int callingPid = getCallingPid();
1925 int callingUid = getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001926
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001927 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001928 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001929 clientUid = callingUid;
1930 } else if (!isTrustedCallingUid(callingUid)) {
1931 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1932 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001933 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1934 "Untrusted caller (calling PID %d, UID %d) trying to "
1935 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001936 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001937 clientName.c_str(), clientPid, clientUid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001938 }
1939
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001940 // Check if we can trust clientPid
1941 if (clientPid == USE_CALLING_PID) {
1942 clientPid = callingPid;
1943 } else if (!isTrustedCallingUid(callingUid)) {
1944 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1945 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001946 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1947 "Untrusted caller (calling PID %d, UID %d) trying to "
1948 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001949 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001950 clientName.c_str(), clientPid, clientUid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001951 }
1952
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001953 if (shouldRejectSystemCameraConnection(cameraId)) {
1954 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1955 cameraId.c_str());
1956 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001957 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001958 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001959 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1960 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001961 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001962 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001963 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001964 }
1965
Biswarup Pale506e732024-03-27 13:46:20 +00001966 // Get the device id that owns this camera.
1967 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1968
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001969 // If it's not calling from cameraserver, check the permission if the
1970 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1971 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001972 bool checkPermissionForCamera =
Biswarup Pale506e732024-03-27 13:46:20 +00001973 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName, deviceId);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001974 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001975 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001976 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001977 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1978 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001979 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001980 }
1981
Svet Ganova453d0d2018-01-11 15:37:58 -08001982 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001983 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001984 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001985 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1986 clientPid, clientUid);
1987 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001988 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1989 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001990 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001991 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001992 }
1993
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001994 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1995 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1996 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1997 if ((!isAutomotivePrivilegedClient(callingUid) ||
1998 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1999 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002000 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
2001 return STATUS_ERROR_FMT(ERROR_DISABLED,
2002 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07002003 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08002004 }
2005
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07002006 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
2007 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07002008 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07002009 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002010
Ruben Brunk6267b532015-04-30 17:44:07 -07002011 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08002012
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002013 // For non-system clients : Only allow clients who are being used by the current foreground
2014 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08002015 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08002016 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002017 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
2018 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07002019 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002020 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2021 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002022 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07002023 }
2024
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07002025 if (flags::camera_hsum_permission()) {
2026 // If the System User tries to access the camera when the device is running in
2027 // headless system user mode, ensure that client has the required permission
2028 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07002029 if (isHeadlessSystemUserMode()
2030 && (clientUserId == USER_SYSTEM)
2031 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07002032 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
2033 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2034 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
2035 User without camera headless system user permission",
Austin Borger249e6592024-03-10 22:28:11 -07002036 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07002037 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07002038 }
2039
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002040 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002041}
2042
Austin Borgered99f642023-06-01 16:51:35 -07002043status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08002044 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08002045 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08002046 if (cameraState == nullptr) {
2047 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07002048 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002049 return -ENODEV;
2050 }
2051
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002052 StatusInternal currentStatus = cameraState->getStatus();
2053 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002054 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07002055 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002056 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002057 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002058 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07002059 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002060 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07002061 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002062
Ruben Brunkcc776712015-02-17 20:18:47 -08002063 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08002064}
2065
Ruben Brunkcc776712015-02-17 20:18:47 -08002066void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002067 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08002068
Ruben Brunkcc776712015-02-17 20:18:47 -08002069 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002070 auto clientDescriptor =
2071 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002072 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08002073 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
2074
2075 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002076 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08002077
2078 if (evicted.size() > 0) {
2079 // This should never happen - clients should already have been removed in disconnect
2080 for (auto& i : evicted) {
2081 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07002082 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002083 }
2084
2085 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
2086 __FUNCTION__);
2087 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002088
2089 // And register a death notification for the client callback. Do
2090 // this last to avoid Binder policy where a nested Binder
2091 // transaction might be pre-empted to service the client death
2092 // notification if the client process dies before linkToDeath is
2093 // invoked.
2094 sp<IBinder> remoteCallback = client->getRemote();
2095 if (remoteCallback != nullptr) {
2096 remoteCallback->linkToDeath(this);
2097 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002098}
2099
Austin Borgered99f642023-06-01 16:51:35 -07002100status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
2101 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
2102 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08002103 /*out*/
2104 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07002105 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002106 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08002107 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002108 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08002109 DescriptorPtr clientDescriptor;
2110 {
2111 if (effectiveApiLevel == API_1) {
2112 // If we are using API1, any existing client for this camera ID with the same remote
2113 // should be returned rather than evicted to allow MediaRecorder to work properly.
2114
2115 auto current = mActiveClientManager.get(cameraId);
2116 if (current != nullptr) {
2117 auto clientSp = current->getValue();
2118 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002119 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07002120 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002121 " API level, evicting prior client...");
2122 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002123 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002124 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002125 *client = clientSp;
2126 return NO_ERROR;
2127 }
2128 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002129 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002130 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08002131
Ruben Brunkcc776712015-02-17 20:18:47 -08002132 // Get state for the given cameraId
2133 auto state = getCameraState(cameraId);
2134 if (state == nullptr) {
2135 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07002136 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002137 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07002138 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002139 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002140
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002141 sp<IServiceManager> sm = defaultServiceManager();
2142 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08002143 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002144 // If processinfo service is not available and the client is automotive privileged
2145 // client used for safety critical uses cases such as rear-view and surround-view which
2146 // needs to be available before android boot completes, then use the hardcoded values
2147 // for the process state and priority score. As this scenario is before android system
2148 // services are up and client is native client, hence using NATIVE_ADJ as the priority
2149 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
2150 // visible on the top.
2151 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2152 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2153 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
2154 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
2155 } else {
2156 // Get current active client PIDs
2157 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
2158 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002159
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002160 std::vector<int> priorityScores(ownerPids.size());
2161 std::vector<int> states(ownerPids.size());
2162
2163 // Get priority scores of all active PIDs
2164 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
2165 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
2166 if (err != OK) {
2167 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
2168 return err;
2169 }
2170
2171 // Update all active clients' priorities
2172 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
2173 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
2174 pidToPriorityMap.emplace(ownerPids[i],
2175 resource_policy::ClientPriority(priorityScores[i], states[i],
2176 /* isVendorClient won't get copied over*/ false,
2177 /* oomScoreOffset won't get copied over*/ 0));
2178 }
2179 mActiveClientManager.updatePriorities(pidToPriorityMap);
2180
2181 int32_t actualScore = priorityScores[priorityScores.size() - 1];
2182 int32_t actualState = states[states.size() - 1];
2183
2184 // Make descriptor for incoming client. We store the oomScoreOffset
2185 // since we might need it later on new handleEvictionsLocked and
2186 // ProcessInfoService would not take that into account.
2187 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2188 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2189 state->getConflicting(), actualScore, clientPid, actualState,
2190 oomScoreOffset, systemNativeClient);
2191 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002192
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002193 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
2194
Ruben Brunkcc776712015-02-17 20:18:47 -08002195 // Find clients that would be evicted
2196 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
2197
2198 // If the incoming client was 'evicted,' higher priority clients have the camera in the
2199 // background, so we cannot do evictions
2200 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2201 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2202 " priority).", clientPid);
2203
2204 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002205 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002206 auto incompatibleClients =
2207 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2208
Austin Borgered99f642023-06-01 16:51:35 -07002209 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2210 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2211 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002212 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002213
2214 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002215 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002216 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002217 i->getKey().c_str(),
2218 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002219 i->getOwnerId(), i->getPriority().getScore(),
2220 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002221 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002222 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2223 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002224 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002225 }
2226
2227 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002228 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002229 mEventLog.add(msg);
2230
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002231 auto current = mActiveClientManager.get(cameraId);
2232 if (current != nullptr) {
2233 return -EBUSY; // CAMERA_IN_USE
2234 } else {
2235 return -EUSERS; // MAX_CAMERAS_IN_USE
2236 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002237 }
2238
2239 for (auto& i : evicted) {
2240 sp<BasicClient> clientSp = i->getValue();
2241 if (clientSp.get() == nullptr) {
2242 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2243
2244 // TODO: Remove this
2245 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2246 __FUNCTION__);
2247 mActiveClientManager.remove(i);
2248 continue;
2249 }
2250
2251 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002252 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002253 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002254
Ruben Brunkcc776712015-02-17 20:18:47 -08002255 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002256 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002257 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2258 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002259 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002260 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002261 i->getPriority().getState(), cameraId.c_str(),
2262 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002263 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002264
2265 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002266 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002267 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002268 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002269 }
2270
Ruben Brunkcc776712015-02-17 20:18:47 -08002271 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2272 // other clients from connecting in mServiceLockWrapper if held
2273 mServiceLock.unlock();
2274
2275 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002276 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002277
2278 // Destroy evicted clients
2279 for (auto& i : evictedClients) {
2280 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002281 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002282 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002283
Austin Borger22c5c852024-03-08 13:31:36 -08002284 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002285
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002286 for (const auto& i : evictedClients) {
2287 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002288 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002289 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2290 if (ret == TIMED_OUT) {
2291 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002292 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2293 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002294 return -EBUSY;
2295 }
2296 if (ret != NO_ERROR) {
2297 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002298 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2299 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002300 return ret;
2301 }
2302 }
2303
2304 evictedClients.clear();
2305
Ruben Brunkcc776712015-02-17 20:18:47 -08002306 // Once clients have been disconnected, relock
2307 mServiceLock.lock();
2308
2309 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2310 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2311 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002312 }
2313
Ruben Brunkcc776712015-02-17 20:18:47 -08002314 *partial = clientDescriptor;
2315 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002316}
2317
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002318Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002319 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002320 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07002321 const std::string& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002322 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08002323 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002324 int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002325 int rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00002326 bool forceSlowJpegMode,
Biswarup Pal37a75182024-01-16 15:53:35 +00002327 int32_t deviceId,
2328 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002329 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002330 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002331 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002332 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002333
Biswarup Pal37a75182024-01-16 15:53:35 +00002334 std::string cameraIdStr = cameraIdIntToStr(api1CameraId, deviceId, devicePolicy);
2335 if (cameraIdStr.empty()) {
2336 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
2337 api1CameraId, deviceId);
2338 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2339 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2340 }
malikakashedb38962023-09-06 00:03:35 +00002341
Ruben Brunkcc776712015-02-17 20:18:47 -08002342 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002343 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
2344 clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002345 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002346 rotationOverride, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002347
Biswarup Pal37a75182024-01-16 15:53:35 +00002348 if (!ret.isOk()) {
2349 logRejected(cameraIdStr, getCallingPid(), clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002350 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002351 }
2352
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002353 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002354
2355 const sp<IServiceManager> sm(defaultServiceManager());
2356 const auto& mActivityManager = getActivityManager();
2357 if (mActivityManager) {
2358 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002359 getCallingUid(),
2360 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002361 }
2362
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002363 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002364}
2365
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002366bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2367 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002368 // If the client is not a vendor client, don't add listener if
2369 // a) the camera is a publicly hidden secure camera OR
2370 // b) the camera is a system only camera and the client doesn't
2371 // have android.permission.SYSTEM_CAMERA permissions.
2372 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2373 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002374 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002375 return true;
2376 }
2377 return false;
2378}
2379
Austin Borgered99f642023-06-01 16:51:35 -07002380bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002381 // Rules for rejection:
2382 // 1) If cameraserver tries to access this camera device, accept the
2383 // connection.
2384 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002385 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002386 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2387 // and the serving thread is a non hwbinder thread, the client must have
2388 // android.permission.SYSTEM_CAMERA permissions to connect.
2389
Austin Borger22c5c852024-03-08 13:31:36 -08002390 int cPid = getCallingPid();
2391 int cUid = getCallingUid();
2392 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002393 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2394 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002395 // This isn't a known camera ID, so it's not a system camera
2396 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2397 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002398 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002399
2400 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002401 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002402 return false;
2403 }
2404 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002405 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002406 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2407 return true;
2408 }
2409 // (3) Here we only check for permissions if it is a system only camera device. This is since
2410 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2411 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2412 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002413 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002414 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002415 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2416 cameraId.c_str());
2417 return true;
2418 }
2419
2420 return false;
2421}
2422
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002423Status CameraService::connectDevice(
2424 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002425 const std::string& unresolvedCameraId,
2426 const std::string& clientPackageName,
2427 const std::optional<std::string>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002428 int clientUid, int oomScoreOffset, int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002429 int rotationOverride, int32_t deviceId, int32_t devicePolicy,
Ruben Brunkcc776712015-02-17 20:18:47 -08002430 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002431 sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002432 ATRACE_CALL();
Emilian Peev31bd2422024-04-23 22:24:09 +00002433 RunThreadWithRealtimePriority priorityBump;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002434 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002435 sp<CameraDeviceClient> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002436 std::string clientPackageNameAdj = clientPackageName;
Austin Borger22c5c852024-03-08 13:31:36 -08002437 int callingPid = getCallingPid();
2438 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002439 bool systemNativeClient = false;
Austin Borger22c5c852024-03-08 13:31:36 -08002440 if (callerHasSystemUid() && (clientPackageNameAdj.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002441 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borgered99f642023-06-01 16:51:35 -07002442 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002443 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002444 }
Austin Borger249e6592024-03-10 22:28:11 -07002445
Biswarup Pal37a75182024-01-16 15:53:35 +00002446 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
2447 devicePolicy, callingUid, clientPackageNameAdj);
2448 if (!cameraIdOptional.has_value()) {
2449 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
2450 unresolvedCameraId.c_str(), deviceId);
2451 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2452 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2453 }
2454 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002455
2456 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002457 std::string msg =
2458 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
2459 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
2460 cameraId.c_str());
2461 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2462 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002463 }
2464
Austin Borger9bfa0a72022-08-03 17:50:40 -07002465 userid_t clientUserId = multiuser_get_user_id(clientUid);
Austin Borger9bfa0a72022-08-03 17:50:40 -07002466 if (clientUid == USE_CALLING_UID) {
2467 clientUserId = multiuser_get_user_id(callingUid);
2468 }
2469
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002470 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2471 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002472 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2473 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002474 std::string msg = "Camera disabled by device policy";
2475 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2476 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002477 }
2478
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002479 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002480 if (oomScoreOffset > 0
2481 && !hasPermissionsForSystemCamera(cameraId, callingPid,
Austin Borger249e6592024-03-10 22:28:11 -07002482 callingUid)
2483 && !isTrustedCallingUid(callingUid)) {
Austin Borgered99f642023-06-01 16:51:35 -07002484 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002485 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07002486 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2487 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2488 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002489 }
2490
Austin Borgered99f642023-06-01 16:51:35 -07002491 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
2492 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002493 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002494 targetSdkVersion, rotationOverride, /*forceSlowJpegMode*/false, unresolvedCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002495 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002496
Biswarup Pal37a75182024-01-16 15:53:35 +00002497 if (!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002498 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002499 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002500 }
2501
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002502 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002503 Mutex::Autolock lock(mServiceLock);
2504
2505 // Clear the previous cached logs and reposition the
2506 // file offset to beginning of the file to log new data.
2507 // If either truncate or lseek fails, close the previous file and create a new one.
2508 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2509 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2510 // Close the previous memfd.
2511 close(mMemFd);
2512 // If failure to wipe the data, then create a new file and
2513 // assign the new value to mMemFd.
2514 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2515 if (mMemFd == -1) {
2516 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2517 }
2518 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002519 const sp<IServiceManager> sm(defaultServiceManager());
2520 const auto& mActivityManager = getActivityManager();
2521 if (mActivityManager) {
2522 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002523 callingUid,
2524 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002525 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002526 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002527}
2528
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002529bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2530 int callingPid, int callingUid) {
2531 if (!isAutomotiveDevice()) {
2532 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2533 }
2534
2535 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2536 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2537 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2538 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2539 "using camera %s", callingUid, cam_id.c_str());
2540 return false;
2541 }
2542
2543 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2544 return true;
2545 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2546 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002547 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2548 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002549 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2550 return false;
2551 } else {
2552 return true;
2553 }
2554 }
2555 return false;
2556}
2557
Austin Borgered99f642023-06-01 16:51:35 -07002558std::string CameraService::getPackageNameFromUid(int clientUid) {
2559 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002560
Avichal Rakesh5788fec2024-03-15 14:39:20 -07002561 sp<IPermissionController> permCtrl;
2562 if (flags::cache_permission_services()) {
2563 permCtrl = getPermissionController();
2564 } else {
2565 sp<IServiceManager> sm = defaultServiceManager();
2566#pragma clang diagnostic push
2567#pragma clang diagnostic ignored "-Wdeprecated-declarations"
2568 // Using deprecated function to preserve functionality until the
2569 // cache_permission_services flag is removed.
2570 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
2571#pragma clang diagnostic pop
2572 if (binder == 0) {
2573 ALOGE("Cannot get permission service");
2574 permCtrl = nullptr;
2575 } else {
2576 permCtrl = interface_cast<IPermissionController>(binder);
2577 }
2578 }
2579
2580 if (permCtrl == nullptr) {
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002581 // Return empty package name and the further interaction
2582 // with camera will likely fail
2583 return packageName;
2584 }
2585
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002586 Vector<String16> packages;
2587
2588 permCtrl->getPackagesForUid(clientUid, packages);
2589
2590 if (packages.isEmpty()) {
2591 ALOGE("No packages for calling UID %d", clientUid);
2592 // Return empty package name and the further interaction
2593 // with camera will likely fail
2594 return packageName;
2595 }
2596
2597 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002598 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002599
2600 return packageName;
2601}
2602
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002603template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002604Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2605 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2606 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002607 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002608 int rotationOverride, bool forceSlowJpegMode,
2609 const std::string& originalCameraId, /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002610 binder::Status ret = binder::Status::ok();
2611
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002612 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002613 std::string clientPackageName;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002614 int packageUid = (clientUid == USE_CALLING_UID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002615 getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002616 if (clientPackageNameMaybe.size() <= 0) {
2617 // NDK calls don't come with package names, but we need one for various cases.
2618 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2619 // do exist. For all authentication cases, all packages under the same UID get the
2620 // same permissions, so picking any associated package name is sufficient. For some
2621 // other cases, this may give inaccurate names for clients in logs.
2622 isNonSystemNdk = true;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002623 clientPackageName = getPackageNameFromUid(packageUid);
2624 } else {
2625 clientPackageName = clientPackageNameMaybe;
2626 }
2627
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002628 int originalClientPid = 0;
2629
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002630 int packagePid = (clientPid == USE_CALLING_PID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002631 getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002632 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002633 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002634 static_cast<int>(effectiveApiLevel));
2635
Shuzhen Wang316781a2020-08-18 18:11:01 -07002636 nsecs_t openTimeNs = systemTime();
2637
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002638 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002639 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002640 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002641
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002642 {
2643 // Acquire mServiceLock and prevent other clients from connecting
2644 std::unique_ptr<AutoConditionLock> lock =
2645 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2646
2647 if (lock == nullptr) {
2648 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2649 , clientPid);
2650 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2651 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002652 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002653 }
2654
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002655 // Enforce client permissions and do basic validity checks
Biswarup Pal37a75182024-01-16 15:53:35 +00002656 if (!(ret = validateConnectLocked(cameraId, clientPackageName,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002657 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2658 return ret;
2659 }
2660
2661 // Check the shim parameters after acquiring lock, if they have already been updated and
2662 // we were doing a shim update, return immediately
2663 if (shimUpdateOnly) {
2664 auto cameraState = getCameraState(cameraId);
2665 if (cameraState != nullptr) {
2666 if (!cameraState->getShimParams().isEmpty()) return ret;
2667 }
2668 }
2669
2670 status_t err;
2671
2672 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002673 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002674 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002675 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2676 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002677 switch (err) {
2678 case -ENODEV:
2679 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2680 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002681 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002682 case -EBUSY:
2683 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2684 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002685 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002686 case -EUSERS:
2687 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2688 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002689 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002690 default:
2691 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2692 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002693 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002694 }
2695 }
2696
2697 if (clientTmp.get() != nullptr) {
2698 // Handle special case for API1 MediaRecorder where the existing client is returned
2699 device = static_cast<CLIENT*>(clientTmp.get());
2700 return ret;
2701 }
2702
2703 // give flashlight a chance to close devices if necessary.
2704 mFlashlight->prepareDeviceOpen(cameraId);
2705
Austin Borger18b30a72022-10-27 12:20:29 -07002706 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002707 auto deviceVersionAndTransport =
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002708 getDeviceVersion(cameraId, rotationOverride, /*out*/&portraitRotation,
Austin Borger18b30a72022-10-27 12:20:29 -07002709 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002710 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002711 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002712 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002713 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002714 }
2715
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002716 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002717 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002718 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002719
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002720 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002721 clientFeatureId, cameraId, api1CameraId, facing,
2722 orientation, clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002723 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002724 rotationOverride, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002725 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002726 return ret;
2727 }
2728 client = static_cast<CLIENT*>(tmp.get());
2729
2730 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2731 __FUNCTION__);
2732
Austin Borgered99f642023-06-01 16:51:35 -07002733 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002734 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002735 if (err != OK) {
2736 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002737 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002738 mServiceLock.unlock();
2739 client->disconnect();
2740 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002741 switch(err) {
2742 case BAD_VALUE:
2743 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002744 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002745 case -EBUSY:
2746 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002747 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002748 case -EUSERS:
2749 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2750 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002751 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002752 case PERMISSION_DENIED:
2753 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002754 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002755 case -EACCES:
2756 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002757 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002758 case -ENODEV:
2759 default:
2760 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002761 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002762 strerror(-err), err);
2763 }
2764 }
2765
2766 // Update shim paremeters for legacy clients
2767 if (effectiveApiLevel == API_1) {
2768 // Assume we have always received a Client subclass for API1
2769 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2770 String8 rawParams = shimClient->getParameters();
2771 CameraParameters params(rawParams);
2772
2773 auto cameraState = getCameraState(cameraId);
2774 if (cameraState != nullptr) {
2775 cameraState->setShimParams(params);
2776 } else {
2777 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002778 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002779 }
2780 }
2781
Ravneetaeb20dc2022-03-30 05:33:03 +00002782 // Enable/disable camera service watchdog
2783 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2784
Emilian Peev6d45db82024-01-18 20:11:54 +00002785 CameraMetadata chars;
2786 bool rotateAndCropSupported = true;
2787 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002788 &chars, rotationOverride);
Emilian Peev6d45db82024-01-18 20:11:54 +00002789 if (err == OK) {
2790 auto availableRotateCropEntry = chars.find(
2791 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2792 if (availableRotateCropEntry.count <= 1) {
2793 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002794 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002795 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002796 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2797 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002798 }
2799
Emilian Peev6d45db82024-01-18 20:11:54 +00002800 if (rotateAndCropSupported) {
2801 // Set rotate-and-crop override behavior
2802 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2803 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002804 } else if (rotationOverride != hardware::ICameraService::ROTATION_OVERRIDE_NONE &&
2805 portraitRotation != 0) {
Emilian Peev6d45db82024-01-18 20:11:54 +00002806 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2807 switch (portraitRotation) {
2808 case 90:
2809 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2810 break;
2811 case 180:
2812 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2813 break;
2814 case 270:
2815 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2816 break;
2817 default:
2818 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2819 break;
2820 }
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002821 // Here we're communicating to the client the chosen rotate
2822 // and crop mode to send to the HAL
Emilian Peev6d45db82024-01-18 20:11:54 +00002823 client->setRotateAndCropOverride(rotateAndCropMode);
2824 } else {
2825 client->setRotateAndCropOverride(
2826 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2827 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2828 }
2829 }
2830
2831 bool autoframingSupported = true;
2832 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2833 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2834 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2835 autoframingSupported = false;
2836 }
2837
2838 if (autoframingSupported) {
2839 // Set autoframing override behaviour
2840 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2841 client->setAutoframingOverride(mOverrideAutoframingMode);
2842 } else {
2843 client->setAutoframingOverride(
2844 mCameraServiceProxyWrapper->getAutoframingOverride(
2845 clientPackageName));
2846 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002847 }
2848
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002849 bool isCameraPrivacyEnabled;
2850 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002851 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002852 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2853 toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2854 } else {
2855 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002856 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002857 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002858
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002859 if (client->supportsCameraMute()) {
2860 client->setCameraMute(
2861 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2862 } else if (isCameraPrivacyEnabled) {
2863 // no camera mute supported, but privacy is on! => disconnect
2864 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2865 client->getPackageName().c_str(), cameraId.c_str());
2866 // Do not hold mServiceLock while disconnecting clients, but
2867 // retain the condition blocking other clients from connecting
2868 // in mServiceLockWrapper if held.
2869 mServiceLock.unlock();
2870 // Clear caller identity temporarily so client disconnect PID
2871 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002872 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002873 // Note AppOp to trigger the "Unblock" dialog
2874 client->noteAppOp();
2875 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002876 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002877 // Reacquire mServiceLock
2878 mServiceLock.lock();
2879
2880 return STATUS_ERROR_FMT(ERROR_DISABLED,
2881 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002882 }
2883
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002884 if (shimUpdateOnly) {
2885 // If only updating legacy shim parameters, immediately disconnect client
2886 mServiceLock.unlock();
2887 client->disconnect();
2888 mServiceLock.lock();
2889 } else {
2890 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002891 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002892 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002893
2894 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002895 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002896 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002897 } // lock is destroyed, allow further connect calls
2898
2899 // Important: release the mutex here so the client can call back into the service from its
2900 // destructor (can be at the end of the call)
2901 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002902
2903 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002904 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002905 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002906
Cliff Wud3a05312021-04-26 23:07:31 +08002907 {
2908 Mutex::Autolock lock(mInjectionParametersLock);
2909 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2910 mInjectionInitPending = false;
2911 status_t res = NO_ERROR;
2912 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2913 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002914 sp<BasicClient> clientSp = clientDescriptor->getValue();
2915 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2916 if(res != OK) {
2917 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2918 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002919 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002920 }
2921 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002922 if (res != OK) {
2923 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2924 }
2925 } else {
2926 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002927 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002928 res = NO_INIT;
2929 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2930 }
2931 }
2932 }
2933
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002934 return ret;
2935}
2936
Austin Borgered99f642023-06-01 16:51:35 -07002937status_t CameraService::addOfflineClient(const std::string &cameraId,
2938 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002939 if (offlineClient.get() == nullptr) {
2940 return BAD_VALUE;
2941 }
2942
2943 {
2944 // Acquire mServiceLock and prevent other clients from connecting
2945 std::unique_ptr<AutoConditionLock> lock =
2946 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2947
2948 if (lock == nullptr) {
2949 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2950 , __FUNCTION__, offlineClient->getClientPid());
2951 return TIMED_OUT;
2952 }
2953
2954 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2955 if (onlineClientDesc.get() == nullptr) {
2956 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2957 cameraId.c_str());
2958 return BAD_VALUE;
2959 }
2960
2961 // Offline clients do not evict or conflict with other online devices. Resource sharing
2962 // conflicts are handled by the camera provider which will either succeed or fail before
2963 // reaching this method.
2964 const auto& onlinePriority = onlineClientDesc->getPriority();
2965 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2966 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002967 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002968 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002969 // native clients don't have offline processing support.
2970 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002971 if (offlineClientDesc == nullptr) {
2972 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2973 return BAD_VALUE;
2974 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002975
2976 // Allow only one offline device per camera
2977 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2978 if (!incompatibleClients.empty()) {
2979 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2980 return BAD_VALUE;
2981 }
2982
Austin Borgered99f642023-06-01 16:51:35 -07002983 std::string monitorTags = isClientWatched(offlineClient.get())
2984 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002985 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002986 if (err != OK) {
2987 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2988 return err;
2989 }
2990
2991 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2992 if (evicted.size() > 0) {
2993 for (auto& i : evicted) {
2994 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002995 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002996 }
2997
2998 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2999 "properly", __FUNCTION__);
3000
3001 return BAD_VALUE;
3002 }
3003
3004 logConnectedOffline(offlineClientDesc->getKey(),
3005 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07003006 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003007
3008 sp<IBinder> remoteCallback = offlineClient->getRemote();
3009 if (remoteCallback != nullptr) {
3010 remoteCallback->linkToDeath(this);
3011 }
3012 } // lock is destroyed, allow further connect calls
3013
3014 return OK;
3015}
3016
Austin Borgered99f642023-06-01 16:51:35 -07003017Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +00003018 int32_t torchStrength, const sp<IBinder>& clientBinder, int32_t deviceId,
3019 int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08003020 Mutex::Autolock lock(mServiceLock);
3021
3022 ATRACE_CALL();
3023 if (clientBinder == nullptr) {
3024 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
3025 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
3026 "Torch client binder in null.");
3027 }
3028
Austin Borger22c5c852024-03-08 13:31:36 -08003029 int uid = getCallingUid();
Biswarup Pal37a75182024-01-16 15:53:35 +00003030 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
3031 devicePolicy, uid);
3032 if (!cameraIdOptional.has_value()) {
3033 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
3034 unresolvedCameraId.c_str(), deviceId);
3035 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3036 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3037 }
3038 std::string cameraId = cameraIdOptional.value();
3039
Austin Borgered99f642023-06-01 16:51:35 -07003040 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08003041 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07003042 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003043 }
3044
3045 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07003046 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08003047 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07003048 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003049 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003050 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003051 }
3052
3053 StatusInternal cameraStatus = state->getStatus();
3054 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
3055 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07003056 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08003057 (int)cameraStatus);
3058 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003059 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003060 }
3061
3062 {
3063 Mutex::Autolock al(mTorchStatusMutex);
3064 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003065 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08003066 if (err != OK) {
3067 if (err == NAME_NOT_FOUND) {
3068 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003069 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003070 }
3071 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003072 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003073 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
3074 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003075 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08003076 }
3077
3078 if (status == TorchModeStatus::NOT_AVAILABLE) {
3079 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
3080 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003081 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003082 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3083 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003084 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003085 } else {
3086 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003087 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003088 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3089 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003090 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003091 }
3092 }
3093 }
3094
3095 {
3096 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003097 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08003098 }
3099 // Check if the current torch strength level is same as the new one.
3100 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07003101 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003102
Austin Borgered99f642023-06-01 16:51:35 -07003103 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003104
3105 if (err != OK) {
3106 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003107 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08003108 switch (err) {
3109 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003110 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
3111 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003112 errorCode = ERROR_ILLEGAL_ARGUMENT;
3113 break;
3114 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003115 msg = fmt::sprintf("Camera \"%s\" is in use",
3116 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003117 errorCode = ERROR_CAMERA_IN_USE;
3118 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08003119 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07003120 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08003121 "valid range.", torchStrength);
3122 errorCode = ERROR_ILLEGAL_ARGUMENT;
3123 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08003124 default:
Austin Borgered99f642023-06-01 16:51:35 -07003125 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08003126 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08003127 }
Austin Borgered99f642023-06-01 16:51:35 -07003128 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3129 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003130 }
3131
3132 {
3133 // update the link to client's death
3134 // Store the last client that turns on each camera's torch mode.
3135 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003136 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08003137 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003138 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08003139 } else {
3140 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
3141 mTorchClientMap.replaceValueAt(index, clientBinder);
3142 }
3143 clientBinder->linkToDeath(this);
3144 }
3145
Austin Borger22c5c852024-03-08 13:31:36 -08003146 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08003147 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07003148 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08003149 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07003150 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003151 }
3152 return Status::ok();
3153}
3154
malikakash73125c62023-07-21 22:44:34 +00003155Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Biswarup Pal37a75182024-01-16 15:53:35 +00003156 const sp<IBinder>& clientBinder, int32_t deviceId, int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003157 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003158
3159 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07003160 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003161 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003162 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
3163 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003164 }
3165
Austin Borger22c5c852024-03-08 13:31:36 -08003166 int uid = getCallingUid();
Biswarup Pal37a75182024-01-16 15:53:35 +00003167 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
3168 devicePolicy, uid);
3169 if (!cameraIdOptional.has_value()) {
3170 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
3171 unresolvedCameraId.c_str(), deviceId);
3172 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3173 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3174 }
3175 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003176
Austin Borgered99f642023-06-01 16:51:35 -07003177 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003178 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07003179 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003180 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003181 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07003182 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003183 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07003184 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003185 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003186 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003187 }
3188
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003189 StatusInternal cameraStatus = state->getStatus();
3190 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003191 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07003192 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
3193 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003194 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003195 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003196 }
3197
3198 {
3199 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003200 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003201 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003202 if (err != OK) {
3203 if (err == NAME_NOT_FOUND) {
3204 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003205 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003206 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003207 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003208 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003209 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07003210 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003211 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003212 }
3213
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003214 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003215 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003216 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003217 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003218 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3219 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003220 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003221 } else {
3222 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003223 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003224 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3225 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003226 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003227 }
3228 }
3229 }
3230
Ruben Brunk99e69712015-05-26 17:25:07 -07003231 {
3232 // Update UID map - this is used in the torch status changed callbacks, so must be done
3233 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003234 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003235 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003236 }
3237
Austin Borgered99f642023-06-01 16:51:35 -07003238 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003239
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003240 if (err != OK) {
3241 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003242 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003243 switch (err) {
3244 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003245 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3246 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003247 errorCode = ERROR_ILLEGAL_ARGUMENT;
3248 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003249 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003250 msg = fmt::sprintf("Camera \"%s\" is in use",
3251 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003252 errorCode = ERROR_CAMERA_IN_USE;
3253 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003254 default:
Austin Borgered99f642023-06-01 16:51:35 -07003255 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003256 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003257 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003258 errorCode = ERROR_INVALID_OPERATION;
3259 }
Austin Borgered99f642023-06-01 16:51:35 -07003260 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3261 logServiceError(msg, errorCode);
3262 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003263 }
3264
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003265 {
3266 // update the link to client's death
3267 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003268 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003269 if (enabled) {
3270 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003271 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003272 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003273 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003274 mTorchClientMap.replaceValueAt(index, clientBinder);
3275 }
3276 clientBinder->linkToDeath(this);
3277 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003278 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003279 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003280 }
3281
Austin Borger22c5c852024-03-08 13:31:36 -08003282 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003283 std::string torchState = enabled ? "on" : "off";
3284 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3285 torchState.c_str(), clientPid);
3286 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003287 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003288}
3289
Austin Borgered99f642023-06-01 16:51:35 -07003290void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3291 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3292 mTorchUidMap[cameraId].first = uid;
3293 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003294 } else {
3295 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003296 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003297 }
3298}
3299
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003300Status CameraService::notifySystemEvent(int32_t eventId,
3301 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003302 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003303 const int selfPid = getpid();
3304
3305 // Permission checks
3306 if (pid != selfPid) {
3307 // Ensure we're being called by system_server, or similar process with
3308 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003309 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003310 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003311 ALOGE("Permission Denial: cannot send updates to camera service about system"
3312 " events from pid=%d, uid=%d", pid, uid);
3313 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003314 "No permission to send updates to camera service about system events"
3315 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003316 }
3317 }
3318
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003319 ATRACE_CALL();
3320
Ruben Brunk36597b22015-03-20 22:15:57 -07003321 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003322 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003323 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003324 // from a system server crash
3325 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003326 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003327 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003328 break;
3329 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003330 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3331 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003332 if (args.size() != 1) {
3333 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3334 "USB Device Event requires 1 argument");
3335 }
3336
Valentin Iftime29e2e152021-08-13 15:17:33 +02003337 // Notify CameraProviderManager for lazy HALs
3338 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3339 std::to_string(args[0]));
3340 break;
3341 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003342 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003343 default: {
3344 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3345 eventId);
3346 break;
3347 }
3348 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003349 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003350}
3351
Emilian Peev53722fa2019-02-22 17:47:20 -08003352void CameraService::notifyMonitoredUids() {
3353 Mutex::Autolock lock(mStatusListenerLock);
3354
3355 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003356 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003357 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3358 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003359 }
3360}
3361
Austin Borgerdddb7552023-03-30 17:53:01 -07003362void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3363 Mutex::Autolock lock(mStatusListenerLock);
3364
3365 for (const auto& it : mListenerList) {
3366 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3367 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3368 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3369 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3370 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3371 }
3372 }
3373}
3374
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003375Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003376 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003377 const int selfPid = getpid();
3378
3379 // Permission checks
3380 if (pid != selfPid) {
3381 // Ensure we're being called by system_server, or similar process with
3382 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003383 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003384 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003385 ALOGE("Permission Denial: cannot send updates to camera service about device"
3386 " state changes from pid=%d, uid=%d", pid, uid);
3387 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3388 "No permission to send updates to camera service about device state"
3389 " changes from pid=%d, uid=%d", pid, uid);
3390 }
3391 }
3392
3393 ATRACE_CALL();
3394
Austin Borger18b30a72022-10-27 12:20:29 -07003395 {
3396 Mutex::Autolock lock(mServiceLock);
3397 mDeviceState = newState;
3398 }
3399
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003400 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003401
3402 return Status::ok();
3403}
3404
Emilian Peev8b64f282021-03-25 16:49:57 -07003405Status CameraService::notifyDisplayConfigurationChange() {
3406 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003407 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003408 const int selfPid = getpid();
3409
3410 // Permission checks
3411 if (callingPid != selfPid) {
3412 // Ensure we're being called by system_server, or similar process with
3413 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003414 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003415 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003416 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3417 " changes from pid=%d, uid=%d", callingPid, uid);
3418 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3419 "No permission to send updates to camera service about orientation"
3420 " changes from pid=%d, uid=%d", callingPid, uid);
3421 }
3422 }
3423
3424 Mutex::Autolock lock(mServiceLock);
3425
3426 // Don't do anything if rotate-and-crop override via cmd is active
3427 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3428
3429 const auto clients = mActiveClientManager.getAll();
3430 for (auto& current : clients) {
3431 if (current != nullptr) {
3432 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003433 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3434 basicClient->setRotateAndCropOverride(
3435 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3436 basicClient->getPackageName(),
3437 basicClient->getCameraFacing(),
3438 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003439 }
3440 }
3441 }
3442
3443 return Status::ok();
3444}
3445
3446Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003447 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3448 ATRACE_CALL();
3449 if (!concurrentCameraIds) {
3450 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3451 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3452 }
3453
3454 if (!mInitialized) {
3455 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003456 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003457 return STATUS_ERROR(ERROR_DISCONNECTED,
3458 "Camera subsystem is not available");
3459 }
3460 // First call into the provider and get the set of concurrent camera
3461 // combinations
3462 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003463 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003464 for (auto &combination : concurrentCameraCombinations) {
Biswarup Pal7d072862024-04-17 15:24:47 +00003465 std::vector<std::pair<std::string, int32_t>> validCombination;
3466 int32_t firstDeviceId = kInvalidDeviceId;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003467 for (auto &cameraId : combination) {
3468 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003469 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003470 if (state == nullptr) {
3471 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3472 continue;
3473 }
3474 StatusInternal status = state->getStatus();
3475 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3476 continue;
3477 }
Austin Borgered99f642023-06-01 16:51:35 -07003478 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003479 continue;
3480 }
Biswarup Pal7d072862024-04-17 15:24:47 +00003481 auto [cameraOwnerDeviceId, mappedCameraId] =
3482 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
3483 if (firstDeviceId == kInvalidDeviceId) {
3484 firstDeviceId = cameraOwnerDeviceId;
3485 } else if (firstDeviceId != cameraOwnerDeviceId) {
3486 // Found an invalid combination which contains cameras with different device id's,
3487 // hence discard it.
3488 validCombination.clear();
3489 break;
3490 }
3491 validCombination.push_back({mappedCameraId, cameraOwnerDeviceId});
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003492 }
3493 if (validCombination.size() != 0) {
3494 concurrentCameraIds->push_back(std::move(validCombination));
3495 }
3496 }
3497 return Status::ok();
3498}
3499
3500Status CameraService::isConcurrentSessionConfigurationSupported(
3501 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Biswarup Pal7d072862024-04-17 15:24:47 +00003502 int targetSdkVersion, int32_t deviceId, int32_t devicePolicy,
3503 /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003504 if (!isSupported) {
3505 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3506 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3507 }
3508
3509 if (!mInitialized) {
3510 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3511 return STATUS_ERROR(ERROR_DISCONNECTED,
3512 "Camera subsystem is not available");
3513 }
3514
Biswarup Pal7d072862024-04-17 15:24:47 +00003515 for (auto cameraIdAndSessionConfiguration : cameraIdsAndSessionConfigurations) {
3516 std::optional<std::string> cameraIdOptional =
3517 resolveCameraId(cameraIdAndSessionConfiguration.mCameraId, deviceId, devicePolicy,
3518 getCallingUid());
3519 if (!cameraIdOptional.has_value()) {
3520 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
3521 cameraIdAndSessionConfiguration.mCameraId.c_str(), deviceId);
3522 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3523 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3524 }
3525 cameraIdAndSessionConfiguration.mCameraId = cameraIdOptional.value();
3526 }
3527
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003528 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003529 int callingPid = getCallingPid();
3530 int callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003531 bool hasCameraPermission = ((callingPid == getpid()) ||
Biswarup Pal7d072862024-04-17 15:24:47 +00003532 hasPermissionsForCamera(callingPid, callingUid,
3533 devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT
3534 ? kDefaultDeviceId : deviceId));
Austin Borger249e6592024-03-10 22:28:11 -07003535 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003536 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3537 "android.permission.CAMERA needed to call"
3538 "isConcurrentSessionConfigurationSupported");
3539 }
3540
3541 status_t res =
3542 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003543 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3544 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003545 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003546 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003547 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003548 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3549 "support %s (%d)", strerror(-res), res);
3550 }
3551 return Status::ok();
3552}
3553
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003554Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3555 /*out*/
3556 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003557 return addListenerHelper(listener, cameraStatuses);
3558}
3559
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003560binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3561 std::vector<hardware::CameraStatus>* cameraStatuses) {
3562 return addListenerHelper(listener, cameraStatuses, false, true);
3563}
3564
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003565Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3566 /*out*/
3567 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003568 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003569 ATRACE_CALL();
3570
Igor Murashkinbfc99152013-02-27 12:55:20 -08003571 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003572
Ruben Brunk3450ba72015-06-16 11:00:37 -07003573 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003574 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003575 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003576 }
3577
Austin Borger22c5c852024-03-08 13:31:36 -08003578 auto clientPid = getCallingPid();
3579 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003580 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003581
Igor Murashkinbfc99152013-02-27 12:55:20 -08003582 Mutex::Autolock lock(mServiceLock);
3583
Ruben Brunkcc776712015-02-17 20:18:47 -08003584 {
3585 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003586 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003587 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003588 ALOGW("%s: Tried to add listener %p which was already subscribed",
3589 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003590 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003591 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003592 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003593
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003594 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003595 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3596 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003597 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003598 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003599 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003600 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003601 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3602 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3603 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003604 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003605 // The listener still needs to be added to the list of listeners, regardless of what
3606 // permissions the listener process has / whether it is a vendor listener. Since it might be
3607 // eligible to listen to other camera ids.
3608 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003609 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003610 }
3611
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003612 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003613 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003614 Mutex::Autolock lock(mCameraStatesLock);
3615 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003616 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3617 auto [deviceId, mappedCameraId] =
3618 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3619
3620 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003621 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003622 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3623 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003624 }
3625 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003626 // Remove the camera statuses that should be hidden from the client, we do
3627 // this after collecting the states in order to avoid holding
3628 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3629 // the same time.
3630 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3631 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003632 std::string cameraId = s.cameraId;
3633 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
3634 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM,
3635 clientUid);
3636 if (!cameraIdOptional.has_value()) {
3637 std::string msg =
3638 fmt::sprintf(
3639 "Camera %s: Invalid camera id for device id %d",
3640 s.cameraId.c_str(), s.deviceId);
3641 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3642 return true;
3643 }
3644 cameraId = cameraIdOptional.value();
3645 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3646 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3647 ALOGE("%s: Invalid camera id %s, skipping status update",
3648 __FUNCTION__, s.cameraId.c_str());
3649 return true;
3650 }
3651 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3652 clientUid);
3653 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003654
Biswarup Pal37a75182024-01-16 15:53:35 +00003655 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003656 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003657 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003658 // Add only default device cameras here, as virtual cameras currently don't support torch
3659 // anyway. Note that this is a simplification of the implementation here, and we should
3660 // change this when virtual cameras support torch.
3661 if (s.deviceId == kDefaultDeviceId) {
3662 idsChosenForCallback.insert(s.cameraId);
3663 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003664 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003665
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003666 /*
3667 * Immediately signal current torch status to this listener only
3668 * This may be a subset of all the devices, so don't include it in the response directly
3669 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003670 {
3671 Mutex::Autolock al(mTorchStatusMutex);
3672 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003673 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003674 // The camera id is visible to the client. Fine to send torch
3675 // callback.
3676 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003677 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3678 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003679 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003680 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003681 }
3682
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003683 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003684}
Ruben Brunkcc776712015-02-17 20:18:47 -08003685
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003686Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003687 ATRACE_CALL();
3688
Igor Murashkinbfc99152013-02-27 12:55:20 -08003689 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3690
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003691 if (listener == 0) {
3692 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003693 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003694 }
3695
Igor Murashkinbfc99152013-02-27 12:55:20 -08003696 Mutex::Autolock lock(mServiceLock);
3697
Ruben Brunkcc776712015-02-17 20:18:47 -08003698 {
3699 Mutex::Autolock lock(mStatusListenerLock);
3700 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003701 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003702 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003703 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003704 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003705 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003706 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003707 }
3708 }
3709
3710 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3711 __FUNCTION__, listener.get());
3712
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003713 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003714}
3715
Austin Borgered99f642023-06-01 16:51:35 -07003716Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003717
3718 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003719 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3720
3721 if (parameters == NULL) {
3722 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003723 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003724 }
3725
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003726 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003727
3728 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003729 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003730 // Error logged by caller
3731 return ret;
3732 }
3733
3734 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003735
Austin Borgered99f642023-06-01 16:51:35 -07003736 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003737
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003738 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003739}
3740
Austin Borgered99f642023-06-01 16:51:35 -07003741Status CameraService::supportsCameraApi(const std::string& unresolvedCameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003742 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003743 ATRACE_CALL();
3744
malikakashedb38962023-09-06 00:03:35 +00003745 const std::string cameraId = resolveCameraId(
Austin Borger22c5c852024-03-08 13:31:36 -08003746 unresolvedCameraId, getCallingUid());
malikakash82ed4352023-07-21 22:44:34 +00003747
Austin Borgered99f642023-06-01 16:51:35 -07003748 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003749
3750 switch (apiVersion) {
3751 case API_VERSION_1:
3752 case API_VERSION_2:
3753 break;
3754 default:
Austin Borgered99f642023-06-01 16:51:35 -07003755 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3756 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3757 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003758 }
3759
Austin Borger18b30a72022-10-27 12:20:29 -07003760 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00003761 auto deviceVersionAndTransport =
3762 getDeviceVersion(cameraId,
3763 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
3764 &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003765 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003766 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3767 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3768 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003769 }
3770 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3771 int deviceVersion = deviceVersionAndTransport.first;
3772 switch (deviceVersion) {
3773 case CAMERA_DEVICE_API_VERSION_1_0:
3774 case CAMERA_DEVICE_API_VERSION_3_0:
3775 case CAMERA_DEVICE_API_VERSION_3_1:
3776 if (apiVersion == API_VERSION_2) {
3777 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003778 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003779 *isSupported = false;
3780 } else { // if (apiVersion == API_VERSION_1) {
3781 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003782 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003783 *isSupported = true;
3784 }
3785 break;
3786 case CAMERA_DEVICE_API_VERSION_3_2:
3787 case CAMERA_DEVICE_API_VERSION_3_3:
3788 case CAMERA_DEVICE_API_VERSION_3_4:
3789 case CAMERA_DEVICE_API_VERSION_3_5:
3790 case CAMERA_DEVICE_API_VERSION_3_6:
3791 case CAMERA_DEVICE_API_VERSION_3_7:
3792 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003793 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003794 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003795 break;
3796 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003797 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3798 deviceVersion, cameraId.c_str());
3799 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3800 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003801 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003802 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003803 } else {
3804 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003805 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003806 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003807}
3808
Austin Borgered99f642023-06-01 16:51:35 -07003809Status CameraService::isHiddenPhysicalCamera(const std::string& unresolvedCameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003810 /*out*/ bool *isSupported) {
3811 ATRACE_CALL();
3812
malikakashedb38962023-09-06 00:03:35 +00003813 const std::string cameraId = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08003814 getCallingUid());
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003815
Austin Borgered99f642023-06-01 16:51:35 -07003816 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3817 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003818
3819 return Status::ok();
3820}
3821
Cliff Wud8cae102021-03-11 01:37:42 +08003822Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003823 const std::string& packageName, const std::string& internalCamId,
3824 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003825 const sp<ICameraInjectionCallback>& callback,
3826 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003827 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003828 ATRACE_CALL();
3829
Austin Borgered99f642023-06-01 16:51:35 -07003830 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003831 const int pid = getCallingPid();
3832 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003833 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3834 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003835 "Permission Denial: no permission to inject camera");
3836 }
3837
3838 // Do not allow any camera injection that injects or replaces a virtual camera.
3839 auto [deviceIdForInternalCamera, _] =
3840 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3841 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3842 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3843 "Cannot replace a virtual camera");
3844 }
3845 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3846 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3847 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3848 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3849 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003850 }
3851
3852 ALOGV(
3853 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3854 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003855 __FUNCTION__, packageName.c_str(),
3856 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003857
Cliff Wud3a05312021-04-26 23:07:31 +08003858 {
3859 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003860 mInjectionInternalCamId = internalCamId;
3861 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003862 mInjectionStatusListener->addListener(callback);
3863 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003864 status_t res = NO_ERROR;
3865 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3866 // If the client already exists, we can directly connect to the camera device through the
3867 // client's injectCamera(), otherwise we need to wait until the client is established
3868 // (execute connectHelper()) before injecting the camera to the camera device.
3869 if (clientDescriptor != nullptr) {
3870 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003871 sp<BasicClient> clientSp = clientDescriptor->getValue();
3872 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3873 if(res != OK) {
3874 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3875 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003876 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003877 }
3878 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003879 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003880 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3881 }
3882 } else {
3883 mInjectionInitPending = true;
3884 }
3885 }
Cliff Wud8cae102021-03-11 01:37:42 +08003886
Cliff Wud3a05312021-04-26 23:07:31 +08003887 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003888}
3889
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003890Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003891 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003892 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3893 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3894 return Status::ok();
3895}
3896
Ruben Brunkcc776712015-02-17 20:18:47 -08003897void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003898 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003899 for (auto& i : mActiveClientManager.getAll()) {
3900 auto clientSp = i->getValue();
3901 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003902 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003903 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003904 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003905 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003906 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003907}
3908
Ruben Brunkcc776712015-02-17 20:18:47 -08003909bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003910 bool ret = false;
3911 {
3912 // Acquire mServiceLock and prevent other clients from connecting
3913 std::unique_ptr<AutoConditionLock> lock =
3914 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003915
Ruben Brunkcc776712015-02-17 20:18:47 -08003916 std::vector<sp<BasicClient>> evicted;
3917 for (auto& i : mActiveClientManager.getAll()) {
3918 auto clientSp = i->getValue();
3919 if (clientSp.get() == nullptr) {
3920 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3921 mActiveClientManager.remove(i);
3922 continue;
3923 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003924 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003925 mActiveClientManager.remove(i);
3926 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003927
Ruben Brunkcc776712015-02-17 20:18:47 -08003928 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003929 clientSp->notifyError(
3930 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003931 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003932 }
3933 }
3934
Ruben Brunkcc776712015-02-17 20:18:47 -08003935 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3936 // other clients from connecting in mServiceLockWrapper if held
3937 mServiceLock.unlock();
3938
Ruben Brunk36597b22015-03-20 22:15:57 -07003939 // Do not clear caller identity, remote caller should be client proccess
3940
Ruben Brunkcc776712015-02-17 20:18:47 -08003941 for (auto& i : evicted) {
3942 if (i.get() != nullptr) {
3943 i->disconnect();
3944 ret = true;
3945 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003946 }
3947
Ruben Brunkcc776712015-02-17 20:18:47 -08003948 // Reacquire mServiceLock
3949 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003950
Ruben Brunkcc776712015-02-17 20:18:47 -08003951 } // lock is destroyed, allow further connect calls
3952
3953 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003954}
3955
Ruben Brunkcc776712015-02-17 20:18:47 -08003956std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003957 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003958 std::shared_ptr<CameraState> state;
3959 {
3960 Mutex::Autolock lock(mCameraStatesLock);
3961 auto iter = mCameraStates.find(cameraId);
3962 if (iter != mCameraStates.end()) {
3963 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003964 }
3965 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003966 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003967}
3968
Austin Borgered99f642023-06-01 16:51:35 -07003969sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003970 // Remove from active clients list
3971 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3972 if (clientDescriptorPtr == nullptr) {
3973 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003974 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003975 return sp<BasicClient>{nullptr};
3976 }
3977
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003978 sp<BasicClient> client = clientDescriptorPtr->getValue();
3979 if (client.get() != nullptr) {
3980 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3981 }
3982 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003983}
3984
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003985void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003986 // Acquire mServiceLock and prevent other clients from connecting
3987 std::unique_ptr<AutoConditionLock> lock =
3988 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3989
Ruben Brunk6267b532015-04-30 17:44:07 -07003990 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003991 for (size_t i = 0; i < newUserIds.size(); i++) {
3992 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003993 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003994 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003995 return;
3996 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003997 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003998 }
3999
Ruben Brunka8ca9152015-04-07 14:23:40 -07004000
Ruben Brunk6267b532015-04-30 17:44:07 -07004001 if (newAllowedUsers == mAllowedUsers) {
4002 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
4003 return;
4004 }
4005
4006 logUserSwitch(mAllowedUsers, newAllowedUsers);
4007
4008 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07004009
4010 // Current user has switched, evict all current clients.
4011 std::vector<sp<BasicClient>> evicted;
4012 for (auto& i : mActiveClientManager.getAll()) {
4013 auto clientSp = i->getValue();
4014
4015 if (clientSp.get() == nullptr) {
4016 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
4017 continue;
4018 }
4019
Ruben Brunk6267b532015-04-30 17:44:07 -07004020 // Don't evict clients that are still allowed.
4021 uid_t clientUid = clientSp->getClientUid();
4022 userid_t clientUserId = multiuser_get_user_id(clientUid);
4023 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
4024 continue;
4025 }
4026
Ruben Brunk36597b22015-03-20 22:15:57 -07004027 evicted.push_back(clientSp);
4028
Ruben Brunk36597b22015-03-20 22:15:57 -07004029 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07004030 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07004031
Ruben Brunk36597b22015-03-20 22:15:57 -07004032 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004033 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00004034 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07004035 " to user switch.", i->getKey().c_str(),
4036 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00004037 i->getOwnerId(), i->getPriority().getScore(),
4038 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07004039
4040 }
4041
4042 // Do not hold mServiceLock while disconnecting clients, but retain the condition
4043 // blocking other clients from connecting in mServiceLockWrapper if held.
4044 mServiceLock.unlock();
4045
4046 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08004047 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07004048
4049 for (auto& i : evicted) {
4050 i->disconnect();
4051 }
4052
Austin Borger22c5c852024-03-08 13:31:36 -08004053 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07004054
4055 // Reacquire mServiceLock
4056 mServiceLock.lock();
4057}
Ruben Brunkcc776712015-02-17 20:18:47 -08004058
Austin Borgered99f642023-06-01 16:51:35 -07004059void CameraService::logEvent(const std::string &event) {
4060 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07004061 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07004062 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07004063 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07004064 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07004065 mEventLog.add(msg);
4066 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
4067 // Error event not added to the dumpsys log before
4068 mEventLog.add(msg);
4069 sServiceErrorEventSet.insert(msg);
4070 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004071}
4072
Austin Borgered99f642023-06-01 16:51:35 -07004073void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
4074 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004075 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004076 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
4077 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004078}
4079
Austin Borgered99f642023-06-01 16:51:35 -07004080void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
4081 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004082 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004083 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
4084 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004085}
4086
Austin Borgered99f642023-06-01 16:51:35 -07004087void CameraService::logConnected(const std::string &cameraId, int clientPid,
4088 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004089 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004090 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
4091 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004092}
4093
Austin Borgered99f642023-06-01 16:51:35 -07004094void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
4095 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004096 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004097 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
4098 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004099}
4100
Austin Borgered99f642023-06-01 16:51:35 -07004101void CameraService::logRejected(const std::string &cameraId, int clientPid,
4102 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004103 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07004104 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
4105 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004106}
4107
Austin Borgered99f642023-06-01 16:51:35 -07004108void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
4109 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07004110 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07004111 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
4112 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07004113}
4114
Ruben Brunk6267b532015-04-30 17:44:07 -07004115void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
4116 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07004117 std::string newUsers = toString(newUserIds);
4118 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004119 if (oldUsers.size() == 0) {
4120 oldUsers = "<None>";
4121 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07004122 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07004123 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
4124 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004125}
4126
Austin Borgered99f642023-06-01 16:51:35 -07004127void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004128 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004129 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004130}
4131
Austin Borgered99f642023-06-01 16:51:35 -07004132void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004133 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004134 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004135}
4136
Austin Borgered99f642023-06-01 16:51:35 -07004137void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004138 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004139 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07004140}
4141
Austin Borgered99f642023-06-01 16:51:35 -07004142void CameraService::logServiceError(const std::string &msg, int errorCode) {
4143 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
4144 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004145}
4146
Ruben Brunk36597b22015-03-20 22:15:57 -07004147status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4148 uint32_t flags) {
4149
Mathias Agopian65ab4712010-07-14 17:59:35 -07004150 // Permission checks
4151 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004152 case SHELL_COMMAND_TRANSACTION: {
4153 int in = data.readFileDescriptor();
4154 int out = data.readFileDescriptor();
4155 int err = data.readFileDescriptor();
4156 int argc = data.readInt32();
4157 Vector<String16> args;
4158 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
4159 args.add(data.readString16());
4160 }
4161 sp<IBinder> unusedCallback;
4162 sp<IResultReceiver> resultReceiver;
4163 status_t status;
4164 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
4165 return status;
4166 }
4167 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
4168 return status;
4169 }
4170 status = shellCommand(in, out, err, args);
4171 if (resultReceiver != nullptr) {
4172 resultReceiver->send(status);
4173 }
4174 return NO_ERROR;
4175 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004176 }
4177
4178 return BnCameraService::onTransact(code, data, reply, flags);
4179}
4180
Mathias Agopian65ab4712010-07-14 17:59:35 -07004181// We share the media players for shutter and recording sound for all clients.
4182// A reference count is kept to determine when we will actually release the
4183// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09004184sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
4185 sp<MediaPlayer> mp = new MediaPlayer();
4186 status_t error;
4187 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08004188 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09004189 error = mp->prepare();
4190 }
4191 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004192 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09004193 mp->disconnect();
4194 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004195 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004196 }
4197 return mp;
4198}
4199
username5755fea2018-12-27 09:48:08 +08004200void CameraService::increaseSoundRef() {
4201 Mutex::Autolock lock(mSoundLock);
4202 mSoundRef++;
4203}
4204
4205void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004206 ATRACE_CALL();
4207
username5755fea2018-12-27 09:48:08 +08004208 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
4209 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
4210 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
4211 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
4212 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4213 }
4214 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
4215 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4216 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4217 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004218 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08004219 }
4220 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4221 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4222 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4223 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4224 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004225 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004226}
4227
username5755fea2018-12-27 09:48:08 +08004228void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004229 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004230 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004231 if (--mSoundRef) return;
4232
4233 for (int i = 0; i < NUM_SOUNDS; i++) {
4234 if (mSoundPlayer[i] != 0) {
4235 mSoundPlayer[i]->disconnect();
4236 mSoundPlayer[i].clear();
4237 }
4238 }
4239}
4240
4241void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004242 ATRACE_CALL();
4243
Mathias Agopian65ab4712010-07-14 17:59:35 -07004244 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004245 if (kind < 0 || kind >= NUM_SOUNDS) {
4246 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4247 return;
4248 }
4249
Mathias Agopian65ab4712010-07-14 17:59:35 -07004250 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004251 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004252 sp<MediaPlayer> player = mSoundPlayer[kind];
4253 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004254 player->seekTo(0);
4255 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004256 }
4257}
4258
4259// ----------------------------------------------------------------------------
4260
4261CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004262 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004263 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004264 const std::string& clientPackageName, bool systemNativeClient,
4265 const std::optional<std::string>& clientFeatureId,
4266 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004267 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004268 int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004269 int servicePid, int rotationOverride) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004270 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004271 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07004272 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004273 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004274 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004275 clientPid, clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004276 servicePid, rotationOverride),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004277 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004278{
Austin Borger22c5c852024-03-08 13:31:36 -08004279 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004280 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004281
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004282 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004283
username5755fea2018-12-27 09:48:08 +08004284 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004285
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004286 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004287}
4288
Mathias Agopian65ab4712010-07-14 17:59:35 -07004289// tear down the client
4290CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004291 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004292 mDestructionStarted = true;
4293
username5755fea2018-12-27 09:48:08 +08004294 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004295 // unconditionally disconnect. function is idempotent
4296 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004297}
4298
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004299sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4300
Igor Murashkin634a5152013-02-20 17:15:11 -08004301CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004302 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004303 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004304 const std::string& clientPackageName, bool nativeClient,
4305 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004306 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004307 int servicePid, int rotationOverride):
Austin Borger249e6592024-03-10 22:28:11 -07004308 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004309 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004310 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004311 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4312 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004313 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004314 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004315 mDisconnected(false), mUidIsTrusted(false),
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004316 mRotationOverride(rotationOverride),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004317 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004318 mRemoteBinder(remoteCallback),
4319 mOpsActive(false),
4320 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004321{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004322 if (sCameraService == nullptr) {
4323 sCameraService = cameraService;
4324 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004325
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004326 // There are 2 scenarios in which a client won't have AppOps operations
4327 // (both scenarios : native clients)
4328 // 1) It's an system native client*, the package name will be empty
4329 // and it will return from this function in the previous if condition
4330 // (This is the same as the previously existing behavior).
4331 // 2) It is a system native client, but its package name has been
4332 // modified for debugging, however it still must not use AppOps since
4333 // the package name is not a real one.
4334 //
4335 // * system native client - native client with UID < AID_APP_START. It
4336 // doesn't exclude clients not on the system partition.
4337 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004338 mAppOpsManager = std::make_unique<AppOpsManager>();
4339 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004340
Charles Chenf075f082024-03-04 23:32:55 +00004341 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004342}
4343
4344CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004345 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004346 mDestructionStarted = true;
4347}
4348
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004349binder::Status CameraService::BasicClient::disconnect() {
4350 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004351 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004352 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004353 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004354 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004355
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004356 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004357 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004358 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004359 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004360
4361 sp<IBinder> remote = getRemote();
4362 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004363 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004364 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004365
4366 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004367 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004368 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004369 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004370 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004371
Igor Murashkincba2c162013-03-20 15:56:31 -07004372 // client shouldn't be able to call into us anymore
4373 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004374
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004375 const auto& mActivityManager = getActivityManager();
4376 if (mActivityManager) {
4377 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004378 getCallingUid(),
4379 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004380 }
4381
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004382 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004383}
4384
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004385status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4386 // No dumping of clients directly over Binder,
4387 // must go through CameraService::dump
4388 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004389 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004390 return OK;
4391}
4392
Austin Borgered99f642023-06-01 16:51:35 -07004393status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004394 // Can't watch tags directly, must go through CameraService::startWatchingTags
4395 return OK;
4396}
4397
4398status_t CameraService::BasicClient::stopWatchingTags(int) {
4399 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4400 return OK;
4401}
4402
4403status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4404 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4405 return OK;
4406}
4407
Austin Borgered99f642023-06-01 16:51:35 -07004408std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004409 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004410}
4411
Emilian Peev8b64f282021-03-25 16:49:57 -07004412int CameraService::BasicClient::getCameraFacing() const {
4413 return mCameraFacing;
4414}
4415
4416int CameraService::BasicClient::getCameraOrientation() const {
4417 return mOrientation;
4418}
Ruben Brunkcc776712015-02-17 20:18:47 -08004419
4420int CameraService::BasicClient::getClientPid() const {
4421 return mClientPid;
4422}
4423
Ruben Brunk6267b532015-04-30 17:44:07 -07004424uid_t CameraService::BasicClient::getClientUid() const {
4425 return mClientUid;
4426}
4427
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004428bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4429 // Defaults to API2.
4430 return level == API_2;
4431}
4432
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004433status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004434 {
4435 Mutex::Autolock l(mAudioRestrictionLock);
4436 mAudioRestriction = mode;
4437 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004438 sCameraService->updateAudioRestriction();
4439 return OK;
4440}
4441
4442int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004443 return sCameraService->updateAudioRestriction();
4444}
4445
4446int32_t CameraService::BasicClient::getAudioRestriction() const {
4447 Mutex::Autolock l(mAudioRestrictionLock);
4448 return mAudioRestriction;
4449}
4450
4451bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4452 switch (mode) {
4453 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4454 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4455 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4456 return true;
4457 default:
4458 return false;
4459 }
4460}
4461
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004462status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4463 if (mode == AppOpsManager::MODE_ERRORED) {
4464 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004465 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004466 return PERMISSION_DENIED;
4467 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4468 // If the calling Uid is trusted (a native service), the AppOpsManager could
4469 // return MODE_IGNORED. Do not treat such case as error.
4470 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4471 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004472
4473 bool isCameraPrivacyEnabled;
4474 if (flags::camera_privacy_allowlist()) {
4475 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4476 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4477 } else {
4478 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004479 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004480 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004481 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4482 // We prefer to successfully open the camera and perform camera muting
4483 // or blocking in connectHelper as handleAppOpMode can be called before the
4484 // connection has been fully established and at that time camera muting
4485 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004486 if (!isUidActive || !isCameraPrivacyEnabled) {
Austin Borgerfd05d982024-04-22 15:54:50 -07004487 ALOGI("Camera %s: Access for \"%s\" has been restricted."
4488 "uid active: %s, privacy enabled: %s", mCameraIdStr.c_str(),
4489 mClientPackageName.c_str(), isUidActive ? "true" : "false",
4490 isCameraPrivacyEnabled ? "true" : "false");
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004491 // Return the same error as for device policy manager rejection
4492 return -EACCES;
4493 }
4494 }
4495 return OK;
4496}
4497
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004498status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004499 ATRACE_CALL();
4500
Igor Murashkine6800ce2013-03-04 17:25:57 -08004501 {
4502 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004503 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004504 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004505 if (mAppOpsManager != nullptr) {
4506 // Notify app ops that the camera is not available
4507 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004508
4509 if (flags::watch_foreground_changes()) {
4510 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4511 toString16(mClientPackageName),
4512 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4513 } else {
4514 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004515 toString16(mClientPackageName), mOpsCallback);
Austin Borgerca1e0062023-06-28 11:32:55 -07004516 }
Igor Murashkine6800ce2013-03-04 17:25:57 -08004517
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004518 // Just check for camera acccess here on open - delay startOp until
4519 // camera frames start streaming in startCameraStreamingOps
4520 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004521 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004522 status_t res = handleAppOpMode(mode);
4523 if (res != OK) {
4524 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004525 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004526 }
4527
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004528 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004529
4530 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004531 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004532
Austin Borgerdddb7552023-03-30 17:53:01 -07004533 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004534
Shuzhen Wang695044d2020-03-06 09:02:23 -08004535 // Notify listeners of camera open/close status
4536 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4537
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004538 return OK;
4539}
4540
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004541status_t CameraService::BasicClient::startCameraStreamingOps() {
4542 ATRACE_CALL();
4543
4544 if (!mOpsActive) {
4545 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4546 return INVALID_OPERATION;
4547 }
4548 if (mOpsStreaming) {
4549 ALOGV("%s: Streaming already active!", __FUNCTION__);
4550 return OK;
4551 }
4552
4553 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004554 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004555
4556 if (mAppOpsManager != nullptr) {
4557 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004558 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4559 toString16(mClientFeatureId),
4560 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004561 status_t res = handleAppOpMode(mode);
4562 if (res != OK) {
4563 return res;
4564 }
4565 }
4566
4567 mOpsStreaming = true;
4568
4569 return OK;
4570}
4571
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004572status_t CameraService::BasicClient::noteAppOp() {
4573 ATRACE_CALL();
4574
4575 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004576 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004577
4578 // noteAppOp is only used for when camera mute is not supported, in order
4579 // to trigger the sensor privacy "Unblock" dialog
4580 if (mAppOpsManager != nullptr) {
4581 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004582 toString16(mClientPackageName), toString16(mClientFeatureId),
4583 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004584 status_t res = handleAppOpMode(mode);
4585 if (res != OK) {
4586 return res;
4587 }
4588 }
4589
4590 return OK;
4591}
4592
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004593status_t CameraService::BasicClient::finishCameraStreamingOps() {
4594 ATRACE_CALL();
4595
4596 if (!mOpsActive) {
4597 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4598 return INVALID_OPERATION;
4599 }
4600 if (!mOpsStreaming) {
4601 ALOGV("%s: Streaming not active!", __FUNCTION__);
4602 return OK;
4603 }
4604
4605 if (mAppOpsManager != nullptr) {
4606 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004607 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004608 mOpsStreaming = false;
4609 }
4610
4611 return OK;
4612}
4613
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004614status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004615 ATRACE_CALL();
4616
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004617 if (mOpsStreaming) {
4618 // Make sure we've notified everyone about camera stopping
4619 finishCameraStreamingOps();
4620 }
4621
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004622 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004623 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004624 mOpsActive = false;
4625
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004626 // This function is called when a client disconnects. This should
4627 // release the camera, but actually only if it was in a proper
4628 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004629 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004630 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004631
Ruben Brunkcc776712015-02-17 20:18:47 -08004632 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004633 sCameraService->updateStatus(StatusInternal::PRESENT,
4634 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004635 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004636 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004637 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4638 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004639 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004640 mOpsCallback.clear();
4641
Austin Borgerdddb7552023-03-30 17:53:01 -07004642 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004643
Shuzhen Wang695044d2020-03-06 09:02:23 -08004644 // Notify listeners of camera open/close status
4645 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4646
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004647 return OK;
4648}
4649
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004650void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004651 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004652 if (mAppOpsManager == nullptr) {
4653 return;
4654 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004655 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004656 if (op != AppOpsManager::OP_CAMERA) {
4657 ALOGW("Unexpected app ops notification received: %d", op);
4658 return;
4659 }
4660
4661 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004662 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004663 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004664 ALOGV("checkOp returns: %d, %s ", res,
4665 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4666 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4667 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4668 "UNKNOWN");
4669
Shuzhen Wang64900852021-02-05 09:03:29 -08004670 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004671 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4672 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004673 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004674 } else if (res == AppOpsManager::MODE_IGNORED) {
4675 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004676
Austin Borgerca1e0062023-06-28 11:32:55 -07004677 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4678 // If not visible, but still active, then we want to block instead of muting the camera.
4679 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4680 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4681
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004682 bool isCameraPrivacyEnabled;
4683 if (flags::camera_privacy_allowlist()) {
4684 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4685 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4686 } else {
4687 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004688 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004689 }
4690
4691 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004692 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4693 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4694 isCameraPrivacyEnabled);
4695 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4696 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4697 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004698 if (!mUidIsTrusted) {
Austin Borgerca1e0062023-06-28 11:32:55 -07004699 if (flags::watch_foreground_changes()) {
4700 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4701 setCameraMute(true);
4702 } else {
4703 block();
4704 }
4705 } else {
4706 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4707 setCameraMute(true);
4708 } else if (!isUidActive
4709 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4710 block();
4711 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004712 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004713 }
Evan Severson09ab4002021-02-10 14:15:19 -08004714 } else if (res == AppOpsManager::MODE_ALLOWED) {
4715 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004716 }
4717}
4718
Svet Ganova453d0d2018-01-11 15:37:58 -08004719void CameraService::BasicClient::block() {
4720 ATRACE_CALL();
4721
4722 // Reset the client PID to allow server-initiated disconnect,
4723 // and to prevent further calls by client.
Austin Borger22c5c852024-03-08 13:31:36 -08004724 mClientPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004725 CaptureResultExtras resultExtras; // a dummy result (invalid)
4726 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4727 disconnect();
4728}
4729
Mathias Agopian65ab4712010-07-14 17:59:35 -07004730// ----------------------------------------------------------------------------
4731
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004732void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004733 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004734 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004735 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4736 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4737 api1ErrorCode = CAMERA_ERROR_DISABLED;
4738 }
4739 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004740 } else {
4741 ALOGE("mRemoteCallback is NULL!!");
4742 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004743}
4744
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004745// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004746binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004747 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004748 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004749}
4750
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004751bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4752 return level == API_1;
4753}
4754
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004755CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4756 mClient(client) {
4757}
4758
4759void CameraService::Client::OpsCallback::opChanged(int32_t op,
4760 const String16& packageName) {
4761 sp<BasicClient> client = mClient.promote();
4762 if (client != NULL) {
4763 client->opChanged(op, packageName);
4764 }
4765}
4766
Mathias Agopian65ab4712010-07-14 17:59:35 -07004767// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004768// UidPolicy
4769// ----------------------------------------------------------------------------
4770
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004771void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004772 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004773 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004774
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004775 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004776 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004777 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004778 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004779 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4780 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004781 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004782 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004783 if (res == OK) {
4784 mRegistered = true;
4785 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004786 } else {
4787 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004788 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004789}
4790
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004791void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004792 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004793 return;
4794 }
4795
4796 registerWithActivityManager();
4797}
4798
4799void CameraService::UidPolicy::registerSelf() {
4800 // Use check service to see if the activity service is available
4801 // If not available then register for notifications, instead of blocking
4802 // till the service is ready
4803 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004804 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004805 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004806 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004807 } else {
4808 registerWithActivityManager();
4809 }
4810}
4811
Svet Ganova453d0d2018-01-11 15:37:58 -08004812void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004813 Mutex::Autolock _l(mUidLock);
4814
Steven Moreland2f348142019-07-02 15:59:07 -07004815 mAm.unregisterUidObserver(this);
4816 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004817 mRegistered = false;
4818 mActiveUids.clear();
4819 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004820}
4821
4822void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4823 onUidIdle(uid, disabled);
4824}
4825
4826void CameraService::UidPolicy::onUidActive(uid_t uid) {
4827 Mutex::Autolock _l(mUidLock);
4828 mActiveUids.insert(uid);
4829}
4830
4831void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4832 bool deleted = false;
4833 {
4834 Mutex::Autolock _l(mUidLock);
4835 if (mActiveUids.erase(uid) > 0) {
4836 deleted = true;
4837 }
4838 }
4839 if (deleted) {
4840 sp<CameraService> service = mService.promote();
4841 if (service != nullptr) {
4842 service->blockClientsForUid(uid);
4843 }
4844 }
4845}
4846
Emilian Peev53722fa2019-02-22 17:47:20 -08004847void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004848 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004849 bool procStateChange = false;
4850 {
4851 Mutex::Autolock _l(mUidLock);
4852 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4853 mMonitoredUids[uid].procState != procState) {
4854 mMonitoredUids[uid].procState = procState;
4855 procStateChange = true;
4856 }
4857 }
4858
4859 if (procStateChange) {
4860 sp<CameraService> service = mService.promote();
4861 if (service != nullptr) {
4862 service->notifyMonitoredUids();
4863 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004864 }
4865}
4866
Austin Borgerdddb7552023-03-30 17:53:01 -07004867/**
4868 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4869 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4870 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4871 * monitoredUids. If it is revised above some other monitoredUid, signal
4872 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4873 * foreground apps in split screen - state changes will capture all other cases.
4874 */
4875void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4876 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004877 {
4878 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004879 auto it = mMonitoredUids.find(uid);
4880
4881 if (it != mMonitoredUids.end()) {
4882 if (it->second.hasCamera) {
4883 for (auto &monitoredUid : mMonitoredUids) {
4884 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004885 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004886 notifyUidSet.emplace(monitoredUid.first);
4887 }
4888 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004889 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004890 notifyUidSet.emplace(uid);
4891 } else {
4892 for (auto &monitoredUid : mMonitoredUids) {
4893 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004894 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004895 notifyUidSet.emplace(uid);
4896 }
4897 }
4898 }
4899 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004900 }
4901 }
4902
Austin Borgerdddb7552023-03-30 17:53:01 -07004903 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004904 sp<CameraService> service = mService.promote();
4905 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004906 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004907 }
4908 }
4909}
4910
Austin Borgerdddb7552023-03-30 17:53:01 -07004911/**
4912 * Register a uid for monitoring, and note whether it owns a camera.
4913 */
4914void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004915 Mutex::Autolock _l(mUidLock);
4916 auto it = mMonitoredUids.find(uid);
4917 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004918 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004919 } else {
Austin Borger65577682022-02-17 00:25:43 +00004920 MonitoredUid monitoredUid;
4921 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004922 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004923 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004924 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004925 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004926 if (res != OK) {
4927 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4928 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004929 }
4930
4931 if (openCamera) {
4932 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004933 }
4934}
4935
Austin Borgerdddb7552023-03-30 17:53:01 -07004936/**
4937 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4938 */
4939void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004940 Mutex::Autolock _l(mUidLock);
4941 auto it = mMonitoredUids.find(uid);
4942 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004943 it->second.refCount--;
4944 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004945 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004946 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004947 if (res != OK) {
4948 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4949 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004950 } else if (closeCamera) {
4951 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004952 }
4953 } else {
4954 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4955 }
4956}
4957
Austin Borgered99f642023-06-01 16:51:35 -07004958bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004959 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004960 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004961}
4962
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004963static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4964static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004965
Austin Borgered99f642023-06-01 16:51:35 -07004966bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004967 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004968 // If activity manager is unreachable, assume everything is active
4969 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004970 return true;
4971 }
4972 auto it = mOverrideUids.find(uid);
4973 if (it != mOverrideUids.end()) {
4974 return it->second;
4975 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004976 bool active = mActiveUids.find(uid) != mActiveUids.end();
4977 if (!active) {
4978 // We want active UIDs to always access camera with their first attempt since
4979 // there is no guarantee the app is robustly written and would retry getting
4980 // the camera on failure. The inverse case is not a problem as we would take
4981 // camera away soon once we get the callback that the uid is no longer active.
4982 ActivityManager am;
4983 // Okay to access with a lock held as UID changes are dispatched without
4984 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004985 int64_t startTimeMillis = 0;
4986 do {
4987 // TODO: Fix this b/109950150!
4988 // Okay this is a hack. There is a race between the UID turning active and
4989 // activity being resumed. The proper fix is very risky, so we temporary add
4990 // some polling which should happen pretty rarely anyway as the race is hard
4991 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004992 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004993 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004994 if (active) {
4995 break;
4996 }
4997 if (startTimeMillis <= 0) {
4998 startTimeMillis = uptimeMillis();
4999 }
5000 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07005001 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07005002 if (remainingTimeMillis <= 0) {
5003 break;
5004 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07005005 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
5006
5007 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07005008 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07005009 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07005010 } while (true);
5011
Svet Ganov7b4ab782018-03-25 12:48:10 -07005012 if (active) {
5013 // Now that we found out the UID is actually active, cache that
5014 mActiveUids.insert(uid);
5015 }
5016 }
5017 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08005018}
5019
Varun Shahb42f1eb2019-04-16 14:45:13 -07005020int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
5021 Mutex::Autolock _l(mUidLock);
5022 return getProcStateLocked(uid);
5023}
5024
5025int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
5026 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
5027 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00005028 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07005029 }
5030 return procState;
5031}
5032
Austin Borgered99f642023-06-01 16:51:35 -07005033void CameraService::UidPolicy::addOverrideUid(uid_t uid,
5034 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07005035 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08005036}
5037
Austin Borgered99f642023-06-01 16:51:35 -07005038void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07005039 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08005040}
5041
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07005042void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
5043 Mutex::Autolock _l(mUidLock);
5044 ALOGV("UidPolicy: ActivityManager has died");
5045 mRegistered = false;
5046 mActiveUids.clear();
5047}
5048
Austin Borgered99f642023-06-01 16:51:35 -07005049void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07005050 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005051 bool wasActive = false;
5052 bool isActive = false;
5053 {
5054 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07005055 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08005056 mOverrideUids.erase(uid);
5057 if (insert) {
5058 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
5059 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07005060 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08005061 }
5062 if (wasActive != isActive && !isActive) {
5063 sp<CameraService> service = mService.promote();
5064 if (service != nullptr) {
5065 service->blockClientsForUid(uid);
5066 }
5067 }
5068}
5069
5070// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08005071// SensorPrivacyPolicy
5072// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005073
5074void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
5075{
Michael Grooverd1d435a2018-12-18 17:39:42 -08005076 Mutex::Autolock _l(mSensorPrivacyLock);
5077 if (mRegistered) {
5078 return;
5079 }
Evan Severson09ab4002021-02-10 14:15:19 -08005080 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08005081 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00005082 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005083 mSpm.addToggleSensorPrivacyListener(this);
5084 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005085 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005086 if (flags::camera_privacy_allowlist()) {
5087 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
5088 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
5089 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5090 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005091 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005092 if (res == OK) {
5093 mRegistered = true;
5094 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
5095 }
5096}
5097
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005098void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
5099 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07005100 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005101 return;
5102 }
5103
5104 registerWithSensorPrivacyManager();
5105}
5106
5107void CameraService::SensorPrivacyPolicy::registerSelf() {
5108 // Use checkservice to see if the sensor_privacy service is available
5109 // If service is not available then register for notification
5110 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07005111 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005112 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07005113 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005114 } else {
5115 registerWithSensorPrivacyManager();
5116 }
5117}
5118
Michael Grooverd1d435a2018-12-18 17:39:42 -08005119void CameraService::SensorPrivacyPolicy::unregisterSelf() {
5120 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08005121 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00005122 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005123 mSpm.removeToggleSensorPrivacyListener(this);
5124 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005125 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005126 mRegistered = false;
5127 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
5128}
5129
5130bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005131 if (!mRegistered) {
5132 registerWithSensorPrivacyManager();
5133 }
5134
Michael Grooverd1d435a2018-12-18 17:39:42 -08005135 Mutex::Autolock _l(mSensorPrivacyLock);
5136 return mSensorPrivacyEnabled;
5137}
5138
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005139int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
5140 if (!mRegistered) {
5141 registerWithSensorPrivacyManager();
5142 }
5143
5144 Mutex::Autolock _l(mSensorPrivacyLock);
5145 return mCameraPrivacyState;
5146}
5147
Evan Seversond0b69922022-01-27 10:47:34 -08005148bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08005149 if (!hasCameraPrivacyFeature()) {
5150 return false;
5151 }
Evan Seversond0b69922022-01-27 10:47:34 -08005152 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08005153}
5154
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005155bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
5156 if (!hasCameraPrivacyFeature()) {
Jyoti Bhayana5882b032024-04-26 11:18:58 -07005157 return false;
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005158 }
5159 return mSpm.isCameraPrivacyEnabled(packageName);
5160}
5161
Evan Seversond0b69922022-01-27 10:47:34 -08005162binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005163 int toggleType, int sensor, bool enabled) {
5164 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
5165 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
5166 {
5167 Mutex::Autolock _l(mSensorPrivacyLock);
5168 mSensorPrivacyEnabled = enabled;
5169 }
5170 // if sensor privacy is enabled then block all clients from accessing the camera
5171 if (enabled) {
5172 sp<CameraService> service = mService.promote();
5173 if (service != nullptr) {
5174 service->blockAllClients();
5175 }
5176 }
5177 }
5178 return binder::Status::ok();
5179}
5180
5181binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
5182 int, int sensor, int state) {
5183 if (!flags::camera_privacy_allowlist()
5184 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
5185 return binder::Status::ok();
5186 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08005187 {
5188 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005189 mCameraPrivacyState = state;
5190 }
5191 sp<CameraService> service = mService.promote();
5192 if (!service) {
5193 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005194 }
5195 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005196 if (state == SensorPrivacyManager::ENABLED) {
5197 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08005198 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005199 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005200 }
5201 return binder::Status::ok();
5202}
5203
5204void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
5205 Mutex::Autolock _l(mSensorPrivacyLock);
5206 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
5207 mRegistered = false;
5208}
5209
Evan Severson09ab4002021-02-10 14:15:19 -08005210bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08005211 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
5212 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5213 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
5214 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5215 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08005216}
5217
Michael Grooverd1d435a2018-12-18 17:39:42 -08005218// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005219// CameraState
5220// ----------------------------------------------------------------------------
5221
Austin Borgered99f642023-06-01 16:51:35 -07005222CameraService::CameraState::CameraState(const std::string& id, int cost,
5223 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005224 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005225 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005226 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005227
5228CameraService::CameraState::~CameraState() {}
5229
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005230CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005231 Mutex::Autolock lock(mStatusLock);
5232 return mStatus;
5233}
5234
Austin Borgered99f642023-06-01 16:51:35 -07005235std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005236 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005237 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005238 return res;
5239}
5240
Ruben Brunkcc776712015-02-17 20:18:47 -08005241CameraParameters CameraService::CameraState::getShimParams() const {
5242 return mShimParams;
5243}
5244
5245void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5246 mShimParams = params;
5247}
5248
5249int CameraService::CameraState::getCost() const {
5250 return mCost;
5251}
5252
Austin Borgered99f642023-06-01 16:51:35 -07005253std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005254 return mConflicting;
5255}
5256
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005257SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5258 return mSystemCameraKind;
5259}
5260
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005261bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5262 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5263 != mPhysicalCameras.end();
5264}
5265
Austin Borgered99f642023-06-01 16:51:35 -07005266bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005267 Mutex::Autolock lock(mStatusLock);
5268 auto result = mUnavailablePhysicalIds.insert(physicalId);
5269 return result.second;
5270}
5271
Austin Borgered99f642023-06-01 16:51:35 -07005272bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005273 Mutex::Autolock lock(mStatusLock);
5274 auto count = mUnavailablePhysicalIds.erase(physicalId);
5275 return count > 0;
5276}
5277
Austin Borgered99f642023-06-01 16:51:35 -07005278void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005279 Mutex::Autolock lock(mStatusLock);
5280 mClientPackage = clientPackage;
5281}
5282
Austin Borgered99f642023-06-01 16:51:35 -07005283std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005284 Mutex::Autolock lock(mStatusLock);
5285 return mClientPackage;
5286}
5287
Ruben Brunkcc776712015-02-17 20:18:47 -08005288// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005289// ClientEventListener
5290// ----------------------------------------------------------------------------
5291
5292void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005293 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005294 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005295 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005296 if (basicClient.get() != nullptr) {
5297 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005298 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005299 static_cast<int>(basicClient->getClientUid()));
5300 }
5301}
5302
5303void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005304 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005305 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005306 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005307 if (basicClient.get() != nullptr) {
5308 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005309 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005310 static_cast<int>(basicClient->getClientUid()));
5311 }
5312}
5313
Ruben Brunk99e69712015-05-26 17:25:07 -07005314// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005315// CameraClientManager
5316// ----------------------------------------------------------------------------
5317
Ruben Brunk99e69712015-05-26 17:25:07 -07005318CameraService::CameraClientManager::CameraClientManager() {
5319 setListener(std::make_shared<ClientEventListener>());
5320}
5321
Ruben Brunkcc776712015-02-17 20:18:47 -08005322CameraService::CameraClientManager::~CameraClientManager() {}
5323
5324sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005325 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005326 auto descriptor = get(id);
5327 if (descriptor == nullptr) {
5328 return sp<BasicClient>{nullptr};
5329 }
5330 return descriptor->getValue();
5331}
5332
Austin Borgered99f642023-06-01 16:51:35 -07005333std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005334 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005335 std::ostringstream ret;
5336 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005337 bool hasAny = false;
5338 for (auto& i : all) {
5339 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005340 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005341 int32_t cost = i->getCost();
5342 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005343 int32_t score = i->getPriority().getScore();
5344 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005345 auto conflicting = i->getConflicting();
5346 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005347 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005348 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005349 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005350 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005351 uid_t clientUid = clientSp->getClientUid();
5352 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005353 }
Austin Borgered99f642023-06-01 16:51:35 -07005354 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5355 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005356
Ruben Brunk6267b532015-04-30 17:44:07 -07005357 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005358 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005359 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005360 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005361 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005362 }
5363
Austin Borgered99f642023-06-01 16:51:35 -07005364 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005365 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005366 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005367 }
Austin Borgered99f642023-06-01 16:51:35 -07005368 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005369 }
Austin Borgered99f642023-06-01 16:51:35 -07005370 if (hasAny) ret << "\n";
5371 ret << "]\n";
5372 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005373}
5374
5375CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005376 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5377 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005378 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005379
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005380 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005381 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005382
Austin Borgered99f642023-06-01 16:51:35 -07005383 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005384 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5385 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005386}
5387
5388CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005389 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005390 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005391 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005392 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005393 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5394 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005395}
5396
5397// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005398// InjectionStatusListener
5399// ----------------------------------------------------------------------------
5400
5401void CameraService::InjectionStatusListener::addListener(
5402 const sp<ICameraInjectionCallback>& callback) {
5403 Mutex::Autolock lock(mListenerLock);
5404 if (mCameraInjectionCallback) return;
5405 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5406 if (res == OK) {
5407 mCameraInjectionCallback = callback;
5408 }
5409}
5410
5411void CameraService::InjectionStatusListener::removeListener() {
5412 Mutex::Autolock lock(mListenerLock);
5413 if (mCameraInjectionCallback == nullptr) {
5414 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5415 return;
5416 }
5417 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5418 mCameraInjectionCallback = nullptr;
5419}
5420
5421void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005422 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005423 if (mCameraInjectionCallback == nullptr) {
5424 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5425 return;
5426 }
Cliff Wud3a05312021-04-26 23:07:31 +08005427
5428 switch (err) {
5429 case -ENODEV:
5430 mCameraInjectionCallback->onInjectionError(
5431 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5432 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005433 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005434 break;
5435 case -EBUSY:
5436 mCameraInjectionCallback->onInjectionError(
5437 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5438 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005439 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005440 break;
5441 case DEAD_OBJECT:
5442 mCameraInjectionCallback->onInjectionError(
5443 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5444 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005445 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005446 break;
5447 case INVALID_OPERATION:
5448 mCameraInjectionCallback->onInjectionError(
5449 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5450 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005451 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005452 break;
5453 case UNKNOWN_TRANSACTION:
5454 mCameraInjectionCallback->onInjectionError(
5455 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5456 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005457 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005458 break;
5459 default:
5460 mCameraInjectionCallback->onInjectionError(
5461 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5462 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005463 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005464 }
Cliff Wud8cae102021-03-11 01:37:42 +08005465}
5466
5467void CameraService::InjectionStatusListener::binderDied(
5468 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005469 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5470 auto parent = mParent.promote();
5471 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005472 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5473 if (clientDescriptor != nullptr) {
5474 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5475 baseClientPtr->stopInjection();
5476 }
Cliff Wu3b268182021-07-06 15:44:43 +08005477 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005478 }
5479}
5480
5481// ----------------------------------------------------------------------------
5482// CameraInjectionSession
5483// ----------------------------------------------------------------------------
5484
5485binder::Status CameraService::CameraInjectionSession::stopInjection() {
5486 Mutex::Autolock lock(mInjectionSessionLock);
5487 auto parent = mParent.promote();
5488 if (parent == nullptr) {
5489 ALOGE("CameraInjectionSession: Parent is gone");
5490 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5491 "Camera service encountered error");
5492 }
Cliff Wud3a05312021-04-26 23:07:31 +08005493
5494 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005495 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5496 if (clientDescriptor != nullptr) {
5497 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5498 res = baseClientPtr->stopInjection();
5499 if (res != OK) {
5500 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5501 " ret != NO_ERROR: %d", res);
5502 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5503 "Camera session encountered error");
5504 }
5505 }
Cliff Wu3b268182021-07-06 15:44:43 +08005506 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005507 return binder::Status::ok();
5508}
5509
5510// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005511
5512static const int kDumpLockRetries = 50;
5513static const int kDumpLockSleep = 60000;
5514
5515static bool tryLock(Mutex& mutex)
5516{
5517 bool locked = false;
5518 for (int i = 0; i < kDumpLockRetries; ++i) {
5519 if (mutex.tryLock() == NO_ERROR) {
5520 locked = true;
5521 break;
5522 }
5523 usleep(kDumpLockSleep);
5524 }
5525 return locked;
5526}
5527
Rucha Katakwardf223072021-06-15 10:21:00 -07005528void CameraService::cacheDump() {
5529 if (mMemFd != -1) {
5530 const Vector<String16> args;
5531 ATRACE_CALL();
5532 // Acquiring service lock here will avoid the deadlock since
5533 // cacheDump will not be called during the second disconnect.
5534 Mutex::Autolock lock(mServiceLock);
5535
5536 Mutex::Autolock l(mCameraStatesLock);
5537 // Start collecting the info for open sessions and store it in temp file.
5538 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005539 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005540 auto clientDescriptor = mActiveClientManager.get(cameraId);
5541 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005542 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005543 // Log the current open session info before device is disconnected.
5544 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5545 }
5546 }
5547 }
5548}
5549
Mathias Agopian65ab4712010-07-14 17:59:35 -07005550status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005551 ATRACE_CALL();
5552
Austin Borgered99f642023-06-01 16:51:35 -07005553 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005554 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005555 getCallingPid(),
5556 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005557 return NO_ERROR;
5558 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005559 bool locked = tryLock(mServiceLock);
5560 // failed to lock - CameraService is probably deadlocked
5561 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005562 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005563 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005564
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005565 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005566 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005567
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005568 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005569 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005570
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005571 if (locked) mServiceLock.unlock();
5572 return NO_ERROR;
5573 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005574 dprintf(fd, "\n== Service global info: ==\n\n");
5575 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005576 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005577 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5578 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005579 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5580 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5581 }
Austin Borgered99f642023-06-01 16:51:35 -07005582 std::string activeClientString = mActiveClientManager.toString();
5583 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5584 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005585 if (mStreamUseCaseOverrides.size() > 0) {
5586 dprintf(fd, "Active stream use case overrides:");
5587 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5588 dprintf(fd, " %" PRId64, useCaseOverride);
5589 }
5590 dprintf(fd, "\n");
5591 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005592
5593 dumpEventLog(fd);
5594
5595 bool stateLocked = tryLock(mCameraStatesLock);
5596 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005597 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005598 }
5599
Emilian Peevbd8c5032018-02-14 23:05:40 +00005600 int argSize = args.size();
5601 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005602 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005603 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005604 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005605 }
5606 break;
5607 }
5608 }
5609
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005610 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005611 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005612
Austin Borgered99f642023-06-01 16:51:35 -07005613 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005614
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005615 CameraParameters p = state.second->getShimParams();
5616 if (!p.isEmpty()) {
5617 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5618 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005619 }
5620
5621 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005622 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005623 // log the current open session info
5624 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005625 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005626 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005627 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005628
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005629 }
5630
5631 if (stateLocked) mCameraStatesLock.unlock();
5632
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005633 if (locked) mServiceLock.unlock();
5634
Emilian Peevf53f66e2017-04-11 14:29:43 +01005635 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005636
5637 dprintf(fd, "\n== Vendor tags: ==\n\n");
5638
5639 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5640 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005641 sp<VendorTagDescriptorCache> cache =
5642 VendorTagDescriptorCache::getGlobalVendorTagCache();
5643 if (cache == NULL) {
5644 dprintf(fd, "No vendor tags.\n");
5645 } else {
5646 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5647 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005648 } else {
5649 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5650 }
5651
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005652 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005653 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005654 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005655
5656 // Process dump arguments, if any
5657 int n = args.size();
5658 String16 verboseOption("-v");
5659 String16 unreachableOption("--unreachable");
5660 for (int i = 0; i < n; i++) {
5661 if (args[i] == verboseOption) {
5662 // change logging level
5663 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005664 std::string levelStr = toStdString(args[i+1]);
5665 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005666 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005667 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005668 } else if (args[i] == unreachableOption) {
5669 // Dump memory analysis
5670 // TODO - should limit be an argument parameter?
5671 UnreachableMemoryInfo info;
5672 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5673 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005674 dprintf(fd, "\n== Unable to dump unreachable memory. "
5675 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005676 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005677 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005678 std::string s = info.ToString(/*log_contents*/ true);
5679 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005680 }
5681 }
5682 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005683
5684 bool serviceLocked = tryLock(mServiceLock);
5685
5686 // Dump info from previous open sessions.
5687 // Reposition the offset to beginning of the file before reading
5688
5689 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5690 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5691 ssize_t size_read;
5692 char buf[4096];
5693 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5694 // Read data from file to a small buffer and write it to fd.
5695 write(fd, buf, size_read);
5696 if (size_read == -1) {
5697 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5698 break;
5699 }
5700 }
5701 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5702 } else {
5703 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5704 }
5705
5706 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005707 return NO_ERROR;
5708}
5709
Rucha Katakwardf223072021-06-15 10:21:00 -07005710void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005711 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005712 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005713 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005714 getFormattedCurrentTime().c_str(),
5715 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005716 dprintf(fd, " Client priority score: %d state: %d\n",
5717 clientDescriptor->getPriority().getScore(),
5718 clientDescriptor->getPriority().getState());
5719 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5720
5721 auto client = clientDescriptor->getValue();
5722 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005723 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005724
5725 client->dumpClient(fd, args);
5726}
5727
Austin Borgered99f642023-06-01 16:51:35 -07005728void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005729 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005730 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005731}
5732
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005733void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005734 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005735
5736 Mutex::Autolock l(mLogLock);
5737 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005738 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005739 }
5740
5741 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005742 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005743 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005744 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005745 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005746 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005747}
5748
Austin Borgered99f642023-06-01 16:51:35 -07005749void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005750 Mutex::Autolock lock(mLogLock);
5751 if (!isClientWatchedLocked(client)) { return; }
5752
5753 std::vector<std::string> dumpVector;
5754 client->dumpWatchedEventsToVector(dumpVector);
5755
5756 if (dumpVector.empty()) { return; }
5757
Austin Borgered99f642023-06-01 16:51:35 -07005758 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005759
Austin Borgered99f642023-06-01 16:51:35 -07005760 std::string currentTime = getFormattedCurrentTime();
5761 dumpString << "Cached @ ";
5762 dumpString << currentTime;
5763 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005764
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005765 size_t i = dumpVector.size();
5766
5767 // Store the string in reverse order (latest last)
5768 while (i > 0) {
5769 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005770 dumpString << cameraId;
5771 dumpString << ":";
5772 dumpString << client->getPackageName();
5773 dumpString << " ";
5774 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005775 }
5776
Austin Borgered99f642023-06-01 16:51:35 -07005777 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005778}
5779
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005780void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005781 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005782 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5783 if (mTorchClientMap[i] == who) {
5784 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005785 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005786 status_t res = mFlashlight->setTorchMode(cameraId, false);
5787 if (res) {
5788 ALOGE("%s: torch client died but couldn't turn off torch: "
5789 "%s (%d)", __FUNCTION__, strerror(-res), res);
5790 return;
5791 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005792 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005793 break;
5794 }
5795 }
5796}
5797
Ruben Brunkcc776712015-02-17 20:18:47 -08005798/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005799
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005800 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005801 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5802 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005803 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005804 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005805 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005806
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005807 // check torch client
5808 handleTorchClientBinderDied(who);
5809
5810 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005811 if(!evictClientIdByRemote(who)) {
5812 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005813 return;
5814 }
5815
Ruben Brunkcc776712015-02-17 20:18:47 -08005816 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5817 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005818}
5819
Austin Borgered99f642023-06-01 16:51:35 -07005820void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005821 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005822}
5823
Austin Borgered99f642023-06-01 16:51:35 -07005824void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005825 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005826 // Do not lock mServiceLock here or can get into a deadlock from
5827 // connect() -> disconnect -> updateStatus
5828
5829 auto state = getCameraState(cameraId);
5830
5831 if (state == nullptr) {
5832 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005833 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005834 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005835 }
5836
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005837 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5838 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5839 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005840 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005841 return;
5842 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005843
Biswarup Pal37a75182024-01-16 15:53:35 +00005844 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5845 CameraMetadata cameraInfo;
5846 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00005847 cameraId, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +00005848 if (res != OK) {
5849 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5850 __FUNCTION__, cameraId.c_str());
5851 } else {
5852 int32_t deviceId = getDeviceId(cameraInfo);
5853 if (deviceId != kDefaultDeviceId) {
5854 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5855 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5856 static_cast<camera_metadata_enum_android_lens_facing_t>(
5857 lensFacingEntry.data.u8[0]);
5858 std::string mappedCameraId;
5859 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5860 mappedCameraId = kVirtualDeviceBackCameraId;
5861 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5862 mappedCameraId = kVirtualDeviceFrontCameraId;
5863 } else {
5864 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5865 __func__);
5866 }
5867 if (!mappedCameraId.empty()) {
5868 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5869 }
5870 }
5871 }
5872 }
5873
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005874 // Collect the logical cameras without holding mStatusLock in updateStatus
5875 // as that can lead to a deadlock(b/162192331).
5876 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005877 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005878 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005879 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005880 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005881 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005882 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5883 auto [deviceId, mappedCameraId] =
5884 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005885
Biswarup Pal37a75182024-01-16 15:53:35 +00005886 if (status != StatusInternal::ENUMERATING) {
5887 // Update torch status if it has a flash unit.
5888 Mutex::Autolock al(mTorchStatusMutex);
5889 TorchModeStatus torchStatus;
5890 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5891 NAME_NOT_FOUND) {
5892 TorchModeStatus newTorchStatus =
5893 status == StatusInternal::PRESENT ?
5894 TorchModeStatus::AVAILABLE_OFF :
5895 TorchModeStatus::NOT_AVAILABLE;
5896 if (torchStatus != newTorchStatus) {
5897 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5898 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005899 }
5900 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005901
Biswarup Pal37a75182024-01-16 15:53:35 +00005902 Mutex::Autolock lock(mStatusListenerLock);
5903 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5904 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005905
Biswarup Pal37a75182024-01-16 15:53:35 +00005906 for (auto& listener : mListenerList) {
5907 bool isVendorListener = listener->isVendorListener();
5908 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5909 listener->getListenerPid(), listener->getListenerUid())) {
5910 ALOGV("Skipping discovery callback for system-only camera device %s",
5911 cameraId.c_str());
5912 continue;
5913 }
5914
5915 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5916 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005917 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005918 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005919 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5920 ret.exceptionCode());
Biswarup Pal37a75182024-01-16 15:53:35 +00005921
5922 // Only cameras of the default device can be remapped to a different camera
5923 // (using remapCameraIds method), so do the following only if the camera is
5924 // associated with the default device.
5925 if (deviceId == kDefaultDeviceId) {
5926 // For the default device, also trigger the callbacks for cameras that were
5927 // remapped to the current cameraId for the specific package that this
5928 // listener belongs to.
5929 std::vector<std::string> remappedCameraIds =
5930 findOriginalIdsForRemappedCameraId(cameraId,
5931 listener->getListenerUid());
5932 for (auto &remappedCameraId: remappedCameraIds) {
5933 ret = listener->getListener()->onStatusChanged(
5934 mapToInterface(status), remappedCameraId, kDefaultDeviceId);
5935 listener->handleBinderStatus(ret,
5936 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
5937 __FUNCTION__, listener->getListenerUid(),
5938 listener->getListenerPid(), ret.exceptionCode());
5939 }
5940 }
malikakash82ed4352023-07-21 22:44:34 +00005941 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005942 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005943}
5944
Austin Borgered99f642023-06-01 16:51:35 -07005945void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5946 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005947 auto state = getCameraState(cameraId);
5948 if (state == nullptr) {
5949 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005950 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005951 return;
5952 }
5953 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005954 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005955 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005956 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005957 }
5958
Biswarup Pal37a75182024-01-16 15:53:35 +00005959 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5960 auto [deviceId, mappedCameraId] =
5961 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5962
Shuzhen Wang695044d2020-03-06 09:02:23 -08005963 Mutex::Autolock lock(mStatusListenerLock);
5964
5965 for (const auto& it : mListenerList) {
5966 if (!it->isOpenCloseCallbackAllowed()) {
5967 continue;
5968 }
5969
5970 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005971 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005972 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5973 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005974 } else {
Biswarup Pal37a75182024-01-16 15:53:35 +00005975 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005976 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005977
5978 it->handleBinderStatus(ret,
5979 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5980 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005981 }
5982}
5983
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005984template<class Func>
5985void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005986 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005987 std::initializer_list<StatusInternal> rejectSourceStates,
5988 Func onStatusUpdatedLocked) {
5989 Mutex::Autolock lock(mStatusLock);
5990 StatusInternal oldStatus = mStatus;
5991 mStatus = status;
5992
5993 if (oldStatus == status) {
5994 return;
5995 }
5996
5997 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005998 cameraId.c_str(), oldStatus, status);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005999
6000 if (oldStatus == StatusInternal::NOT_PRESENT &&
6001 (status != StatusInternal::PRESENT &&
6002 status != StatusInternal::ENUMERATING)) {
6003
6004 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
6005 __FUNCTION__);
6006 mStatus = oldStatus;
6007 return;
6008 }
6009
6010 /**
6011 * Sometimes we want to conditionally do a transition.
6012 * For example if a client disconnects, we want to go to PRESENT
6013 * only if we weren't already in NOT_PRESENT or ENUMERATING.
6014 */
6015 for (auto& rejectStatus : rejectSourceStates) {
6016 if (oldStatus == rejectStatus) {
6017 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07006018 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006019 mStatus = oldStatus;
6020 return;
6021 }
6022 }
6023
6024 onStatusUpdatedLocked(cameraId, status);
6025}
6026
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006027status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07006028 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006029 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006030 if (!status) {
6031 return BAD_VALUE;
6032 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006033 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
6034 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006035 // invalid camera ID or the camera doesn't have a flash unit
6036 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006037 }
6038
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006039 *status = mTorchStatusMap.valueAt(index);
6040 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006041}
6042
Austin Borgered99f642023-06-01 16:51:35 -07006043status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006044 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006045 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
6046 if (index == NAME_NOT_FOUND) {
6047 return BAD_VALUE;
6048 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006049 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006050
6051 return OK;
6052}
6053
Austin Borgered99f642023-06-01 16:51:35 -07006054std::list<std::string> CameraService::getLogicalCameras(
6055 const std::string& physicalCameraId) {
6056 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08006057 Mutex::Autolock lock(mCameraStatesLock);
6058 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07006059 if (state.second->containsPhysicalCamera(physicalCameraId)) {
6060 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08006061 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006062 }
6063 return retList;
6064}
6065
6066void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07006067 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00006068 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006069 // mStatusListenerLock is expected to be locked
6070 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08006071 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006072 // Note: we check only the deviceKind of the physical camera id
6073 // since, logical camera ids and their physical camera ids are
6074 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07006075 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
6076 listener->getListenerPid(), listener->getListenerUid())) {
6077 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07006078 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07006079 continue;
6080 }
Austin Borgere8e2c422022-05-12 13:45:24 -07006081 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00006082 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07006083 listener->handleBinderStatus(ret,
6084 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
6085 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
6086 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08006087 }
6088 }
6089}
6090
Svet Ganova453d0d2018-01-11 15:37:58 -08006091void CameraService::blockClientsForUid(uid_t uid) {
6092 const auto clients = mActiveClientManager.getAll();
6093 for (auto& current : clients) {
6094 if (current != nullptr) {
6095 const auto basicClient = current->getValue();
6096 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
6097 basicClient->block();
6098 }
6099 }
6100 }
6101}
6102
Michael Grooverd1d435a2018-12-18 17:39:42 -08006103void CameraService::blockAllClients() {
6104 const auto clients = mActiveClientManager.getAll();
6105 for (auto& current : clients) {
6106 if (current != nullptr) {
6107 const auto basicClient = current->getValue();
6108 if (basicClient.get() != nullptr) {
6109 basicClient->block();
6110 }
6111 }
6112 }
6113}
6114
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00006115void CameraService::blockPrivacyEnabledClients() {
6116 const auto clients = mActiveClientManager.getAll();
6117 for (auto& current : clients) {
6118 if (current != nullptr) {
6119 const auto basicClient = current->getValue();
6120 if (basicClient.get() != nullptr) {
6121 std::string pkgName = basicClient->getPackageName();
6122 bool cameraPrivacyEnabled =
6123 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
6124 if (cameraPrivacyEnabled) {
6125 basicClient->block();
6126 }
6127 }
6128 }
6129 }
6130}
6131
Svet Ganova453d0d2018-01-11 15:37:58 -08006132// NOTE: This is a remote API - make sure all args are validated
6133status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006134 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006135 return PERMISSION_DENIED;
6136 }
6137 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
6138 return BAD_VALUE;
6139 }
Austin Borgered99f642023-06-01 16:51:35 -07006140 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006141 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006142 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006143 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006144 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006145 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07006146 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006147 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07006148 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006149 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07006150 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006151 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07006152 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006153 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07006154 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006155 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07006156 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006157 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07006158 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006159 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07006160 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006161 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07006162 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006163 handleClearStreamUseCaseOverrides();
6164 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07006165 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006166 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07006167 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006168 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07006169 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00006170 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07006171 } else if (args.size() >= 4 && args[0] == toString16("remap-camera-id")) {
malikakash82ed4352023-07-21 22:44:34 +00006172 return handleCameraIdRemapping(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006173 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006174 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006175 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08006176 }
6177 printHelp(err);
6178 return BAD_VALUE;
6179}
6180
malikakash82ed4352023-07-21 22:44:34 +00006181status_t CameraService::handleCameraIdRemapping(const Vector<String16>& args, int err) {
6182 uid_t uid = IPCThreadState::self()->getCallingUid();
6183 if (uid != AID_ROOT) {
6184 dprintf(err, "Must be adb root\n");
6185 return PERMISSION_DENIED;
6186 }
6187 if (args.size() != 4) {
6188 dprintf(err, "Expected format: remap-camera-id <PACKAGE> <Id0> <Id1>\n");
6189 return BAD_VALUE;
6190 }
Austin Borgered99f642023-06-01 16:51:35 -07006191 std::string packageName = toStdString(args[1]);
6192 std::string cameraIdToReplace = toStdString(args[2]);
6193 std::string cameraIdNew = toStdString(args[3]);
malikakash82ed4352023-07-21 22:44:34 +00006194 remapCameraIds({{packageName, {{cameraIdToReplace, cameraIdNew}}}});
6195 return OK;
6196}
6197
Svet Ganova453d0d2018-01-11 15:37:58 -08006198status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006199 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006200
Svet Ganova453d0d2018-01-11 15:37:58 -08006201 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07006202 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006203 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07006204 } else if ((args[2] != toString16("idle"))) {
6205 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08006206 return BAD_VALUE;
6207 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006208
6209 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006210 if (args.size() >= 5 && args[3] == toString16("--user")) {
6211 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006212 }
6213
6214 uid_t uid;
6215 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
6216 return BAD_VALUE;
6217 }
6218
6219 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08006220 return NO_ERROR;
6221}
6222
6223status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006224 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006225
6226 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006227 if (args.size() >= 4 && args[2] == toString16("--user")) {
6228 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006229 }
6230
6231 uid_t uid;
6232 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006233 return BAD_VALUE;
6234 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006235
6236 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08006237 return NO_ERROR;
6238}
6239
6240status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006241 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006242
6243 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006244 if (args.size() >= 4 && args[2] == toString16("--user")) {
6245 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006246 }
6247
6248 uid_t uid;
6249 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006250 return BAD_VALUE;
6251 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006252
6253 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006254 return dprintf(out, "active\n");
6255 } else {
6256 return dprintf(out, "idle\n");
6257 }
6258}
6259
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006260status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006261 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006262 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
6263 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
6264 Mutex::Autolock lock(mServiceLock);
6265
6266 mOverrideRotateAndCropMode = rotateValue;
6267
6268 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6269
6270 const auto clients = mActiveClientManager.getAll();
6271 for (auto& current : clients) {
6272 if (current != nullptr) {
6273 const auto basicClient = current->getValue();
6274 if (basicClient.get() != nullptr) {
6275 basicClient->setRotateAndCropOverride(rotateValue);
6276 }
6277 }
6278 }
6279
6280 return OK;
6281}
6282
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006283status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6284 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006285 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006286 if ((*end != '\0') ||
6287 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6288 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6289 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6290 return BAD_VALUE;
6291 }
6292
6293 Mutex::Autolock lock(mServiceLock);
6294 mOverrideAutoframingMode = autoframingValue;
6295
6296 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6297
6298 const auto clients = mActiveClientManager.getAll();
6299 for (auto& current : clients) {
6300 if (current != nullptr) {
6301 const auto basicClient = current->getValue();
6302 if (basicClient.get() != nullptr) {
6303 basicClient->setAutoframingOverride(autoframingValue);
6304 }
6305 }
6306 }
6307
6308 return OK;
6309}
6310
Ravneetaeb20dc2022-03-30 05:33:03 +00006311status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006312 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006313
6314 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6315
6316 Mutex::Autolock lock(mServiceLock);
6317
6318 mCameraServiceWatchdogEnabled = enableWatchdog;
6319
6320 const auto clients = mActiveClientManager.getAll();
6321 for (auto& current : clients) {
6322 if (current != nullptr) {
6323 const auto basicClient = current->getValue();
6324 if (basicClient.get() != nullptr) {
6325 basicClient->setCameraServiceWatchdog(enableWatchdog);
6326 }
6327 }
6328 }
6329
6330 return OK;
6331}
6332
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006333status_t CameraService::handleGetRotateAndCrop(int out) {
6334 Mutex::Autolock lock(mServiceLock);
6335
6336 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6337}
6338
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006339status_t CameraService::handleGetAutoframing(int out) {
6340 Mutex::Autolock lock(mServiceLock);
6341
6342 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6343}
6344
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006345status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6346 char *endPtr;
6347 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006348 std::string maskString = toStdString(args[1]);
6349 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006350
6351 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006352 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006353 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6354
6355 Mutex::Autolock lock(mServiceLock);
6356
6357 mImageDumpMask = maskValue;
6358
6359 return OK;
6360}
6361
6362status_t CameraService::handleGetImageDumpMask(int out) {
6363 Mutex::Autolock lock(mServiceLock);
6364
6365 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6366}
6367
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006368status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006369 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006370 if (errno != 0) return BAD_VALUE;
6371
6372 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6373 Mutex::Autolock lock(mServiceLock);
6374
6375 mOverrideCameraMuteMode = (muteValue == 1);
6376
6377 const auto clients = mActiveClientManager.getAll();
6378 for (auto& current : clients) {
6379 if (current != nullptr) {
6380 const auto basicClient = current->getValue();
6381 if (basicClient.get() != nullptr) {
6382 if (basicClient->supportsCameraMute()) {
6383 basicClient->setCameraMute(mOverrideCameraMuteMode);
6384 }
6385 }
6386 }
6387 }
6388
6389 return OK;
6390}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006391
Shuzhen Wang16610a62022-12-15 22:38:07 -08006392status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6393 std::vector<int64_t> useCasesOverride;
6394 for (size_t i = 1; i < args.size(); i++) {
6395 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006396 std::string arg = toStdString(args[i]);
6397 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006398 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006399 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006400 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006401 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006402 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006403 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006404 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006405 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006406 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006407 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006408 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006409 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006410 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6411 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006412 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006413 return BAD_VALUE;
6414 }
6415 useCasesOverride.push_back(useCase);
6416 }
6417
6418 Mutex::Autolock lock(mServiceLock);
6419 mStreamUseCaseOverrides = std::move(useCasesOverride);
6420
6421 return OK;
6422}
6423
6424void CameraService::handleClearStreamUseCaseOverrides() {
6425 Mutex::Autolock lock(mServiceLock);
6426 mStreamUseCaseOverrides.clear();
6427}
6428
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006429status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6430 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006431 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006432 if ((*end != '\0') ||
6433 (zoomOverrideValue != -1 &&
6434 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6435 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6436 return BAD_VALUE;
6437 }
6438
6439 Mutex::Autolock lock(mServiceLock);
6440 mZoomOverrideValue = zoomOverrideValue;
6441
6442 const auto clients = mActiveClientManager.getAll();
6443 for (auto& current : clients) {
6444 if (current != nullptr) {
6445 const auto basicClient = current->getValue();
6446 if (basicClient.get() != nullptr) {
6447 if (basicClient->supportsZoomOverride()) {
6448 basicClient->setZoomOverride(mZoomOverrideValue);
6449 }
6450 }
6451 }
6452 }
6453
6454 return OK;
6455}
6456
Avichal Rakesh84147132021-11-11 17:47:11 -08006457status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006458 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006459 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006460 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006461 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006462 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006463 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006464 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006465 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006466 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006467 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006468 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006469 dprintf(outFd, "Camera service watch commands:\n"
6470 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6471 " starts watching the provided tags for clients with provided package\n"
6472 " recognizes tag shorthands like '3a'\n"
6473 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006474 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006475 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006476 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006477 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006478 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006479 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006480 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006481}
6482
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006483status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6484 Mutex::Autolock lock(mLogLock);
6485 size_t tagsIdx; // index of '-m'
6486 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006487 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006488 if (tagsIdx < args.size() - 1) {
6489 tags = args[tagsIdx + 1];
6490 } else {
6491 dprintf(outFd, "No tags provided.\n");
6492 return BAD_VALUE;
6493 }
6494
6495 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006496 // watch all clients if no clients are provided
6497 String16 clients = toString16(kWatchAllClientsFlag);
6498 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006499 clientsIdx++);
6500 if (clientsIdx < args.size() - 1) {
6501 clients = args[clientsIdx + 1];
6502 }
Austin Borgered99f642023-06-01 16:51:35 -07006503 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006504
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006505 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006506 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006507
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006508 bool serviceLock = tryLock(mServiceLock);
6509 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006510 auto cameraClients = mActiveClientManager.getAll();
6511 for (const auto &clientDescriptor: cameraClients) {
6512 if (clientDescriptor == nullptr) { continue; }
6513 sp<BasicClient> client = clientDescriptor->getValue();
6514 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006515
6516 if (isClientWatchedLocked(client.get())) {
6517 client->startWatchingTags(mMonitorTags, outFd);
6518 numWatchedClients++;
6519 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006520 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006521 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6522
6523 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006524 return OK;
6525}
6526
6527status_t CameraService::stopWatchingTags(int outFd) {
6528 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006529 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006530 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006531
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006532 mWatchedClientPackages.clear();
6533 mWatchedClientsDumpCache.clear();
6534
6535 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006536 auto cameraClients = mActiveClientManager.getAll();
6537 for (const auto &clientDescriptor : cameraClients) {
6538 if (clientDescriptor == nullptr) { continue; }
6539 sp<BasicClient> client = clientDescriptor->getValue();
6540 if (client.get() == nullptr) { continue; }
6541 client->stopWatchingTags(outFd);
6542 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006543 dprintf(outFd, "Stopped watching all clients.\n");
6544 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006545 return OK;
6546}
6547
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006548status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6549 Mutex::Autolock lock(mLogLock);
6550 size_t clearedSize = mWatchedClientsDumpCache.size();
6551 mWatchedClientsDumpCache.clear();
6552 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6553 return OK;
6554}
6555
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006556status_t CameraService::printWatchedTags(int outFd) {
6557 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006558 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006559
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006560 bool printedSomething = false; // tracks if any monitoring information was printed
6561 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006562
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006563 bool serviceLock = tryLock(mServiceLock);
6564 // get all watched clients that are currently connected
6565 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6566 if (clientDescriptor == nullptr) { continue; }
6567
6568 sp<BasicClient> client = clientDescriptor->getValue();
6569 if (client.get() == nullptr) { continue; }
6570 if (!isClientWatchedLocked(client.get())) { continue; }
6571
6572 std::vector<std::string> dumpVector;
6573 client->dumpWatchedEventsToVector(dumpVector);
6574
6575 size_t printIdx = dumpVector.size();
6576 if (printIdx == 0) {
6577 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006578 }
6579
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006580 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006581 const std::string &cameraId = clientDescriptor->getKey();
6582 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006583 while(printIdx > 0) {
6584 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006585 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006586 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006587 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006588 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006589 printedSomething = true;
6590
6591 connectedMonitoredClients.emplace(client->getPackageName());
6592 }
6593 if (serviceLock) { mServiceLock.unlock(); }
6594
6595 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6596 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006597 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006598 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6599 continue;
6600 }
6601
Austin Borgered99f642023-06-01 16:51:35 -07006602 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006603 dprintf(outFd, "%s\n", kv.second.c_str());
6604 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006605 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006606
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006607 if (!printedSomething) {
6608 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006609 }
6610
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006611 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006612}
6613
Avichal Rakesh84147132021-11-11 17:47:11 -08006614// Print all events in vector `events' that came after lastPrintedEvent
6615void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006616 const std::string &cameraId,
6617 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006618 const std::vector<std::string> &events,
6619 const std::string &lastPrintedEvent) {
6620 if (events.empty()) { return; }
6621
6622 // index of lastPrintedEvent in events.
6623 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6624 size_t lastPrintedIdx;
6625 for (lastPrintedIdx = 0;
6626 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6627 lastPrintedIdx++);
6628
6629 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6630
Avichal Rakesh84147132021-11-11 17:47:11 -08006631 // print events in chronological order (latest event last)
6632 size_t idxToPrint = lastPrintedIdx;
6633 do {
6634 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006635 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6636 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006637 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006638}
6639
6640// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6641// command should be interrupted if the user presses the return key, or if user loses any way to
6642// signal interrupt.
6643// If timeoutMs == 0, this function will always return false
6644bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6645 struct timeval startTime;
6646 int startTimeError = gettimeofday(&startTime, nullptr);
6647 if (startTimeError) {
6648 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6649 return true;
6650 }
6651
6652 const nfds_t numFds = 1;
6653 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6654
6655 struct timeval currTime;
6656 char buffer[2];
6657 while(true) {
6658 int currTimeError = gettimeofday(&currTime, nullptr);
6659 if (currTimeError) {
6660 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6661 return true;
6662 }
6663
6664 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6665 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6666 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6667
6668 if (remainingTimeMs <= 0) {
6669 // No user interrupt within timeoutMs, don't interrupt watch command
6670 return false;
6671 }
6672
6673 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6674 if (numFdsUpdated < 0) {
6675 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6676 return true;
6677 }
6678
6679 if (numFdsUpdated == 0) {
6680 // No user input within timeoutMs, don't interrupt watch command
6681 return false;
6682 }
6683
6684 if (!(pollFd.revents & POLLIN)) {
6685 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6686 return true;
6687 }
6688
6689 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6690 if (sizeRead < 0) {
6691 dprintf(outFd, "Error reading user input. Exiting.\n");
6692 return true;
6693 }
6694
6695 if (sizeRead == 0) {
6696 // Reached end of input fd (can happen if input is piped)
6697 // User has no way to signal an interrupt, so interrupt here
6698 return true;
6699 }
6700
6701 if (buffer[0] == '\n') {
6702 // User pressed return, interrupt watch command.
6703 return true;
6704 }
6705 }
6706}
6707
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006708status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6709 int inFd, int outFd) {
6710 // Figure out refresh interval, if present in args
6711 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006712 if (args.size() > 2) {
6713 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006714 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006715 intervalIdx++);
6716
6717 size_t intervalValIdx = intervalIdx + 1;
6718 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006719 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006720 if (errno) { return BAD_VALUE; }
6721 }
6722 }
6723
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006724 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6725 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006726
Avichal Rakesh84147132021-11-11 17:47:11 -08006727 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006728 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006729
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006730 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006731 bool serviceLock = tryLock(mServiceLock);
6732 auto cameraClients = mActiveClientManager.getAll();
6733 if (serviceLock) { mServiceLock.unlock(); }
6734
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006735 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006736 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006737 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006738
6739 sp<BasicClient> client = clientDescriptor->getValue();
6740 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006741 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006742
Austin Borgered99f642023-06-01 16:51:35 -07006743 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006744 // This also initializes the map entries with an empty string
6745 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6746
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006747 std::vector<std::string> latestEvents;
6748 client->dumpWatchedEventsToVector(latestEvents);
6749
6750 if (!latestEvents.empty()) {
6751 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006752 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006753 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006754 latestEvents,
6755 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006756 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006757 }
6758 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006759 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006760 break;
6761 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006762 }
6763 return OK;
6764}
6765
Austin Borgered99f642023-06-01 16:51:35 -07006766void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006767 mWatchedClientPackages.clear();
6768
Austin Borgered99f642023-06-01 16:51:35 -07006769 std::istringstream iss(clients);
6770 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006771
Austin Borgered99f642023-06-01 16:51:35 -07006772 while (std::getline(iss, nextClient, ',')) {
6773 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006774 // Don't need to track any other package if 'all' is present
6775 mWatchedClientPackages.clear();
6776 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6777 break;
6778 }
6779
6780 // track package names
6781 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006782 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006783}
6784
Svet Ganova453d0d2018-01-11 15:37:58 -08006785status_t CameraService::printHelp(int out) {
6786 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006787 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6788 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6789 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006790 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6791 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6792 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006793 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6794 " Valid values 0=false, 1=true, 2=auto\n"
6795 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006796 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6797 " Valid values 0=OFF, 1=ON for JPEG\n"
6798 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006799 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006800 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6801 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6802 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6803 " on. In case the number of usecases is smaller than the number of streams, the\n"
6804 " last use case is assigned to all the remaining streams. In case of multiple\n"
6805 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6806 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6807 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6808 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006809 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6810 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006811 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6812 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006813 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
malikakash73125c62023-07-21 22:44:34 +00006814 " remap-camera-id <PACKAGE> <Id0> <Id1> remaps camera ids. Must use adb root\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006815 " help print this message\n");
6816}
6817
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006818bool CameraService::isClientWatched(const BasicClient *client) {
6819 Mutex::Autolock lock(mLogLock);
6820 return isClientWatchedLocked(client);
6821}
6822
6823bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6824 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6825 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6826}
6827
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006828int32_t CameraService::updateAudioRestriction() {
6829 Mutex::Autolock lock(mServiceLock);
6830 return updateAudioRestrictionLocked();
6831}
6832
6833int32_t CameraService::updateAudioRestrictionLocked() {
6834 int32_t mode = 0;
6835 // iterate through all active client
6836 for (const auto& i : mActiveClientManager.getAll()) {
6837 const auto clientSp = i->getValue();
6838 mode |= clientSp->getAudioRestriction();
6839 }
6840
6841 bool modeChanged = (mAudioRestriction != mode);
6842 mAudioRestriction = mode;
6843 if (modeChanged) {
6844 mAppOps.setCameraAudioRestriction(mode);
6845 }
6846 return mode;
6847}
6848
Austin Borgered99f642023-06-01 16:51:35 -07006849status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006850 sp<BasicClient> clientSp) {
6851 std::unique_ptr<AutoConditionLock> lock =
6852 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6853 status_t res = NO_ERROR;
6854 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006855 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006856 mInjectionStatusListener->notifyInjectionError(
6857 externalCamId, UNKNOWN_TRANSACTION);
6858 clientSp->notifyError(
6859 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6860 CaptureResultExtras());
6861
6862 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6863 // other clients from connecting in mServiceLockWrapper if held
6864 mServiceLock.unlock();
6865
6866 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006867 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006868 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006869 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006870
6871 // Reacquire mServiceLock
6872 mServiceLock.lock();
6873 }
6874
6875 return res;
6876}
6877
Cliff Wud3a05312021-04-26 23:07:31 +08006878void CameraService::clearInjectionParameters() {
6879 {
6880 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006881 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006882 mInjectionInternalCamId = "";
6883 }
6884 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006885 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006886}
6887
Biswarup Pal37a75182024-01-16 15:53:35 +00006888} // namespace android