blob: e7954952cd1306acd9d04efd0b32dfa02574eca3 [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 {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080092 const char* kActivityServiceName = "activity";
93 const char* kSensorPrivacyServiceName = "sensor_privacy";
94 const char* kAppopsServiceName = "appops";
Jyoti Bhayanada519ab2023-05-15 15:49:15 -070095 const char* kProcessInfoServiceName = "processinfo";
Biswarup Pal37a75182024-01-16 15:53:35 +000096 const char* kVirtualDeviceBackCameraId = "0";
97 const char* kVirtualDeviceFrontCameraId = "1";
98
99 int32_t getDeviceId(const android::CameraMetadata& cameraInfo) {
100 if (!cameraInfo.exists(ANDROID_INFO_DEVICE_ID)) {
101 return android::kDefaultDeviceId;
102 }
103
104 const auto &deviceIdEntry = cameraInfo.find(ANDROID_INFO_DEVICE_ID);
105 return deviceIdEntry.data.i32[0];
106 }
107} // namespace anonymous
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -0800108
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109namespace android {
110
Austin Borgerea931242021-12-13 23:10:41 +0000111using namespace camera3;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700112using namespace camera3::SessionConfigurationUtils;
113
114using binder::Status;
Biswarup Pal37a75182024-01-16 15:53:35 +0000115using companion::virtualnative::IVirtualDeviceManagerNative;
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700116using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700117using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800118using hardware::ICamera;
119using hardware::ICameraClient;
120using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800121using hardware::camera2::ICameraInjectionCallback;
122using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800123using hardware::camera2::utils::CameraIdAndSessionConfiguration;
124using hardware::camera2::utils::ConcurrentCameraIdCombination;
Biswarup Pal37a75182024-01-16 15:53:35 +0000125
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -0700126namespace flags = com::android::internal::camera::flags;
Biswarup Pal37a75182024-01-16 15:53:35 +0000127namespace vd_flags = android::companion::virtualdevice::flags;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800128
Mathias Agopian65ab4712010-07-14 17:59:35 -0700129// ----------------------------------------------------------------------------
130// Logging support -- this is for debugging only
131// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700132volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700133
Steve Blockb8a80522011-12-20 16:23:08 +0000134#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
135#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700136
137static void setLogLevel(int level) {
138 android_atomic_write(level, &gLogLevel);
139}
140
Henri Chataingbcb99452023-11-01 17:40:30 +0000141int32_t format_as(CameraService::StatusInternal s) {
142 return fmt::underlying(s);
143}
144
Mathias Agopian65ab4712010-07-14 17:59:35 -0700145// ----------------------------------------------------------------------------
146
Austin Borger249e6592024-03-10 22:28:11 -0700147// Permission strings (references to AttributionAndPermissionUtils for brevity)
148static const std::string &sDumpPermission =
149 AttributionAndPermissionUtils::sDumpPermission;
150static const std::string &sManageCameraPermission =
151 AttributionAndPermissionUtils::sManageCameraPermission;
152static const std::string &sCameraSendSystemEventsPermission =
153 AttributionAndPermissionUtils::sCameraSendSystemEventsPermission;
154static const std::string &sCameraInjectExternalCameraPermission =
155 AttributionAndPermissionUtils::sCameraInjectExternalCameraPermission;
156
Kunal Malhotrabfc96052023-02-28 23:25:34 +0000157// Constant integer for FGS Logging, used to denote the API type for logger
158static const int LOG_FGS_CAMERA_API = 1;
Rucha Katakwardf223072021-06-15 10:21:00 -0700159const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800160static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
161static constexpr int32_t kSystemNativeClientState =
162 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Austin Borgered99f642023-06-01 16:51:35 -0700163static const std::string kServiceName("cameraserver");
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700164
Austin Borgered99f642023-06-01 16:51:35 -0700165const std::string CameraService::kOfflineDevice("offline-");
166const std::string CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700167
Biswarup Pal7d072862024-04-17 15:24:47 +0000168constexpr int32_t kInvalidDeviceId = -1;
169
Rucha Katakward9ea6452021-05-06 11:57:16 -0700170// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700171static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700172
Austin Borger74fca042022-05-23 12:41:21 -0700173CameraService::CameraService(
Austin Borger249e6592024-03-10 22:28:11 -0700174 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,
175 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils) :
176 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils == nullptr ?
177 std::make_shared<AttributionAndPermissionUtils>()\
178 : attributionAndPermissionUtils),
Austin Borger74fca042022-05-23 12:41:21 -0700179 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
180 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800181 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800182 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700183 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700184 mSoundRef(0), mInitialized(false),
185 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000186 ALOGI("CameraService started (pid=%d)", getpid());
Austin Borger249e6592024-03-10 22:28:11 -0700187 mAttributionAndPermissionUtils->setCameraService(this);
Ruben Brunkcc776712015-02-17 20:18:47 -0800188 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700189 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
190 if (mMemFd == -1) {
191 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
192 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700193}
194
Charles Chena7b613c2023-01-24 21:57:33 +0000195// Enable processes with isolated AID to request the binder
196void CameraService::instantiate() {
197 CameraService::publish(true);
198}
199
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800200void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700201 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800202 return;
203 }
204
205 ALOGV("appops service registered. setting camera audio restriction");
206 mAppOps.setCameraAudioRestriction(mAudioRestriction);
207}
208
Iliyan Malchev8951a972011-04-14 16:55:59 -0700209void CameraService::onFirstRef()
210{
Ruben Brunkcc776712015-02-17 20:18:47 -0800211 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800212
Iliyan Malchev8951a972011-04-14 16:55:59 -0700213 BnCameraService::onFirstRef();
214
Ruben Brunk99e69712015-05-26 17:25:07 -0700215 // Update battery life tracking if service is restarting
216 BatteryNotifier& notifier(BatteryNotifier::getInstance());
217 notifier.noteResetCamera();
218 notifier.noteResetFlashlight();
219
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800220 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800221
Emilian Peevf53f66e2017-04-11 14:29:43 +0100222 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800223 if (res == OK) {
224 mInitialized = true;
225 }
226
Svet Ganova453d0d2018-01-11 15:37:58 -0800227 mUidPolicy = new UidPolicy(this);
228 mUidPolicy->registerSelf();
Austin Borger249e6592024-03-10 22:28:11 -0700229 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this, mAttributionAndPermissionUtils);
Michael Grooverd1d435a2018-12-18 17:39:42 -0800230 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800231 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800232
233 // appops function setCamerAudioRestriction uses getService which
234 // is blocking till the appops service is ready. To enable early
235 // boot availability for cameraservice, use checkService which is
236 // non blocking and register for notifications
237 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700238 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800239 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700240 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800241 } else {
242 mAppOps.setCameraAudioRestriction(mAudioRestriction);
243 }
244
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700245 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
246 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000247 // Deprecated, so it will fail to register on newer devices
248 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700249 __FUNCTION__);
250 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700251
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700252 if (!AidlCameraService::registerService(this)) {
253 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
254 }
255
Shuzhen Wang24b44152019-09-20 10:38:11 -0700256 // This needs to be last call in this function, so that it's as close to
257 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700258 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700259 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800260}
261
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800262status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800263 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100264
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800265 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000266 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800267 {
268 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800269
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800270 if (nullptr == mCameraProviderManager.get()) {
271 mCameraProviderManager = new CameraProviderManager();
272 res = mCameraProviderManager->initialize(this);
273 if (res != OK) {
274 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
275 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700276 logServiceError("Unable to initialize camera provider manager",
277 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800278 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100279 }
280 }
281
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800282 // Setup vendor tags before we call get_camera_info the first time
283 // because HAL might need to setup static vendor keys in get_camera_info
284 // TODO: maybe put this into CameraProviderManager::initialize()?
285 mCameraProviderManager->setUpVendorTags();
286
287 if (nullptr == mFlashlight.get()) {
288 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700289 }
290
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800291 res = mFlashlight->findFlashUnits();
292 if (res != OK) {
293 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
294 }
295
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000296 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800297 }
298
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800299 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700300 if (getCameraState(cameraId) == nullptr) {
301 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800302 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000303 if (unavailPhysicalIds.count(cameraId) > 0) {
304 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700305 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000306 }
307 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800308 }
309
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700310 // Derive primary rear/front cameras, and filter their charactierstics.
311 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700312 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700313 // Assume internal cameras are advertised from the same
314 // provider. If multiple providers are registered at different time,
315 // and each provider contains multiple internal color cameras, the current
316 // logic may filter the characteristics of more than one front/rear color
317 // cameras.
318 Mutex::Autolock l(mServiceLock);
319 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700320 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700321
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800322 return OK;
323}
324
Austin Borgered99f642023-06-01 16:51:35 -0700325void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700326 SystemCameraKind systemCameraKind) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000327 // Get the device id and app-visible camera id for the given HAL-visible camera id.
328 auto [deviceId, mappedCameraId] =
329 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
330
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800331 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800332 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700333 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
334 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000335 ALOGV("%s: Skipping torch callback for system-only camera device %s",
336 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700337 continue;
338 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000339
Austin Borgere8e2c422022-05-12 13:45:24 -0700340 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Biswarup Pal37a75182024-01-16 15:53:35 +0000341 mappedCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700342 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
343 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800344 }
345}
346
Mathias Agopian65ab4712010-07-14 17:59:35 -0700347CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800348 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800349 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800350 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800351 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700352}
353
Emilian Peevaee727d2017-05-04 16:35:48 +0100354void CameraService::onNewProviderRegistered() {
355 enumerateProviders();
356}
357
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700358void CameraService::filterAPI1SystemCameraLocked(
359 const std::vector<std::string> &normalDeviceIds) {
360 mNormalDeviceIdsWithoutSystemCamera.clear();
Biswarup Pal37a75182024-01-16 15:53:35 +0000361 for (auto &cameraId : normalDeviceIds) {
362 if (vd_flags::camera_device_awareness()) {
363 CameraMetadata cameraInfo;
364 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000365 cameraId, false, &cameraInfo,
366 hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +0000367 int32_t deviceId = kDefaultDeviceId;
368 if (res != OK) {
369 ALOGW("%s: Not able to get camera characteristics for camera id %s",
370 __FUNCTION__, cameraId.c_str());
371 } else {
372 deviceId = getDeviceId(cameraInfo);
373 }
374 // Cameras associated with non-default device id's (i.e., virtual cameras) can never be
375 // system cameras, so skip for non-default device id's.
376 if (deviceId != kDefaultDeviceId) {
377 continue;
378 }
379 }
380
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700381 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Biswarup Pal37a75182024-01-16 15:53:35 +0000382 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
383 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700384 continue;
385 }
386 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700387 // All system camera ids will necessarily come after public camera
388 // device ids as per the HAL interface contract.
389 break;
390 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000391 mNormalDeviceIdsWithoutSystemCamera.push_back(cameraId);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700392 }
393 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
394 mNormalDeviceIdsWithoutSystemCamera.size());
395}
396
Austin Borgered99f642023-06-01 16:51:35 -0700397status_t CameraService::getSystemCameraKind(const std::string& cameraId,
398 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700399 auto state = getCameraState(cameraId);
400 if (state != nullptr) {
401 *kind = state->getSystemCameraKind();
402 return OK;
403 }
404 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700405 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700406}
407
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800408void CameraService::updateCameraNumAndIds() {
409 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700410 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
411 // Excludes hidden secure cameras
412 mNumberOfCameras =
413 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
414 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800415 mNormalDeviceIds =
416 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700417 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800418}
419
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700420void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700421 // To claim to be S Performance primary cameras, the cameras must be
422 // backward compatible. So performance class primary camera Ids must be API1
423 // compatible.
424 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
425 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
426 int facing = -1;
427 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800428 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000429 getDeviceVersion(cameraId,
430 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
431 /*out*/&portraitRotation, /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700432 if (facing == -1) {
433 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
434 return;
435 }
436
437 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
438 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700439 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
440 if (res == OK) {
441 mPerfClassPrimaryCameraIds.insert(cameraId);
442 } else {
443 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
444 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
445 break;
446 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700447
448 if (facing == hardware::CAMERA_FACING_BACK) {
449 firstRearCameraSeen = true;
450 }
451 if (facing == hardware::CAMERA_FACING_FRONT) {
452 firstFrontCameraSeen = true;
453 }
454 }
455
456 if (firstRearCameraSeen && firstFrontCameraSeen) {
457 break;
458 }
459 }
460}
461
Austin Borgered99f642023-06-01 16:51:35 -0700462void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700463 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100464 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
465 if (res != OK) {
466 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
467 return;
468 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000469 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700470 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
471 if (res != OK) {
472 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
473 return;
474 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000475 std::vector<std::string> physicalCameraIds;
476 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700477 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100478 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700479 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100480 }
481
482 {
483 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700484 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000485 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100486 }
487
Austin Borgered99f642023-06-01 16:51:35 -0700488 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100489 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700490 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800491
Austin Borgered99f642023-06-01 16:51:35 -0700492 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100493 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800494
495 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700496 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100497}
498
Austin Borgered99f642023-06-01 16:51:35 -0700499void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800500 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700501 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100502 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700503 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100504 }
505
506 {
507 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700508 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100509 }
510}
511
Austin Borgered99f642023-06-01 16:51:35 -0700512void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800513 CameraDeviceStatus newHalStatus) {
514 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700515 cameraId.c_str(), eToI(newHalStatus));
Igor Murashkincba2c162013-03-20 15:56:31 -0700516
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800517 StatusInternal newStatus = mapToInternal(newHalStatus);
518
Austin Borgered99f642023-06-01 16:51:35 -0700519 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800520
521 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700522 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100523 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700524 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100525
526 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700527 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100528
Austin Borgered99f642023-06-01 16:51:35 -0700529 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700530 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700531 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700532 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700533 return;
534 }
535
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800536 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800537
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800538 if (oldStatus == newStatus) {
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700539 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__,
540 eToI(newStatus));
Igor Murashkincba2c162013-03-20 15:56:31 -0700541 return;
542 }
543
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800544 if (newStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000545 logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
546 oldStatus, newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800547 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
548 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700549 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000550 mVirtualDeviceCameraIdMapper.removeCamera(cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800551
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800552 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700553 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800554 // Don't do this in updateStatus to avoid deadlock over mServiceLock
555 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700556
Ruben Brunkcc776712015-02-17 20:18:47 -0800557 // Remove cached shim parameters
558 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700559
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800560 // Remove online as well as offline client from the list of active clients,
561 // if they are present
Austin Borgered99f642023-06-01 16:51:35 -0700562 clientToDisconnectOnline = removeClientLocked(cameraId);
563 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700564 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800565
Austin Borgered99f642023-06-01 16:51:35 -0700566 disconnectClient(cameraId, clientToDisconnectOnline);
567 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700568
Austin Borgered99f642023-06-01 16:51:35 -0700569 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800570 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800571 if (oldStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000572 logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
573 oldStatus, newStatus));
Ruben Brunka8ca9152015-04-07 14:23:40 -0700574 }
Austin Borgered99f642023-06-01 16:51:35 -0700575 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700576 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800577}
Igor Murashkincba2c162013-03-20 15:56:31 -0700578
Austin Borgered99f642023-06-01 16:51:35 -0700579void CameraService::onDeviceStatusChanged(const std::string& id,
580 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800581 CameraDeviceStatus newHalStatus) {
582 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700583 __FUNCTION__, id.c_str(), physicalId.c_str(), eToI(newHalStatus));
Shuzhen Wang43858162020-01-10 13:42:15 -0800584
585 StatusInternal newStatus = mapToInternal(newHalStatus);
586
587 std::shared_ptr<CameraState> state = getCameraState(id);
588
589 if (state == nullptr) {
590 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700591 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800592 return;
593 }
594
595 StatusInternal logicalCameraStatus = state->getStatus();
596 if (logicalCameraStatus != StatusInternal::PRESENT &&
597 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
598 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700599 __FUNCTION__, physicalId.c_str(), eToI(newHalStatus), eToI(logicalCameraStatus));
Shuzhen Wang43858162020-01-10 13:42:15 -0800600 return;
601 }
602
603 bool updated = false;
604 if (newStatus == StatusInternal::PRESENT) {
605 updated = state->removeUnavailablePhysicalId(physicalId);
606 } else {
607 updated = state->addUnavailablePhysicalId(physicalId);
608 }
609
610 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700611 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800612 if (newStatus == StatusInternal::PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000613 logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800614 } else {
Henri Chataingbcb99452023-11-01 17:40:30 +0000615 logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800616 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700617 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
618 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
619 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700620 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700621 return;
622 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800623 Mutex::Autolock lock(mStatusListenerLock);
624 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700625 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
626 listener->getListenerPid(), listener->getListenerUid())) {
627 ALOGV("Skipping discovery callback for system-only camera device %s",
628 id.c_str());
629 continue;
630 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700631 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Biswarup Pal37a75182024-01-16 15:53:35 +0000632 mapToInterface(newStatus), id, physicalId, kDefaultDeviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700633 listener->handleBinderStatus(ret,
634 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
635 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
636 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800637 }
638 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700639}
640
Austin Borgered99f642023-06-01 16:51:35 -0700641void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800642 if (clientToDisconnect.get() != nullptr) {
643 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700644 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800645 // Notify the client of disconnection
646 clientToDisconnect->notifyError(
647 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
648 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800649 clientToDisconnect->disconnect();
650 }
651}
652
Austin Borgered99f642023-06-01 16:51:35 -0700653void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800654 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700655 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
656 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
657 if (res != OK) {
658 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700659 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700660 return;
661 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800662 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700663 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800664}
665
Austin Borgered99f642023-06-01 16:51:35 -0700666void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700667 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
668 Mutex::Autolock al(mTorchStatusMutex);
669 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
670}
671
Austin Borgered99f642023-06-01 16:51:35 -0700672void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800673 int32_t newStrengthLevel) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000674 // Get the device id and app-visible camera id for the given HAL-visible camera id.
675 auto [deviceId, mappedCameraId] =
676 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
677
Rucha Katakwar38284522021-11-10 11:25:21 -0800678 Mutex::Autolock lock(mStatusListenerLock);
679 for (auto& i : mListenerList) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000680 auto ret = i->getListener()->onTorchStrengthLevelChanged(mappedCameraId,
681 newStrengthLevel, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700682 i->handleBinderStatus(ret,
683 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
684 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800685 }
686}
687
Austin Borgered99f642023-06-01 16:51:35 -0700688void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700689 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800690 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700691 __FUNCTION__, cameraId.c_str(), eToI(newStatus));
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800692
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800693 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800694 status_t res = getTorchStatusLocked(cameraId, &status);
695 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700696 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700697 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800698 return;
699 }
700 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800701 return;
702 }
703
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800704 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800705 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800706 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
707 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800708 return;
709 }
710
Ruben Brunkcc776712015-02-17 20:18:47 -0800711 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700712 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700713 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700714 auto iter = mTorchUidMap.find(cameraId);
715 if (iter != mTorchUidMap.end()) {
716 int oldUid = iter->second.second;
717 int newUid = iter->second.first;
718 BatteryNotifier& notifier(BatteryNotifier::getInstance());
719 if (oldUid != newUid) {
720 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800721 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700722 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700723 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800724 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700725 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700726 }
727 iter->second.second = newUid;
728 } else {
729 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800730 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700731 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700732 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700733 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700734 }
735 }
736 }
737 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700738 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800739}
740
Austin Borger249e6592024-03-10 22:28:11 -0700741bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700742 // Returns false if this is not an automotive device type.
743 if (!isAutomotiveDevice())
744 return false;
745
746 // Returns false if no camera id is provided.
Austin Borger1c1bee02023-06-01 16:51:35 -0700747 if (cam_id.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700748 return false;
749
750 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
751 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
752 // This isn't a known camera ID, so it's not a system camera.
753 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
754 return false;
755 }
756
757 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
758 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
759 return false;
760 }
761
762 CameraMetadata cameraInfo;
763 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000764 cam_id, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700765 if (res != OK){
766 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
767 cam_id.c_str());
768 return false;
769 }
770
771 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
772 if (auto_location.count != 1)
773 return false;
774
775 uint8_t location = auto_location.data.u8[0];
776 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
777 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
778 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
779 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
780 return false;
781 }
782
783 return true;
784}
785
Austin Borger65e64642024-06-11 15:58:23 -0700786Status CameraService::getNumberOfCameras(int32_t type,
787 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +0000788 int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700789 ATRACE_CALL();
Austin Borger65e64642024-06-11 15:58:23 -0700790 if (vd_flags::camera_device_awareness() && (clientAttribution.deviceId != kDefaultDeviceId)
Biswarup Pal37a75182024-01-16 15:53:35 +0000791 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
Austin Borger65e64642024-06-11 15:58:23 -0700792 *numCameras = mVirtualDeviceCameraIdMapper.getNumberOfCameras(clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000793 return Status::ok();
794 }
795
Emilian Peevaee727d2017-05-04 16:35:48 +0100796 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700797 bool hasSystemCameraPermissions =
Austin Borger22c5c852024-03-08 13:31:36 -0800798 hasPermissionsForSystemCamera(std::string(), getCallingPid(),
799 getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700800 switch (type) {
801 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700802 if (hasSystemCameraPermissions) {
803 *numCameras = static_cast<int>(mNormalDeviceIds.size());
804 } else {
805 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
806 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800807 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700808 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700809 if (hasSystemCameraPermissions) {
810 *numCameras = mNumberOfCameras;
811 } else {
812 *numCameras = mNumberOfCamerasWithoutSystemCamera;
813 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800814 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700815 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800816 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700817 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800818 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
819 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700820 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800821 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700822}
823
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700824Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
Austin Borger65e64642024-06-11 15:58:23 -0700825 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700826 /* out */
827 hardware::camera2::impl::CameraMetadataNative* request) {
828 ATRACE_CALL();
829
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700830 if (!mInitialized) {
831 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
832 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
833 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
834 }
835
Austin Borger65e64642024-06-11 15:58:23 -0700836 std::optional<std::string> cameraIdOptional =
837 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000838 if (!cameraIdOptional.has_value()) {
839 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700840 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000841 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
842 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
843 }
844 std::string cameraId = cameraIdOptional.value();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700845
846 binder::Status res;
847 if (request == nullptr) {
848 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
849 "Camera %s: Error creating default request", cameraId.c_str());
850 return res;
851 }
852 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
853 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
854 cameraId, templateId, &tempId);
855 if (!res.isOk()) {
856 ALOGE("%s: Camera %s: failed to map request Template %d",
857 __FUNCTION__, cameraId.c_str(), templateId);
858 return res;
859 }
860
861 if (shouldRejectSystemCameraConnection(cameraId)) {
862 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
863 "request for system only device %s: ", cameraId.c_str());
864 }
865
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700866 CameraMetadata metadata;
867 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
868 if (err == OK) {
869 request->swap(metadata);
870 } else if (err == BAD_VALUE) {
871 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
872 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
873 cameraId.c_str(), templateId, strerror(-err), err);
874 } else {
875 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
876 "Camera %s: Error creating default request for template %d: %s (%d)",
877 cameraId.c_str(), templateId, strerror(-err), err);
878 }
879 return res;
880}
881
882Status CameraService::isSessionConfigurationWithParametersSupported(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700883 const std::string& unresolvedCameraId, int targetSdkVersion,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700884 const SessionConfiguration& sessionConfiguration,
Austin Borger65e64642024-06-11 15:58:23 -0700885 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700886 /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700887 ATRACE_CALL();
888
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700889 if (!mInitialized) {
890 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
891 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
892 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
893 }
894
Austin Borger65e64642024-06-11 15:58:23 -0700895 std::optional<std::string> cameraIdOptional =
896 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000897 if (!cameraIdOptional.has_value()) {
898 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700899 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000900 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
901 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
902 }
903 std::string cameraId = cameraIdOptional.value();
904
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700905 if (supported == nullptr) {
906 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
907 unresolvedCameraId.c_str());
908 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
909 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
910 }
911
912 if (shouldRejectSystemCameraConnection(cameraId)) {
913 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
914 "session configuration with parameters support for system only device %s: ",
915 cameraId.c_str());
916 }
917
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700918 bool overrideForPerfClass = flags::calculate_perf_override_during_session_support() &&
919 SessionConfigurationUtils::targetPerfClassPrimaryCamera(
920 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
921
Shuzhen Wange3e8e732024-05-22 17:48:01 -0700922 auto ret = isSessionConfigurationWithParametersSupportedUnsafe(cameraId,
923 sessionConfiguration, overrideForPerfClass, supported);
924 if (flags::analytics_24q3()) {
925 mCameraServiceProxyWrapper->logFeatureCombinationQuery(cameraId,
926 getCallingUid(), sessionConfiguration, ret);
927 }
928 return ret;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700929}
930
931Status CameraService::isSessionConfigurationWithParametersSupportedUnsafe(
932 const std::string& cameraId, const SessionConfiguration& sessionConfiguration,
933 bool overrideForPerfClass, /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700934 *supported = false;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700935 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(
936 cameraId, sessionConfiguration, overrideForPerfClass,
937 /*checkSessionParams=*/true, supported);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700938 binder::Status res;
939 switch (ret) {
940 case OK:
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700941 // Expected. Do Nothing.
942 return Status::ok();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700943 case INVALID_OPERATION: {
944 std::string msg = fmt::sprintf(
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700945 "Camera %s: Session configuration with parameters supported query not "
946 "supported!",
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700947 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700948 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
949 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
950 *supported = false;
951 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700952 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700953 break;
954 case NAME_NOT_FOUND: {
955 std::string msg = fmt::sprintf("Camera %s: Unknown camera ID.", cameraId.c_str());
956 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
957 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
958 *supported = false;
959 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
960 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700961 break;
962 default: {
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700963 std::string msg = fmt::sprintf(
964 "Unable to retrieve session configuration support for camera "
965 "device %s: Error: %s (%d)",
966 cameraId.c_str(), strerror(-ret), ret);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700967 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700968 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
969 *supported = false;
970 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700971 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700972 break;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700973 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700974}
975
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800976Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000977 int targetSdkVersion, int rotationOverride,
Austin Borger65e64642024-06-11 15:58:23 -0700978 const SessionConfiguration& sessionConfiguration,
979 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +0000980 /*out*/ CameraMetadata* outMetadata) {
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800981 ATRACE_CALL();
982
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800983 if (outMetadata == nullptr) {
984 std::string msg =
985 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
986 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
987 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
988 }
989
Avichal Rakesh4baf7262024-03-20 19:16:04 -0700990 if (!mInitialized) {
991 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
992 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
993 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
994 }
995
Austin Borger65e64642024-06-11 15:58:23 -0700996 std::optional<std::string> cameraIdOptional =
997 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000998 if (!cameraIdOptional.has_value()) {
999 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001000 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001001 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1002 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1003 }
1004 std::string cameraId = cameraIdOptional.value();
1005
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001006 if (shouldRejectSystemCameraConnection(cameraId)) {
1007 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1008 "Unable to retrieve camera"
1009 "characteristics for system only device %s: ",
1010 cameraId.c_str());
1011 }
1012
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001013 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1014 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001015 if (flags::check_session_support_before_session_char()) {
1016 bool sessionConfigSupported;
1017 Status res = isSessionConfigurationWithParametersSupportedUnsafe(
1018 cameraId, sessionConfiguration, overrideForPerfClass, &sessionConfigSupported);
1019 if (!res.isOk()) {
1020 // isSessionConfigurationWithParametersSupportedUnsafe should log what went wrong and
1021 // report the correct Status to send to the client. Simply forward the error to
1022 // the client.
1023 outMetadata->clear();
1024 return res;
1025 }
1026 if (!sessionConfigSupported) {
1027 std::string msg = fmt::sprintf(
1028 "Session configuration not supported for camera device %s.", cameraId.c_str());
1029 outMetadata->clear();
1030 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1031 }
1032 }
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001033
1034 status_t ret = mCameraProviderManager->getSessionCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001035 cameraId, sessionConfiguration, overrideForPerfClass, rotationOverride, outMetadata);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001036
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001037 switch (ret) {
1038 case OK:
1039 // Expected, no handling needed.
1040 break;
1041 case INVALID_OPERATION: {
1042 std::string msg = fmt::sprintf(
1043 "Camera %s: Session characteristics query not supported!",
1044 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001045 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001046 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1047 outMetadata->clear();
1048 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1049 }
1050 break;
1051 case NAME_NOT_FOUND: {
1052 std::string msg = fmt::sprintf(
1053 "Camera %s: Unknown camera ID.",
1054 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001055 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001056 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1057 outMetadata->clear();
1058 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001059 }
1060 break;
1061 default: {
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001062 std::string msg = fmt::sprintf(
1063 "Unable to retrieve session characteristics for camera device %s: "
1064 "Error: %s (%d)",
1065 cameraId.c_str(), strerror(-ret), ret);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001066 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001067 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1068 outMetadata->clear();
1069 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001070 }
1071 }
1072
Shuzhen Wange3e8e732024-05-22 17:48:01 -07001073 Status res = filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
1074 if (flags::analytics_24q3()) {
1075 mCameraServiceProxyWrapper->logSessionCharacteristicsQuery(cameraId,
1076 getCallingUid(), sessionConfiguration, res);
1077 }
1078 return res;
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001079}
1080
1081Status CameraService::filterSensitiveMetadataIfNeeded(
1082 const std::string& cameraId, CameraMetadata* metadata) {
1083 int callingPid = getCallingPid();
1084 int callingUid = getCallingUid();
1085
1086 if (callingPid == getpid()) {
1087 // Caller is cameraserver; no need to remove keys
1088 return Status::ok();
1089 }
1090
1091 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1092 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1093 ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
1094 metadata->clear();
1095 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1096 "Unable to retrieve camera kind for device %s", cameraId.c_str());
1097 }
1098 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
1099 // Attempting to query system only camera without system camera permission would have
1100 // failed the shouldRejectSystemCameraConnection in the caller. So if we get here
1101 // for a system only camera, then the caller has the required permission.
1102 // No need to remove keys
1103 return Status::ok();
1104 }
1105
1106 std::vector<int32_t> tagsRemoved;
Biswarup Pale506e732024-03-27 13:46:20 +00001107 // Get the device id that owns this camera.
1108 auto [cameraOwnerDeviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1109 cameraId);
1110 bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid,
1111 cameraOwnerDeviceId);
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001112 if (hasCameraPermission) {
1113 // Caller has camera permission; no need to remove keys
1114 return Status::ok();
1115 }
1116
1117 status_t ret = metadata->removePermissionEntries(
1118 mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1119 if (ret != OK) {
1120 metadata->clear();
1121 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1122 "Failed to remove camera characteristics needing camera permission "
1123 "for device %s:%s (%d)",
1124 cameraId.c_str(), strerror(-ret), ret);
1125 }
1126
1127 if (!tagsRemoved.empty()) {
1128 ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1129 tagsRemoved.data(), tagsRemoved.size());
1130 if (ret != OK) {
1131 metadata->clear();
1132 return STATUS_ERROR_FMT(
1133 ERROR_INVALID_OPERATION,
1134 "Failed to insert camera keys needing permission for device %s: %s (%d)",
1135 cameraId.c_str(), strerror(-ret), ret);
1136 }
1137 }
1138 return Status::ok();
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001139}
1140
malikakash22af94c2023-12-04 18:13:14 +00001141Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001142 const std::string& cameraId,
1143 const CameraMetadata& sessionParams) {
1144 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001145 const int pid = getCallingPid();
1146 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001147 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1148 __FUNCTION__, pid, uid);
1149 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1150 "Permission Denial: no permission to inject session params");
1151 }
1152
Biswarup Pal37a75182024-01-16 15:53:35 +00001153 // Do not allow session params injection for a virtual camera.
1154 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1155 if (deviceId != kDefaultDeviceId) {
1156 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1157 "Cannot inject session params for a virtual camera");
1158 }
1159
malikakash22af94c2023-12-04 18:13:14 +00001160 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1161 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1162
1163 auto clientDescriptor = mActiveClientManager.get(cameraId);
1164 if (clientDescriptor == nullptr) {
1165 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1166 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1167 "No active client for camera id %s", cameraId.c_str());
1168 }
1169
1170 sp<BasicClient> clientSp = clientDescriptor->getValue();
1171 status_t res = clientSp->injectSessionParams(sessionParams);
1172
1173 if (res != OK) {
1174 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1175 "Error injecting session params into camera \"%s\": %s (%d)",
1176 cameraId.c_str(), strerror(-res), res);
1177 }
1178 return Status::ok();
1179}
1180
Biswarup Pal37a75182024-01-16 15:53:35 +00001181std::optional<std::string> CameraService::resolveCameraId(
1182 const std::string& inputCameraId,
1183 int32_t deviceId,
malikakash98260df2024-05-10 23:33:57 +00001184 int32_t devicePolicy) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001185 if ((deviceId == kDefaultDeviceId)
1186 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1187 auto [storedDeviceId, _] =
1188 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1189 if (storedDeviceId != kDefaultDeviceId) {
1190 // Trying to access a virtual camera from default-policy device context, we should fail.
1191 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1192 inputCameraId.c_str(), deviceId);
1193 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1194 return std::nullopt;
1195 }
malikakash98260df2024-05-10 23:33:57 +00001196 return inputCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001197 }
1198
1199 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1200}
1201
Austin Borger65e64642024-06-11 15:58:23 -07001202Status CameraService::getCameraInfo(int cameraId, int rotationOverride,
1203 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
1204 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001205 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001206 Mutex::Autolock l(mServiceLock);
Austin Borger65e64642024-06-11 15:58:23 -07001207 std::string cameraIdStr =
1208 cameraIdIntToStrLocked(cameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001209 if (cameraIdStr.empty()) {
1210 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001211 cameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001212 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1213 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1214 }
malikakashedb38962023-09-06 00:03:35 +00001215
Austin Borgered99f642023-06-01 16:51:35 -07001216 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001217 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1218 "characteristics for system only device %s: ", cameraIdStr.c_str());
1219 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001220
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001221 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001222 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001223 return STATUS_ERROR(ERROR_DISCONNECTED,
1224 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001225 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001226 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001227 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001228 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1229 if (hasSystemCameraPermissions) {
1230 cameraIdBound = mNumberOfCameras;
1231 }
1232 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001233 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1234 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001235 }
1236
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001237 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001238 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001239 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001240 cameraIdStr, rotationOverride, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001241 if (err != OK) {
1242 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1243 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1244 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001245 logServiceError(std::string("Error retrieving camera info from device ")
1246 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001247 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001248
Ruben Brunkcc776712015-02-17 20:18:47 -08001249 return ret;
1250}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001251
Biswarup Pal37a75182024-01-16 15:53:35 +00001252std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1253 int32_t deviceId, int32_t devicePolicy) {
1254 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1255 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1256 std::optional<std::string> cameraIdOptional =
1257 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1258 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1259 }
1260
1261 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001262 auto callingPid = getCallingPid();
1263 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001264 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1265 callingPid, callingUid, /* checkCameraPermissions= */ false);
1266 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001267 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001268 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001269 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1270 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1271 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001272 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001273 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001274
malikakash98260df2024-05-10 23:33:57 +00001275 return (*cameraIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001276}
1277
Biswarup Pal37a75182024-01-16 15:53:35 +00001278std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1279 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001280 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001281 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001282}
1283
Austin Borgered99f642023-06-01 16:51:35 -07001284Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07001285 int targetSdkVersion, int rotationOverride, const AttributionSourceState& clientAttribution,
1286 int32_t devicePolicy, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001287 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001288
Zhijun He2b59be82013-09-25 10:14:30 -07001289 if (!cameraInfo) {
1290 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001291 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001292 }
1293
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001294 if (!mInitialized) {
1295 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001296 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001297 return STATUS_ERROR(ERROR_DISCONNECTED,
1298 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001299 }
1300
Austin Borger65e64642024-06-11 15:58:23 -07001301 std::optional<std::string> cameraIdOptional =
1302 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001303 if (!cameraIdOptional.has_value()) {
1304 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001305 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001306 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1307 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1308 }
1309 std::string cameraId = cameraIdOptional.value();
1310
Austin Borgered99f642023-06-01 16:51:35 -07001311 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001312 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001313 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001314 }
1315
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001316 bool overrideForPerfClass =
1317 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001318 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001319 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001320 cameraId, overrideForPerfClass, cameraInfo, rotationOverride);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001321 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001322 if (res == NAME_NOT_FOUND) {
1323 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001324 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001325 strerror(-res), res);
1326 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001327 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1328 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001329 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001330 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001331 strerror(-res), res);
1332 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001333 }
Emilian Peeve20c6372018-08-14 18:45:53 +01001334
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001335 return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -07001336}
1337
Austin Borger65e64642024-06-11 15:58:23 -07001338Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId,
1339 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00001340 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001341 ATRACE_CALL();
1342 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001343
Austin Borger65e64642024-06-11 15:58:23 -07001344 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
1345 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001346 if (!cameraIdOptional.has_value()) {
1347 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001348 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001349 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1350 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1351 }
1352 std::string cameraId = cameraIdOptional.value();
1353
Rucha Katakwar38284522021-11-10 11:25:21 -08001354 if (!mInitialized) {
1355 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1356 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1357 }
1358
Biswarup Pal37a75182024-01-16 15:53:35 +00001359 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001360 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1361 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1362 }
1363
Austin Borgered99f642023-06-01 16:51:35 -07001364 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001365 if (res != OK) {
1366 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001367 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001368 strerror(-res), res);
1369 }
1370 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1371 return Status::ok();
1372}
1373
Austin Borgered99f642023-06-01 16:51:35 -07001374std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001375 time_t now = time(nullptr);
1376 char formattedTime[64];
1377 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001378 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001379}
1380
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001381Status CameraService::getCameraVendorTagDescriptor(
1382 /*out*/
1383 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001384 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001385 if (!mInitialized) {
1386 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001387 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001388 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001389 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1390 if (globalDescriptor != nullptr) {
1391 *desc = *(globalDescriptor.get());
1392 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001393 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001394}
1395
Emilian Peev71c73a22017-03-21 16:35:51 +00001396Status CameraService::getCameraVendorTagCache(
1397 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1398 ATRACE_CALL();
1399 if (!mInitialized) {
1400 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1401 return STATUS_ERROR(ERROR_DISCONNECTED,
1402 "Camera subsystem not available");
1403 }
1404 sp<VendorTagDescriptorCache> globalCache =
1405 VendorTagDescriptorCache::getGlobalVendorTagCache();
1406 if (globalCache != nullptr) {
1407 *cache = *(globalCache.get());
1408 }
1409 return Status::ok();
1410}
1411
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001412void CameraService::clearCachedVariables() {
1413 BasicClient::BasicClient::sCameraService = nullptr;
1414}
1415
Austin Borgered99f642023-06-01 16:51:35 -07001416std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001417 int rotationOverride, int* portraitRotation, int* facing,
1418 int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001419 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001420
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001421 int deviceVersion = 0;
1422
Emilian Peevf53f66e2017-04-11 14:29:43 +01001423 status_t res;
1424 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001425 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001426 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001427 if (res != OK || transport == IPCTransport::INVALID) {
1428 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001429 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001430 return std::make_pair(-1, IPCTransport::INVALID) ;
1431 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001432 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001433
Emilian Peevf53f66e2017-04-11 14:29:43 +01001434 hardware::CameraInfo info;
1435 if (facing) {
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001436 res = mCameraProviderManager->getCameraInfo(cameraId, rotationOverride,
Austin Borger18b30a72022-10-27 12:20:29 -07001437 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001438 if (res != OK) {
1439 return std::make_pair(-1, IPCTransport::INVALID);
1440 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001441 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001442 if (orientation) {
1443 *orientation = info.orientation;
1444 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001445 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001446
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001447 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001448}
1449
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001450Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001451 switch(err) {
1452 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001453 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001454 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001455 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1456 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001457 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001458 return STATUS_ERROR(ERROR_DISCONNECTED,
1459 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001460 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001461 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1462 "Camera HAL encountered error %d: %s",
1463 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001464 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001465}
1466
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001467Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001468 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1469 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001470 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001471 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001472 apiLevel effectiveApiLevel, bool overrideForPerfClass, int rotationOverride,
malikakash73125c62023-07-21 22:44:34 +00001473 bool forceSlowJpegMode, const std::string& originalCameraId,
1474 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001475 // For HIDL devices
1476 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1477 // Create CameraClient based on device version reported by the HAL.
1478 int deviceVersion = deviceVersionAndTransport.first;
1479 switch(deviceVersion) {
1480 case CAMERA_DEVICE_API_VERSION_1_0:
1481 ALOGE("Camera using old HAL version: %d", deviceVersion);
1482 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1483 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001484 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001485 break;
1486 case CAMERA_DEVICE_API_VERSION_3_0:
1487 case CAMERA_DEVICE_API_VERSION_3_1:
1488 case CAMERA_DEVICE_API_VERSION_3_2:
1489 case CAMERA_DEVICE_API_VERSION_3_3:
1490 case CAMERA_DEVICE_API_VERSION_3_4:
1491 case CAMERA_DEVICE_API_VERSION_3_5:
1492 case CAMERA_DEVICE_API_VERSION_3_6:
1493 case CAMERA_DEVICE_API_VERSION_3_7:
1494 break;
1495 default:
1496 // Should not be reachable
1497 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1498 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1499 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001500 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001501 }
1502 }
1503 if (effectiveApiLevel == API_1) { // Camera1 API route
1504 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001505 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001506 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001507 api1CameraId, facing, sensorOrientation,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001508 clientPid, clientUid, servicePid, overrideForPerfClass, rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00001509 forceSlowJpegMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001510 ALOGI("%s: Camera1 API (legacy), rotationOverride %d, forceSlowJpegMode %d",
1511 __FUNCTION__, rotationOverride, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001512 } else { // Camera2 API route
1513 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1514 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001515 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001516 cameraService->mCameraServiceProxyWrapper,
1517 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001518 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001519 overrideForPerfClass, rotationOverride, originalCameraId);
1520 ALOGI("%s: Camera2 API, rotationOverride %d", __FUNCTION__, rotationOverride);
Ruben Brunkcc776712015-02-17 20:18:47 -08001521 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001522 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001523}
1524
Austin Borgered99f642023-06-01 16:51:35 -07001525std::string CameraService::toString(std::set<userid_t> intSet) {
1526 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001527 bool first = true;
1528 for (userid_t i : intSet) {
1529 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001530 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001531 first = false;
1532 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001533 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001534 }
1535 }
Yi Kong3ac211f2024-08-12 07:31:44 +08001536 return s.str();
Ruben Brunk6267b532015-04-30 17:44:07 -07001537}
1538
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001539int32_t CameraService::mapToInterface(TorchModeStatus status) {
1540 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1541 switch (status) {
1542 case TorchModeStatus::NOT_AVAILABLE:
1543 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1544 break;
1545 case TorchModeStatus::AVAILABLE_OFF:
1546 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1547 break;
1548 case TorchModeStatus::AVAILABLE_ON:
1549 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1550 break;
1551 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001552 ALOGW("Unknown new flash status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001553 }
1554 return serviceStatus;
1555}
1556
1557CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1558 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1559 switch (status) {
1560 case CameraDeviceStatus::NOT_PRESENT:
1561 serviceStatus = StatusInternal::NOT_PRESENT;
1562 break;
1563 case CameraDeviceStatus::PRESENT:
1564 serviceStatus = StatusInternal::PRESENT;
1565 break;
1566 case CameraDeviceStatus::ENUMERATING:
1567 serviceStatus = StatusInternal::ENUMERATING;
1568 break;
1569 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001570 ALOGW("Unknown new HAL device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001571 }
1572 return serviceStatus;
1573}
1574
1575int32_t CameraService::mapToInterface(StatusInternal status) {
1576 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1577 switch (status) {
1578 case StatusInternal::NOT_PRESENT:
1579 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1580 break;
1581 case StatusInternal::PRESENT:
1582 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1583 break;
1584 case StatusInternal::ENUMERATING:
1585 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1586 break;
1587 case StatusInternal::NOT_AVAILABLE:
1588 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1589 break;
1590 case StatusInternal::UNKNOWN:
1591 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1592 break;
1593 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001594 ALOGW("Unknown new internal device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001595 }
1596 return serviceStatus;
1597}
1598
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001599Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001600 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001601
Austin Borgered99f642023-06-01 16:51:35 -07001602 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001603 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001604 sp<Client> tmp = nullptr;
Austin Borger7d2b9232024-07-22 14:17:14 -07001605
Austin Borgerb01a8702024-07-22 16:20:34 -07001606 int callingPid = getCallingPid();
1607 logConnectionAttempt(callingPid, kServiceName, cameraIdStr, API_1);
Austin Borger7d2b9232024-07-22 14:17:14 -07001608
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001609 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001610 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
Austin Borgerb01a8702024-07-22 16:20:34 -07001611 kServiceName, /*systemNativeClient*/ false, {}, uid, callingPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001612 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001613 /*targetSdkVersion*/ __ANDROID_API_FUTURE__,
1614 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_OVERRIDE_TO_PORTRAIT,
Austin Borger7d2b9232024-07-22 14:17:14 -07001615 /*forceSlowJpegMode*/false, cameraIdStr, /*isNonSystemNdk*/ false, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001616 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001617 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001618 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001619 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001620}
1621
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001622Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001623 /*out*/
1624 CameraParameters* parameters) {
1625
1626 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1627
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001628 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001629
1630 if (parameters == NULL) {
1631 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001632 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001633 }
1634
malikakash98260df2024-05-10 23:33:57 +00001635 std::string cameraIdStr = std::to_string(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001636
1637 // Check if we already have parameters
1638 {
1639 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001640 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001641 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001642 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001643 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001644 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001645 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001646 }
1647 CameraParameters p = cameraState->getShimParams();
1648 if (!p.isEmpty()) {
1649 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001650 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001651 }
1652 }
1653
Austin Borger22c5c852024-03-08 13:31:36 -08001654 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001655 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001656 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001657 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001658 // Error already logged by callee
1659 return ret;
1660 }
1661
1662 // Check for parameters again
1663 {
1664 // Scope for service lock
1665 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001666 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001667 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001668 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001669 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001670 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001671 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001672 CameraParameters p = cameraState->getShimParams();
1673 if (!p.isEmpty()) {
1674 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001675 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001676 }
1677 }
1678
Ruben Brunkcc776712015-02-17 20:18:47 -08001679 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1680 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001681 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001682}
1683
Austin Borgered99f642023-06-01 16:51:35 -07001684Status CameraService::validateConnectLocked(const std::string& cameraId,
Austin Borgerb01a8702024-07-22 16:20:34 -07001685 const std::string& clientName8, int clientUid, int clientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001686
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001687#ifdef __BRILLO__
1688 UNUSED(clientName8);
1689 UNUSED(clientUid);
1690 UNUSED(clientPid);
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001691#else
Austin Borger6e831c42024-07-22 13:07:56 -07001692 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001693 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001694 return allowed;
1695 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001696#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001697
Austin Borger22c5c852024-03-08 13:31:36 -08001698 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001699
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001700 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001701 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1702 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001703 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001704 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001705 }
1706
Ruben Brunkcc776712015-02-17 20:18:47 -08001707 if (getCameraState(cameraId) == nullptr) {
1708 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001709 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001710 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001711 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001712 }
1713
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001714 status_t err = checkIfDeviceIsUsable(cameraId);
1715 if (err != NO_ERROR) {
1716 switch(err) {
1717 case -ENODEV:
1718 case -EBUSY:
1719 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001720 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001721 default:
1722 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001723 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001724 }
1725 }
1726 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001727}
1728
Austin Borgerb01a8702024-07-22 16:20:34 -07001729Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1730 const std::string& clientName, int clientUid, int clientPid) const {
1731 int callingPid = getCallingPid();
1732 int callingUid = getCallingUid();
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001733
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001734 if (shouldRejectSystemCameraConnection(cameraId)) {
1735 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1736 cameraId.c_str());
1737 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001738 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001739 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001740 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1741 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001742 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001743 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001744 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001745 }
1746
Biswarup Pale506e732024-03-27 13:46:20 +00001747 // Get the device id that owns this camera.
1748 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1749
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001750 // If it's not calling from cameraserver, check the permission if the
1751 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1752 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001753 bool checkPermissionForCamera =
Biswarup Pale506e732024-03-27 13:46:20 +00001754 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName, deviceId);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001755 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001756 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001757 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001758 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1759 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001760 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001761 }
1762
Svet Ganova453d0d2018-01-11 15:37:58 -08001763 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001764 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001765 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001766 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1767 clientPid, clientUid);
1768 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001769 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1770 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001771 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001772 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001773 }
1774
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001775 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1776 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1777 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1778 if ((!isAutomotivePrivilegedClient(callingUid) ||
1779 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1780 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001781 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1782 return STATUS_ERROR_FMT(ERROR_DISABLED,
1783 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001784 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001785 }
1786
Austin Borger6e831c42024-07-22 13:07:56 -07001787 userid_t clientUserId = multiuser_get_user_id(clientUid);
1788
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001789 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1790 // connected to camera service directly.
Wu-cheng Lia3355432011-05-20 14:54:25 +08001791
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001792 // For non-system clients : Only allow clients who are being used by the current foreground
1793 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08001794 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001795 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001796 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1797 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001798 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001799 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1800 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001801 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001802 }
1803
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001804 if (flags::camera_hsum_permission()) {
1805 // If the System User tries to access the camera when the device is running in
1806 // headless system user mode, ensure that client has the required permission
1807 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07001808 if (isHeadlessSystemUserMode()
1809 && (clientUserId == USER_SYSTEM)
1810 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Austin Borger6e831c42024-07-22 13:07:56 -07001811 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", callingPid, clientUid);
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001812 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1813 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1814 User without camera headless system user permission",
Austin Borger6e831c42024-07-22 13:07:56 -07001815 clientName.c_str(), callingPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001816 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001817 }
1818
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001819 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001820}
1821
Austin Borgered99f642023-06-01 16:51:35 -07001822status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001823 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001824 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001825 if (cameraState == nullptr) {
1826 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001827 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001828 return -ENODEV;
1829 }
1830
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001831 StatusInternal currentStatus = cameraState->getStatus();
1832 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001833 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001834 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001835 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001836 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001837 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001838 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001839 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001840 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001841
Ruben Brunkcc776712015-02-17 20:18:47 -08001842 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001843}
1844
Ruben Brunkcc776712015-02-17 20:18:47 -08001845void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001846 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001847
Ruben Brunkcc776712015-02-17 20:18:47 -08001848 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001849 auto clientDescriptor =
1850 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001851 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001852 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1853
1854 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001855 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001856
1857 if (evicted.size() > 0) {
1858 // This should never happen - clients should already have been removed in disconnect
1859 for (auto& i : evicted) {
1860 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001861 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001862 }
1863
1864 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1865 __FUNCTION__);
1866 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001867
1868 // And register a death notification for the client callback. Do
1869 // this last to avoid Binder policy where a nested Binder
1870 // transaction might be pre-empted to service the client death
1871 // notification if the client process dies before linkToDeath is
1872 // invoked.
1873 sp<IBinder> remoteCallback = client->getRemote();
1874 if (remoteCallback != nullptr) {
1875 remoteCallback->linkToDeath(this);
1876 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001877}
1878
Austin Borgered99f642023-06-01 16:51:35 -07001879status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1880 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1881 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001882 /*out*/
1883 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001884 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001885 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001886 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001887 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001888 DescriptorPtr clientDescriptor;
1889 {
1890 if (effectiveApiLevel == API_1) {
1891 // If we are using API1, any existing client for this camera ID with the same remote
1892 // should be returned rather than evicted to allow MediaRecorder to work properly.
1893
1894 auto current = mActiveClientManager.get(cameraId);
1895 if (current != nullptr) {
1896 auto clientSp = current->getValue();
1897 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001898 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001899 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001900 " API level, evicting prior client...");
1901 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001902 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001903 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001904 *client = clientSp;
1905 return NO_ERROR;
1906 }
1907 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001908 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001909 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001910
Ruben Brunkcc776712015-02-17 20:18:47 -08001911 // Get state for the given cameraId
1912 auto state = getCameraState(cameraId);
1913 if (state == nullptr) {
1914 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001915 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001916 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001917 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001918 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001919
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001920 sp<IServiceManager> sm = defaultServiceManager();
1921 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08001922 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001923 // If processinfo service is not available and the client is automotive privileged
1924 // client used for safety critical uses cases such as rear-view and surround-view which
1925 // needs to be available before android boot completes, then use the hardcoded values
1926 // for the process state and priority score. As this scenario is before android system
1927 // services are up and client is native client, hence using NATIVE_ADJ as the priority
1928 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
1929 // visible on the top.
1930 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1931 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1932 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
1933 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
1934 } else {
1935 // Get current active client PIDs
1936 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1937 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001938
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001939 std::vector<int> priorityScores(ownerPids.size());
1940 std::vector<int> states(ownerPids.size());
1941
1942 // Get priority scores of all active PIDs
1943 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
1944 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
1945 if (err != OK) {
1946 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
1947 return err;
1948 }
1949
1950 // Update all active clients' priorities
1951 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
1952 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1953 pidToPriorityMap.emplace(ownerPids[i],
1954 resource_policy::ClientPriority(priorityScores[i], states[i],
1955 /* isVendorClient won't get copied over*/ false,
1956 /* oomScoreOffset won't get copied over*/ 0));
1957 }
1958 mActiveClientManager.updatePriorities(pidToPriorityMap);
1959
1960 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1961 int32_t actualState = states[states.size() - 1];
1962
1963 // Make descriptor for incoming client. We store the oomScoreOffset
1964 // since we might need it later on new handleEvictionsLocked and
1965 // ProcessInfoService would not take that into account.
1966 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1967 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1968 state->getConflicting(), actualScore, clientPid, actualState,
1969 oomScoreOffset, systemNativeClient);
1970 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001971
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001972 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1973
Ruben Brunkcc776712015-02-17 20:18:47 -08001974 // Find clients that would be evicted
1975 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1976
1977 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1978 // background, so we cannot do evictions
1979 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1980 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1981 " priority).", clientPid);
1982
1983 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07001984 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08001985 auto incompatibleClients =
1986 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1987
Austin Borgered99f642023-06-01 16:51:35 -07001988 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
1989 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
1990 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001991 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001992
1993 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07001994 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001995 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001996 i->getKey().c_str(),
1997 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00001998 i->getOwnerId(), i->getPriority().getScore(),
1999 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002000 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002001 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2002 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002003 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002004 }
2005
2006 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002007 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002008 mEventLog.add(msg);
2009
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002010 auto current = mActiveClientManager.get(cameraId);
2011 if (current != nullptr) {
2012 return -EBUSY; // CAMERA_IN_USE
2013 } else {
2014 return -EUSERS; // MAX_CAMERAS_IN_USE
2015 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002016 }
2017
2018 for (auto& i : evicted) {
2019 sp<BasicClient> clientSp = i->getValue();
2020 if (clientSp.get() == nullptr) {
2021 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2022
2023 // TODO: Remove this
2024 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2025 __FUNCTION__);
2026 mActiveClientManager.remove(i);
2027 continue;
2028 }
2029
2030 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002031 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002032 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002033
Ruben Brunkcc776712015-02-17 20:18:47 -08002034 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002035 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002036 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2037 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002038 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002039 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002040 i->getPriority().getState(), cameraId.c_str(),
2041 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002042 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002043
2044 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002045 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002046 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002047 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002048 }
2049
Ruben Brunkcc776712015-02-17 20:18:47 -08002050 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2051 // other clients from connecting in mServiceLockWrapper if held
2052 mServiceLock.unlock();
2053
2054 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002055 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002056
2057 // Destroy evicted clients
2058 for (auto& i : evictedClients) {
2059 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002060 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002061 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002062
Austin Borger22c5c852024-03-08 13:31:36 -08002063 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002064
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002065 for (const auto& i : evictedClients) {
2066 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002067 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002068 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2069 if (ret == TIMED_OUT) {
2070 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002071 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2072 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002073 return -EBUSY;
2074 }
2075 if (ret != NO_ERROR) {
2076 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002077 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2078 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002079 return ret;
2080 }
2081 }
2082
2083 evictedClients.clear();
2084
Ruben Brunkcc776712015-02-17 20:18:47 -08002085 // Once clients have been disconnected, relock
2086 mServiceLock.lock();
2087
2088 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2089 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2090 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002091 }
2092
Ruben Brunkcc776712015-02-17 20:18:47 -08002093 *partial = clientDescriptor;
2094 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002095}
2096
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002097Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002098 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002099 int api1CameraId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002100 int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002101 int rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00002102 bool forceSlowJpegMode,
Austin Borger65e64642024-06-11 15:58:23 -07002103 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00002104 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002105 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002106 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002107 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002108 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002109
Austin Borger65e64642024-06-11 15:58:23 -07002110 std::string cameraIdStr =
2111 cameraIdIntToStr(api1CameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002112 if (cameraIdStr.empty()) {
2113 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002114 api1CameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002115 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2116 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2117 }
malikakashedb38962023-09-06 00:03:35 +00002118
Austin Borger7d2b9232024-07-22 14:17:14 -07002119 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
2120 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
Austin Borger7d2b9232024-07-22 14:17:14 -07002121
Austin Borger95a00152024-09-23 17:20:24 -07002122 AttributionSourceState resolvedClientAttribution(clientAttribution);
2123 ret = resolveAttributionSource(resolvedClientAttribution, __FUNCTION__, cameraIdStr);
2124 if (!ret.isOk()) {
2125 logRejected(cameraIdStr, getCallingPid(),
2126 clientAttribution.packageName.value_or("<unknown>"),
2127 toStdString(ret.toString8()));
2128 return ret;
Austin Borgerb01a8702024-07-22 16:20:34 -07002129 }
2130
Austin Borger95a00152024-09-23 17:20:24 -07002131 const int clientPid = resolvedClientAttribution.pid;
2132 const int clientUid = resolvedClientAttribution.uid;
2133 const std::string& clientPackageName = *resolvedClientAttribution.packageName;
2134
2135 logConnectionAttempt(clientPid, clientPackageName, cameraIdStr, API_1);
Austin Borgerb01a8702024-07-22 16:20:34 -07002136
Ruben Brunkcc776712015-02-17 20:18:47 -08002137 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002138 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
Austin Borger7d2b9232024-07-22 14:17:14 -07002139 clientPackageName, /*systemNativeClient*/ false, {},
Austin Borgerb01a8702024-07-22 16:20:34 -07002140 clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002141 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borger7d2b9232024-07-22 14:17:14 -07002142 rotationOverride, forceSlowJpegMode, cameraIdStr, isNonSystemNdk, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002143
Biswarup Pal37a75182024-01-16 15:53:35 +00002144 if (!ret.isOk()) {
Austin Borger95a00152024-09-23 17:20:24 -07002145 logRejected(cameraIdStr, getCallingPid(),
2146 clientAttribution.packageName.value_or("<unknown>"),
2147 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002148 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002149 }
2150
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002151 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002152
2153 const sp<IServiceManager> sm(defaultServiceManager());
2154 const auto& mActivityManager = getActivityManager();
2155 if (mActivityManager) {
2156 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002157 getCallingUid(),
2158 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002159 }
2160
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002161 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002162}
2163
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002164bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2165 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002166 // If the client is not a vendor client, don't add listener if
2167 // a) the camera is a publicly hidden secure camera OR
2168 // b) the camera is a system only camera and the client doesn't
2169 // have android.permission.SYSTEM_CAMERA permissions.
2170 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2171 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002172 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002173 return true;
2174 }
2175 return false;
2176}
2177
Austin Borgered99f642023-06-01 16:51:35 -07002178bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002179 // Rules for rejection:
2180 // 1) If cameraserver tries to access this camera device, accept the
2181 // connection.
2182 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002183 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002184 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2185 // and the serving thread is a non hwbinder thread, the client must have
2186 // android.permission.SYSTEM_CAMERA permissions to connect.
2187
Austin Borger22c5c852024-03-08 13:31:36 -08002188 int cPid = getCallingPid();
2189 int cUid = getCallingUid();
2190 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002191 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2192 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002193 // This isn't a known camera ID, so it's not a system camera
2194 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2195 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002196 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002197
2198 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002199 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002200 return false;
2201 }
2202 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002203 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002204 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2205 return true;
2206 }
2207 // (3) Here we only check for permissions if it is a system only camera device. This is since
2208 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2209 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2210 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002211 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002212 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002213 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2214 cameraId.c_str());
2215 return true;
2216 }
2217
2218 return false;
2219}
2220
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002221Status CameraService::connectDevice(
2222 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002223 const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002224 int oomScoreOffset, int targetSdkVersion,
2225 int rotationOverride, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Ruben Brunkcc776712015-02-17 20:18:47 -08002226 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002227 sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002228 ATRACE_CALL();
Emilian Peev31bd2422024-04-23 22:24:09 +00002229 RunThreadWithRealtimePriority priorityBump;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002230 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002231 sp<CameraDeviceClient> client = nullptr;
Austin Borger7d2b9232024-07-22 14:17:14 -07002232 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
Austin Borger22c5c852024-03-08 13:31:36 -08002233 int callingPid = getCallingPid();
2234 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002235 bool systemNativeClient = false;
Austin Borger7d2b9232024-07-22 14:17:14 -07002236 if (callerHasSystemUid() && (clientPackageNameMaybe.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002237 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borger7d2b9232024-07-22 14:17:14 -07002238 clientPackageNameMaybe = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002239 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002240 }
Austin Borger249e6592024-03-10 22:28:11 -07002241
Austin Borger65e64642024-06-11 15:58:23 -07002242 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2243 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002244 if (!cameraIdOptional.has_value()) {
2245 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002246 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002247 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2248 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2249 }
2250 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002251
Austin Borger7d2b9232024-07-22 14:17:14 -07002252 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
Austin Borger7d2b9232024-07-22 14:17:14 -07002253
Austin Borger95a00152024-09-23 17:20:24 -07002254 AttributionSourceState resolvedClientAttribution(clientAttribution);
2255 if (!flags::use_context_attribution_source()) {
2256 resolvedClientAttribution.pid = USE_CALLING_PID;
2257 }
2258 ret = resolveAttributionSource(resolvedClientAttribution, __FUNCTION__, cameraId);
2259 if (!ret.isOk()) {
2260 logRejected(cameraId, getCallingPid(), clientAttribution.packageName.value_or(""),
2261 toStdString(ret.toString8()));
2262 return ret;
Austin Borgerb01a8702024-07-22 16:20:34 -07002263 }
2264
Austin Borger95a00152024-09-23 17:20:24 -07002265 const int clientPid = resolvedClientAttribution.pid;
2266 const int clientUid = resolvedClientAttribution.uid;
2267 const std::string& clientPackageName = *resolvedClientAttribution.packageName;
2268 userid_t clientUserId = multiuser_get_user_id(resolvedClientAttribution.uid);
Austin Borgerb01a8702024-07-22 16:20:34 -07002269
Austin Borger95a00152024-09-23 17:20:24 -07002270 logConnectionAttempt(clientPid, clientPackageName, cameraId, API_2);
Austin Borgerb01a8702024-07-22 16:20:34 -07002271
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002272 if (oomScoreOffset < 0) {
Austin Borger95a00152024-09-23 17:20:24 -07002273 std::string msg = fmt::sprintf(
2274 "Cannot increase the priority of a client %s pid %d for "
2275 "camera id %s",
2276 clientPackageName.c_str(), clientPid, cameraId.c_str());
Austin Borgered99f642023-06-01 16:51:35 -07002277 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2278 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002279 }
2280
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002281 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2282 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002283 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2284 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002285 std::string msg = "Camera disabled by device policy";
2286 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2287 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002288 }
2289
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002290 // enforce system camera permissions
Austin Borger95a00152024-09-23 17:20:24 -07002291 if (oomScoreOffset > 0 && !hasPermissionsForSystemCamera(cameraId, clientPid, callingUid) &&
2292 !isTrustedCallingUid(callingUid)) {
2293 std::string msg = fmt::sprintf(
2294 "Cannot change the priority of a client %s pid %d for "
2295 "camera id %s without SYSTEM_CAMERA permissions",
2296 clientPackageName.c_str(), clientPid, cameraId.c_str());
Austin Borgered99f642023-06-01 16:51:35 -07002297 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2298 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002299 }
2300
Austin Borger95a00152024-09-23 17:20:24 -07002301 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks, CameraDeviceClient>(
2302 cameraCb, cameraId, /*api1CameraId*/ -1, clientPackageName, systemNativeClient,
2303 resolvedClientAttribution.attributionTag, clientUid, clientPid, API_2,
Austin Borgerd1ad6c62024-07-01 11:28:31 -07002304 /*shimUpdateOnly*/ false, oomScoreOffset, targetSdkVersion, rotationOverride,
Austin Borger95a00152024-09-23 17:20:24 -07002305 /*forceSlowJpegMode*/ false, unresolvedCameraId, isNonSystemNdk, /*out*/ client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002306
Biswarup Pal37a75182024-01-16 15:53:35 +00002307 if (!ret.isOk()) {
Austin Borger95a00152024-09-23 17:20:24 -07002308 logRejected(cameraId, clientPid, clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002309 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002310 }
2311
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002312 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002313 Mutex::Autolock lock(mServiceLock);
2314
2315 // Clear the previous cached logs and reposition the
2316 // file offset to beginning of the file to log new data.
2317 // If either truncate or lseek fails, close the previous file and create a new one.
2318 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2319 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2320 // Close the previous memfd.
2321 close(mMemFd);
2322 // If failure to wipe the data, then create a new file and
2323 // assign the new value to mMemFd.
2324 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2325 if (mMemFd == -1) {
2326 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2327 }
2328 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002329 const sp<IServiceManager> sm(defaultServiceManager());
2330 const auto& mActivityManager = getActivityManager();
2331 if (mActivityManager) {
2332 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002333 callingUid,
2334 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002335 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002336 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002337}
2338
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002339bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2340 int callingPid, int callingUid) {
2341 if (!isAutomotiveDevice()) {
2342 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2343 }
2344
2345 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2346 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2347 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2348 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2349 "using camera %s", callingUid, cam_id.c_str());
2350 return false;
2351 }
2352
2353 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2354 return true;
2355 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2356 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002357 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2358 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002359 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2360 return false;
2361 } else {
2362 return true;
2363 }
2364 }
2365 return false;
2366}
2367
Austin Borger7d2b9232024-07-22 14:17:14 -07002368void CameraService::logConnectionAttempt(int clientPid, const std::string& clientPackageName,
Austin Borger95a00152024-09-23 17:20:24 -07002369 const std::string& cameraId,
2370 apiLevel effectiveApiLevel) const {
Austin Borger7d2b9232024-07-22 14:17:14 -07002371 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borger95a00152024-09-23 17:20:24 -07002372 "Camera API version %d",
2373 clientPid, clientPackageName.c_str(), cameraId.c_str(),
2374 static_cast<int>(effectiveApiLevel));
Austin Borger7d2b9232024-07-22 14:17:14 -07002375}
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002376
Austin Borger7d2b9232024-07-22 14:17:14 -07002377template<class CALLBACK, class CLIENT>
2378Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2379 int api1CameraId, const std::string& clientPackageName, bool systemNativeClient,
2380 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
2381 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
2382 int rotationOverride, bool forceSlowJpegMode,
2383 const std::string& originalCameraId, bool isNonSystemNdk, /*out*/sp<CLIENT>& device) {
2384 binder::Status ret = binder::Status::ok();
2385
Shuzhen Wang316781a2020-08-18 18:11:01 -07002386 nsecs_t openTimeNs = systemTime();
2387
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002388 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002389 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002390 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002391
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002392 {
2393 // Acquire mServiceLock and prevent other clients from connecting
2394 std::unique_ptr<AutoConditionLock> lock =
2395 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2396
2397 if (lock == nullptr) {
2398 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2399 , clientPid);
2400 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2401 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002402 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002403 }
2404
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002405 // Enforce client permissions and do basic validity checks
Biswarup Pal37a75182024-01-16 15:53:35 +00002406 if (!(ret = validateConnectLocked(cameraId, clientPackageName,
Austin Borger6e831c42024-07-22 13:07:56 -07002407 /*inout*/clientUid, /*inout*/clientPid)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002408 return ret;
2409 }
2410
2411 // Check the shim parameters after acquiring lock, if they have already been updated and
2412 // we were doing a shim update, return immediately
2413 if (shimUpdateOnly) {
2414 auto cameraState = getCameraState(cameraId);
2415 if (cameraState != nullptr) {
2416 if (!cameraState->getShimParams().isEmpty()) return ret;
2417 }
2418 }
2419
2420 status_t err;
2421
2422 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002423 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Austin Borger6e831c42024-07-22 13:07:56 -07002424 if ((err = handleEvictionsLocked(cameraId, clientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002425 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2426 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002427 switch (err) {
2428 case -ENODEV:
2429 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2430 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002431 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002432 case -EBUSY:
2433 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2434 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002435 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002436 case -EUSERS:
2437 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2438 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002439 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002440 default:
2441 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2442 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002443 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002444 }
2445 }
2446
2447 if (clientTmp.get() != nullptr) {
2448 // Handle special case for API1 MediaRecorder where the existing client is returned
2449 device = static_cast<CLIENT*>(clientTmp.get());
2450 return ret;
2451 }
2452
2453 // give flashlight a chance to close devices if necessary.
2454 mFlashlight->prepareDeviceOpen(cameraId);
2455
Austin Borger18b30a72022-10-27 12:20:29 -07002456 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002457 auto deviceVersionAndTransport =
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002458 getDeviceVersion(cameraId, rotationOverride, /*out*/&portraitRotation,
Austin Borger18b30a72022-10-27 12:20:29 -07002459 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002460 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002461 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002462 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002463 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002464 }
2465
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002466 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002467 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002468 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002469
Austin Borger6e831c42024-07-22 13:07:56 -07002470 // Only use passed in clientPid to check permission. Use calling PID as the client PID
2471 // that's connected to camera service directly.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002472 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002473 clientFeatureId, cameraId, api1CameraId, facing,
Austin Borger7d2b9232024-07-22 14:17:14 -07002474 orientation, getCallingPid(), clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002475 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002476 rotationOverride, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002477 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002478 return ret;
2479 }
2480 client = static_cast<CLIENT*>(tmp.get());
2481
2482 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2483 __FUNCTION__);
2484
Austin Borgered99f642023-06-01 16:51:35 -07002485 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002486 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002487 if (err != OK) {
2488 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002489 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002490 mServiceLock.unlock();
2491 client->disconnect();
2492 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002493 switch(err) {
2494 case BAD_VALUE:
2495 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002496 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002497 case -EBUSY:
2498 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002499 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002500 case -EUSERS:
2501 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2502 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002503 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002504 case PERMISSION_DENIED:
2505 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002506 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002507 case -EACCES:
2508 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002509 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002510 case -ENODEV:
2511 default:
2512 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002513 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002514 strerror(-err), err);
2515 }
2516 }
2517
2518 // Update shim paremeters for legacy clients
2519 if (effectiveApiLevel == API_1) {
2520 // Assume we have always received a Client subclass for API1
2521 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2522 String8 rawParams = shimClient->getParameters();
2523 CameraParameters params(rawParams);
2524
2525 auto cameraState = getCameraState(cameraId);
2526 if (cameraState != nullptr) {
2527 cameraState->setShimParams(params);
2528 } else {
2529 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002530 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002531 }
2532 }
2533
Ravneetaeb20dc2022-03-30 05:33:03 +00002534 // Enable/disable camera service watchdog
2535 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2536
Emilian Peev6d45db82024-01-18 20:11:54 +00002537 CameraMetadata chars;
2538 bool rotateAndCropSupported = true;
2539 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002540 &chars, rotationOverride);
Emilian Peev6d45db82024-01-18 20:11:54 +00002541 if (err == OK) {
2542 auto availableRotateCropEntry = chars.find(
2543 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2544 if (availableRotateCropEntry.count <= 1) {
2545 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002546 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002547 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002548 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2549 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002550 }
2551
Emilian Peev6d45db82024-01-18 20:11:54 +00002552 if (rotateAndCropSupported) {
2553 // Set rotate-and-crop override behavior
2554 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2555 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002556 } else if (rotationOverride != hardware::ICameraService::ROTATION_OVERRIDE_NONE &&
2557 portraitRotation != 0) {
Emilian Peev6d45db82024-01-18 20:11:54 +00002558 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2559 switch (portraitRotation) {
2560 case 90:
2561 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2562 break;
2563 case 180:
2564 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2565 break;
2566 case 270:
2567 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2568 break;
2569 default:
2570 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2571 break;
2572 }
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002573 // Here we're communicating to the client the chosen rotate
2574 // and crop mode to send to the HAL
Emilian Peev6d45db82024-01-18 20:11:54 +00002575 client->setRotateAndCropOverride(rotateAndCropMode);
2576 } else {
2577 client->setRotateAndCropOverride(
2578 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2579 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2580 }
2581 }
2582
2583 bool autoframingSupported = true;
2584 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2585 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2586 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2587 autoframingSupported = false;
2588 }
2589
2590 if (autoframingSupported) {
2591 // Set autoframing override behaviour
2592 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2593 client->setAutoframingOverride(mOverrideAutoframingMode);
2594 } else {
2595 client->setAutoframingOverride(
2596 mCameraServiceProxyWrapper->getAutoframingOverride(
2597 clientPackageName));
2598 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002599 }
2600
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002601 bool isCameraPrivacyEnabled;
2602 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002603 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002604 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
Austin Borger95a00152024-09-23 17:20:24 -07002605 toString16(client->getPackageName()), cameraId, clientPid, clientUid);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002606 } else {
2607 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002608 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002609 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002610
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002611 if (client->supportsCameraMute()) {
2612 client->setCameraMute(
2613 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2614 } else if (isCameraPrivacyEnabled) {
2615 // no camera mute supported, but privacy is on! => disconnect
2616 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2617 client->getPackageName().c_str(), cameraId.c_str());
2618 // Do not hold mServiceLock while disconnecting clients, but
2619 // retain the condition blocking other clients from connecting
2620 // in mServiceLockWrapper if held.
2621 mServiceLock.unlock();
2622 // Clear caller identity temporarily so client disconnect PID
2623 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002624 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002625 // Note AppOp to trigger the "Unblock" dialog
2626 client->noteAppOp();
2627 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002628 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002629 // Reacquire mServiceLock
2630 mServiceLock.lock();
2631
2632 return STATUS_ERROR_FMT(ERROR_DISABLED,
2633 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002634 }
2635
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002636 if (shimUpdateOnly) {
2637 // If only updating legacy shim parameters, immediately disconnect client
2638 mServiceLock.unlock();
2639 client->disconnect();
2640 mServiceLock.lock();
2641 } else {
2642 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002643 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002644 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002645
2646 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002647 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002648 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002649 } // lock is destroyed, allow further connect calls
2650
2651 // Important: release the mutex here so the client can call back into the service from its
2652 // destructor (can be at the end of the call)
2653 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002654
2655 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002656 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002657 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002658
Cliff Wud3a05312021-04-26 23:07:31 +08002659 {
2660 Mutex::Autolock lock(mInjectionParametersLock);
2661 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2662 mInjectionInitPending = false;
2663 status_t res = NO_ERROR;
2664 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2665 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002666 sp<BasicClient> clientSp = clientDescriptor->getValue();
2667 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2668 if(res != OK) {
2669 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2670 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002671 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002672 }
2673 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002674 if (res != OK) {
2675 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2676 }
2677 } else {
2678 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002679 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002680 res = NO_INIT;
2681 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2682 }
2683 }
2684 }
2685
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002686 return ret;
2687}
2688
Austin Borgered99f642023-06-01 16:51:35 -07002689status_t CameraService::addOfflineClient(const std::string &cameraId,
2690 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002691 if (offlineClient.get() == nullptr) {
2692 return BAD_VALUE;
2693 }
2694
2695 {
2696 // Acquire mServiceLock and prevent other clients from connecting
2697 std::unique_ptr<AutoConditionLock> lock =
2698 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2699
2700 if (lock == nullptr) {
2701 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2702 , __FUNCTION__, offlineClient->getClientPid());
2703 return TIMED_OUT;
2704 }
2705
2706 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2707 if (onlineClientDesc.get() == nullptr) {
2708 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2709 cameraId.c_str());
2710 return BAD_VALUE;
2711 }
2712
2713 // Offline clients do not evict or conflict with other online devices. Resource sharing
2714 // conflicts are handled by the camera provider which will either succeed or fail before
2715 // reaching this method.
2716 const auto& onlinePriority = onlineClientDesc->getPriority();
2717 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2718 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002719 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002720 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002721 // native clients don't have offline processing support.
2722 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002723 if (offlineClientDesc == nullptr) {
2724 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2725 return BAD_VALUE;
2726 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002727
2728 // Allow only one offline device per camera
2729 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2730 if (!incompatibleClients.empty()) {
2731 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2732 return BAD_VALUE;
2733 }
2734
Austin Borgered99f642023-06-01 16:51:35 -07002735 std::string monitorTags = isClientWatched(offlineClient.get())
2736 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002737 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002738 if (err != OK) {
2739 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2740 return err;
2741 }
2742
2743 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2744 if (evicted.size() > 0) {
2745 for (auto& i : evicted) {
2746 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002747 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002748 }
2749
2750 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2751 "properly", __FUNCTION__);
2752
2753 return BAD_VALUE;
2754 }
2755
2756 logConnectedOffline(offlineClientDesc->getKey(),
2757 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002758 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002759
2760 sp<IBinder> remoteCallback = offlineClient->getRemote();
2761 if (remoteCallback != nullptr) {
2762 remoteCallback->linkToDeath(this);
2763 }
2764 } // lock is destroyed, allow further connect calls
2765
2766 return OK;
2767}
2768
Austin Borgered99f642023-06-01 16:51:35 -07002769Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002770 int32_t torchStrength, const sp<IBinder>& clientBinder,
2771 const AttributionSourceState& clientAttribution, int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002772 Mutex::Autolock lock(mServiceLock);
2773
2774 ATRACE_CALL();
2775 if (clientBinder == nullptr) {
2776 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2777 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2778 "Torch client binder in null.");
2779 }
2780
Austin Borger22c5c852024-03-08 13:31:36 -08002781 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002782 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2783 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002784 if (!cameraIdOptional.has_value()) {
2785 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002786 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002787 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2788 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2789 }
2790 std::string cameraId = cameraIdOptional.value();
2791
Austin Borgered99f642023-06-01 16:51:35 -07002792 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002793 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002794 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002795 }
2796
2797 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002798 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002799 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002800 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002801 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002802 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002803 }
2804
2805 StatusInternal cameraStatus = state->getStatus();
2806 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2807 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002808 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002809 (int)cameraStatus);
2810 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002811 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002812 }
2813
2814 {
2815 Mutex::Autolock al(mTorchStatusMutex);
2816 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002817 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002818 if (err != OK) {
2819 if (err == NAME_NOT_FOUND) {
2820 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002821 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002822 }
2823 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002824 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002825 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2826 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002827 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002828 }
2829
2830 if (status == TorchModeStatus::NOT_AVAILABLE) {
2831 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2832 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002833 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002834 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2835 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002836 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002837 } else {
2838 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002839 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002840 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2841 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002842 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002843 }
2844 }
2845 }
2846
2847 {
2848 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002849 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002850 }
2851 // Check if the current torch strength level is same as the new one.
2852 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002853 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002854
Austin Borgered99f642023-06-01 16:51:35 -07002855 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002856
2857 if (err != OK) {
2858 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002859 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002860 switch (err) {
2861 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002862 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2863 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002864 errorCode = ERROR_ILLEGAL_ARGUMENT;
2865 break;
2866 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002867 msg = fmt::sprintf("Camera \"%s\" is in use",
2868 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002869 errorCode = ERROR_CAMERA_IN_USE;
2870 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002871 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002872 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002873 "valid range.", torchStrength);
2874 errorCode = ERROR_ILLEGAL_ARGUMENT;
2875 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002876 default:
Austin Borgered99f642023-06-01 16:51:35 -07002877 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002878 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002879 }
Austin Borgered99f642023-06-01 16:51:35 -07002880 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2881 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002882 }
2883
2884 {
2885 // update the link to client's death
2886 // Store the last client that turns on each camera's torch mode.
2887 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002888 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002889 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002890 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002891 } else {
2892 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2893 mTorchClientMap.replaceValueAt(index, clientBinder);
2894 }
2895 clientBinder->linkToDeath(this);
2896 }
2897
Austin Borger22c5c852024-03-08 13:31:36 -08002898 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002899 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002900 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002901 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002902 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002903 }
2904 return Status::ok();
2905}
2906
malikakash73125c62023-07-21 22:44:34 +00002907Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Austin Borger65e64642024-06-11 15:58:23 -07002908 const sp<IBinder>& clientBinder, const AttributionSourceState& clientAttribution,
2909 int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002910 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002911
2912 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002913 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002914 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002915 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2916 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002917 }
2918
Austin Borger22c5c852024-03-08 13:31:36 -08002919 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002920 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2921 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002922 if (!cameraIdOptional.has_value()) {
2923 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002924 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002925 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2926 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2927 }
2928 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002929
Austin Borgered99f642023-06-01 16:51:35 -07002930 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002931 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07002932 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002933 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002934 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07002935 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08002936 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002937 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002938 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002939 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002940 }
2941
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002942 StatusInternal cameraStatus = state->getStatus();
2943 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002944 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07002945 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
2946 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002947 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002948 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002949 }
2950
2951 {
2952 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002953 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002954 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002955 if (err != OK) {
2956 if (err == NAME_NOT_FOUND) {
2957 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002958 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002959 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002960 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002961 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002962 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002963 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002964 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002965 }
2966
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002967 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002968 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002969 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002970 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002971 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2972 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002973 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002974 } else {
2975 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002976 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002977 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2978 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002979 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002980 }
2981 }
2982 }
2983
Ruben Brunk99e69712015-05-26 17:25:07 -07002984 {
2985 // Update UID map - this is used in the torch status changed callbacks, so must be done
2986 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002987 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002988 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07002989 }
2990
Austin Borgered99f642023-06-01 16:51:35 -07002991 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002992
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002993 if (err != OK) {
2994 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002995 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002996 switch (err) {
2997 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002998 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
2999 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003000 errorCode = ERROR_ILLEGAL_ARGUMENT;
3001 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003002 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003003 msg = fmt::sprintf("Camera \"%s\" is in use",
3004 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003005 errorCode = ERROR_CAMERA_IN_USE;
3006 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003007 default:
Austin Borgered99f642023-06-01 16:51:35 -07003008 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003009 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003010 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003011 errorCode = ERROR_INVALID_OPERATION;
3012 }
Austin Borgered99f642023-06-01 16:51:35 -07003013 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3014 logServiceError(msg, errorCode);
3015 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003016 }
3017
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003018 {
3019 // update the link to client's death
3020 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003021 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003022 if (enabled) {
3023 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003024 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003025 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003026 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003027 mTorchClientMap.replaceValueAt(index, clientBinder);
3028 }
3029 clientBinder->linkToDeath(this);
3030 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003031 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003032 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003033 }
3034
Austin Borger22c5c852024-03-08 13:31:36 -08003035 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003036 std::string torchState = enabled ? "on" : "off";
3037 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3038 torchState.c_str(), clientPid);
3039 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003040 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003041}
3042
Austin Borgered99f642023-06-01 16:51:35 -07003043void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3044 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3045 mTorchUidMap[cameraId].first = uid;
3046 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003047 } else {
3048 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003049 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003050 }
3051}
3052
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003053Status CameraService::notifySystemEvent(int32_t eventId,
3054 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003055 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003056 const int selfPid = getpid();
3057
3058 // Permission checks
3059 if (pid != selfPid) {
3060 // Ensure we're being called by system_server, or similar process with
3061 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003062 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003063 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003064 ALOGE("Permission Denial: cannot send updates to camera service about system"
3065 " events from pid=%d, uid=%d", pid, uid);
3066 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003067 "No permission to send updates to camera service about system events"
3068 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003069 }
3070 }
3071
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003072 ATRACE_CALL();
3073
Ruben Brunk36597b22015-03-20 22:15:57 -07003074 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003075 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003076 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003077 // from a system server crash
3078 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003079 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003080 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003081 break;
3082 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003083 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3084 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003085 if (args.size() != 1) {
3086 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3087 "USB Device Event requires 1 argument");
3088 }
3089
Valentin Iftime29e2e152021-08-13 15:17:33 +02003090 // Notify CameraProviderManager for lazy HALs
3091 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3092 std::to_string(args[0]));
3093 break;
3094 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003095 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003096 default: {
3097 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3098 eventId);
3099 break;
3100 }
3101 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003102 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003103}
3104
Emilian Peev53722fa2019-02-22 17:47:20 -08003105void CameraService::notifyMonitoredUids() {
3106 Mutex::Autolock lock(mStatusListenerLock);
3107
3108 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003109 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003110 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3111 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003112 }
3113}
3114
Austin Borgerdddb7552023-03-30 17:53:01 -07003115void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3116 Mutex::Autolock lock(mStatusListenerLock);
3117
3118 for (const auto& it : mListenerList) {
3119 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3120 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3121 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3122 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3123 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3124 }
3125 }
3126}
3127
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003128Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003129 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003130 const int selfPid = getpid();
3131
3132 // Permission checks
3133 if (pid != selfPid) {
3134 // Ensure we're being called by system_server, or similar process with
3135 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003136 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003137 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003138 ALOGE("Permission Denial: cannot send updates to camera service about device"
3139 " state changes from pid=%d, uid=%d", pid, uid);
3140 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3141 "No permission to send updates to camera service about device state"
3142 " changes from pid=%d, uid=%d", pid, uid);
3143 }
3144 }
3145
3146 ATRACE_CALL();
3147
Austin Borger18b30a72022-10-27 12:20:29 -07003148 {
3149 Mutex::Autolock lock(mServiceLock);
3150 mDeviceState = newState;
3151 }
3152
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003153 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003154
3155 return Status::ok();
3156}
3157
Emilian Peev8b64f282021-03-25 16:49:57 -07003158Status CameraService::notifyDisplayConfigurationChange() {
3159 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003160 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003161 const int selfPid = getpid();
3162
3163 // Permission checks
3164 if (callingPid != selfPid) {
3165 // Ensure we're being called by system_server, or similar process with
3166 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003167 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003168 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003169 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3170 " changes from pid=%d, uid=%d", callingPid, uid);
3171 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3172 "No permission to send updates to camera service about orientation"
3173 " changes from pid=%d, uid=%d", callingPid, uid);
3174 }
3175 }
3176
3177 Mutex::Autolock lock(mServiceLock);
3178
3179 // Don't do anything if rotate-and-crop override via cmd is active
3180 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3181
3182 const auto clients = mActiveClientManager.getAll();
3183 for (auto& current : clients) {
3184 if (current != nullptr) {
3185 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003186 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3187 basicClient->setRotateAndCropOverride(
3188 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3189 basicClient->getPackageName(),
3190 basicClient->getCameraFacing(),
3191 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003192 }
3193 }
3194 }
3195
3196 return Status::ok();
3197}
3198
3199Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003200 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3201 ATRACE_CALL();
3202 if (!concurrentCameraIds) {
3203 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3204 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3205 }
3206
3207 if (!mInitialized) {
3208 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003209 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003210 return STATUS_ERROR(ERROR_DISCONNECTED,
3211 "Camera subsystem is not available");
3212 }
3213 // First call into the provider and get the set of concurrent camera
3214 // combinations
3215 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003216 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003217 for (auto &combination : concurrentCameraCombinations) {
Biswarup Pal7d072862024-04-17 15:24:47 +00003218 std::vector<std::pair<std::string, int32_t>> validCombination;
3219 int32_t firstDeviceId = kInvalidDeviceId;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003220 for (auto &cameraId : combination) {
3221 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003222 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003223 if (state == nullptr) {
3224 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3225 continue;
3226 }
3227 StatusInternal status = state->getStatus();
3228 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3229 continue;
3230 }
Austin Borgered99f642023-06-01 16:51:35 -07003231 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003232 continue;
3233 }
Biswarup Pal7d072862024-04-17 15:24:47 +00003234 auto [cameraOwnerDeviceId, mappedCameraId] =
3235 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
3236 if (firstDeviceId == kInvalidDeviceId) {
3237 firstDeviceId = cameraOwnerDeviceId;
3238 } else if (firstDeviceId != cameraOwnerDeviceId) {
3239 // Found an invalid combination which contains cameras with different device id's,
3240 // hence discard it.
3241 validCombination.clear();
3242 break;
3243 }
3244 validCombination.push_back({mappedCameraId, cameraOwnerDeviceId});
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003245 }
3246 if (validCombination.size() != 0) {
3247 concurrentCameraIds->push_back(std::move(validCombination));
3248 }
3249 }
3250 return Status::ok();
3251}
3252
3253Status CameraService::isConcurrentSessionConfigurationSupported(
3254 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Austin Borger65e64642024-06-11 15:58:23 -07003255 int targetSdkVersion, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal7d072862024-04-17 15:24:47 +00003256 /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003257 if (!isSupported) {
3258 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3259 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3260 }
3261
3262 if (!mInitialized) {
3263 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3264 return STATUS_ERROR(ERROR_DISCONNECTED,
3265 "Camera subsystem is not available");
3266 }
3267
Biswarup Pal7d072862024-04-17 15:24:47 +00003268 for (auto cameraIdAndSessionConfiguration : cameraIdsAndSessionConfigurations) {
3269 std::optional<std::string> cameraIdOptional =
Austin Borger65e64642024-06-11 15:58:23 -07003270 resolveCameraId(cameraIdAndSessionConfiguration.mCameraId,
3271 clientAttribution.deviceId, devicePolicy);
Biswarup Pal7d072862024-04-17 15:24:47 +00003272 if (!cameraIdOptional.has_value()) {
3273 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07003274 cameraIdAndSessionConfiguration.mCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal7d072862024-04-17 15:24:47 +00003275 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3276 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3277 }
3278 cameraIdAndSessionConfiguration.mCameraId = cameraIdOptional.value();
3279 }
3280
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003281 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003282 int callingPid = getCallingPid();
3283 int callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003284 bool hasCameraPermission = ((callingPid == getpid()) ||
Biswarup Pal7d072862024-04-17 15:24:47 +00003285 hasPermissionsForCamera(callingPid, callingUid,
3286 devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT
Austin Borger65e64642024-06-11 15:58:23 -07003287 ? kDefaultDeviceId : clientAttribution.deviceId));
Austin Borger249e6592024-03-10 22:28:11 -07003288 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003289 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3290 "android.permission.CAMERA needed to call"
3291 "isConcurrentSessionConfigurationSupported");
3292 }
3293
3294 status_t res =
3295 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003296 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3297 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003298 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003299 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003300 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003301 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3302 "support %s (%d)", strerror(-res), res);
3303 }
3304 return Status::ok();
3305}
3306
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003307Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3308 /*out*/
3309 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003310 return addListenerHelper(listener, cameraStatuses);
3311}
3312
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003313binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3314 std::vector<hardware::CameraStatus>* cameraStatuses) {
3315 return addListenerHelper(listener, cameraStatuses, false, true);
3316}
3317
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003318Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3319 /*out*/
3320 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003321 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003322 ATRACE_CALL();
3323
Igor Murashkinbfc99152013-02-27 12:55:20 -08003324 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003325
Ruben Brunk3450ba72015-06-16 11:00:37 -07003326 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003327 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003328 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003329 }
3330
Austin Borger22c5c852024-03-08 13:31:36 -08003331 auto clientPid = getCallingPid();
3332 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003333 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003334
Igor Murashkinbfc99152013-02-27 12:55:20 -08003335 Mutex::Autolock lock(mServiceLock);
3336
Ruben Brunkcc776712015-02-17 20:18:47 -08003337 {
3338 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003339 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003340 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003341 ALOGW("%s: Tried to add listener %p which was already subscribed",
3342 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003343 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003344 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003345 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003346
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003347 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003348 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3349 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003350 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003351 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003352 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003353 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003354 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3355 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3356 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003357 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003358 // The listener still needs to be added to the list of listeners, regardless of what
3359 // permissions the listener process has / whether it is a vendor listener. Since it might be
3360 // eligible to listen to other camera ids.
3361 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003362 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003363 }
3364
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003365 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003366 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003367 Mutex::Autolock lock(mCameraStatesLock);
3368 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003369 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3370 auto [deviceId, mappedCameraId] =
3371 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3372
3373 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003374 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003375 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3376 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003377 }
3378 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003379 // Remove the camera statuses that should be hidden from the client, we do
3380 // this after collecting the states in order to avoid holding
3381 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3382 // the same time.
3383 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3384 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003385 std::string cameraId = s.cameraId;
3386 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
malikakash98260df2024-05-10 23:33:57 +00003387 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM);
Biswarup Pal37a75182024-01-16 15:53:35 +00003388 if (!cameraIdOptional.has_value()) {
3389 std::string msg =
3390 fmt::sprintf(
3391 "Camera %s: Invalid camera id for device id %d",
3392 s.cameraId.c_str(), s.deviceId);
3393 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3394 return true;
3395 }
3396 cameraId = cameraIdOptional.value();
3397 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3398 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3399 ALOGE("%s: Invalid camera id %s, skipping status update",
3400 __FUNCTION__, s.cameraId.c_str());
3401 return true;
3402 }
3403 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3404 clientUid);
3405 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003406
Biswarup Pal37a75182024-01-16 15:53:35 +00003407 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003408 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003409 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003410 // Add only default device cameras here, as virtual cameras currently don't support torch
3411 // anyway. Note that this is a simplification of the implementation here, and we should
3412 // change this when virtual cameras support torch.
3413 if (s.deviceId == kDefaultDeviceId) {
3414 idsChosenForCallback.insert(s.cameraId);
3415 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003416 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003417
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003418 /*
3419 * Immediately signal current torch status to this listener only
3420 * This may be a subset of all the devices, so don't include it in the response directly
3421 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003422 {
3423 Mutex::Autolock al(mTorchStatusMutex);
3424 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003425 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003426 // The camera id is visible to the client. Fine to send torch
3427 // callback.
3428 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003429 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3430 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003431 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003432 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003433 }
3434
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003435 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003436}
Ruben Brunkcc776712015-02-17 20:18:47 -08003437
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003438Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003439 ATRACE_CALL();
3440
Igor Murashkinbfc99152013-02-27 12:55:20 -08003441 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3442
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003443 if (listener == 0) {
3444 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003445 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003446 }
3447
Igor Murashkinbfc99152013-02-27 12:55:20 -08003448 Mutex::Autolock lock(mServiceLock);
3449
Ruben Brunkcc776712015-02-17 20:18:47 -08003450 {
3451 Mutex::Autolock lock(mStatusListenerLock);
3452 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003453 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003454 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003455 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003456 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003457 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003458 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003459 }
3460 }
3461
3462 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3463 __FUNCTION__, listener.get());
3464
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003465 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003466}
3467
Austin Borgered99f642023-06-01 16:51:35 -07003468Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003469
3470 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003471 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3472
3473 if (parameters == NULL) {
3474 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003475 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003476 }
3477
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003478 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003479
3480 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003481 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003482 // Error logged by caller
3483 return ret;
3484 }
3485
3486 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003487
Austin Borgered99f642023-06-01 16:51:35 -07003488 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003489
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003490 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003491}
3492
malikakash98260df2024-05-10 23:33:57 +00003493Status CameraService::supportsCameraApi(const std::string& cameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003494 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003495 ATRACE_CALL();
3496
Austin Borgered99f642023-06-01 16:51:35 -07003497 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003498
3499 switch (apiVersion) {
3500 case API_VERSION_1:
3501 case API_VERSION_2:
3502 break;
3503 default:
Austin Borgered99f642023-06-01 16:51:35 -07003504 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3505 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3506 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003507 }
3508
Austin Borger18b30a72022-10-27 12:20:29 -07003509 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00003510 auto deviceVersionAndTransport =
3511 getDeviceVersion(cameraId,
3512 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
3513 &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003514 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003515 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3516 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3517 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003518 }
3519 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3520 int deviceVersion = deviceVersionAndTransport.first;
3521 switch (deviceVersion) {
3522 case CAMERA_DEVICE_API_VERSION_1_0:
3523 case CAMERA_DEVICE_API_VERSION_3_0:
3524 case CAMERA_DEVICE_API_VERSION_3_1:
3525 if (apiVersion == API_VERSION_2) {
3526 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003527 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003528 *isSupported = false;
3529 } else { // if (apiVersion == API_VERSION_1) {
3530 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003531 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003532 *isSupported = true;
3533 }
3534 break;
3535 case CAMERA_DEVICE_API_VERSION_3_2:
3536 case CAMERA_DEVICE_API_VERSION_3_3:
3537 case CAMERA_DEVICE_API_VERSION_3_4:
3538 case CAMERA_DEVICE_API_VERSION_3_5:
3539 case CAMERA_DEVICE_API_VERSION_3_6:
3540 case CAMERA_DEVICE_API_VERSION_3_7:
3541 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003542 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003543 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003544 break;
3545 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003546 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3547 deviceVersion, cameraId.c_str());
3548 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3549 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003550 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003551 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003552 } else {
3553 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003554 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003555 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003556}
3557
malikakash98260df2024-05-10 23:33:57 +00003558Status CameraService::isHiddenPhysicalCamera(const std::string& cameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003559 /*out*/ bool *isSupported) {
3560 ATRACE_CALL();
3561
Austin Borgered99f642023-06-01 16:51:35 -07003562 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3563 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003564
3565 return Status::ok();
3566}
3567
Cliff Wud8cae102021-03-11 01:37:42 +08003568Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003569 const std::string& packageName, const std::string& internalCamId,
3570 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003571 const sp<ICameraInjectionCallback>& callback,
3572 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003573 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003574 ATRACE_CALL();
3575
Austin Borgered99f642023-06-01 16:51:35 -07003576 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003577 const int pid = getCallingPid();
3578 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003579 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3580 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003581 "Permission Denial: no permission to inject camera");
3582 }
3583
3584 // Do not allow any camera injection that injects or replaces a virtual camera.
3585 auto [deviceIdForInternalCamera, _] =
3586 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3587 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3588 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3589 "Cannot replace a virtual camera");
3590 }
3591 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3592 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3593 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3594 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3595 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003596 }
3597
3598 ALOGV(
3599 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3600 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003601 __FUNCTION__, packageName.c_str(),
3602 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003603
Cliff Wud3a05312021-04-26 23:07:31 +08003604 {
3605 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003606 mInjectionInternalCamId = internalCamId;
3607 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003608 mInjectionStatusListener->addListener(callback);
3609 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003610 status_t res = NO_ERROR;
3611 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3612 // If the client already exists, we can directly connect to the camera device through the
3613 // client's injectCamera(), otherwise we need to wait until the client is established
3614 // (execute connectHelper()) before injecting the camera to the camera device.
3615 if (clientDescriptor != nullptr) {
3616 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003617 sp<BasicClient> clientSp = clientDescriptor->getValue();
3618 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3619 if(res != OK) {
3620 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3621 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003622 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003623 }
3624 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003625 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003626 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3627 }
3628 } else {
3629 mInjectionInitPending = true;
3630 }
3631 }
Cliff Wud8cae102021-03-11 01:37:42 +08003632
Cliff Wud3a05312021-04-26 23:07:31 +08003633 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003634}
3635
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003636Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003637 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003638 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3639 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3640 return Status::ok();
3641}
3642
Ruben Brunkcc776712015-02-17 20:18:47 -08003643void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003644 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003645 for (auto& i : mActiveClientManager.getAll()) {
3646 auto clientSp = i->getValue();
3647 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003648 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003649 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003650 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003651 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003652 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003653}
3654
Ruben Brunkcc776712015-02-17 20:18:47 -08003655bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003656 bool ret = false;
3657 {
3658 // Acquire mServiceLock and prevent other clients from connecting
3659 std::unique_ptr<AutoConditionLock> lock =
3660 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003661
Ruben Brunkcc776712015-02-17 20:18:47 -08003662 std::vector<sp<BasicClient>> evicted;
3663 for (auto& i : mActiveClientManager.getAll()) {
3664 auto clientSp = i->getValue();
3665 if (clientSp.get() == nullptr) {
3666 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3667 mActiveClientManager.remove(i);
3668 continue;
3669 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003670 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003671 mActiveClientManager.remove(i);
3672 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003673
Ruben Brunkcc776712015-02-17 20:18:47 -08003674 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003675 clientSp->notifyError(
3676 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003677 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003678 }
3679 }
3680
Ruben Brunkcc776712015-02-17 20:18:47 -08003681 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3682 // other clients from connecting in mServiceLockWrapper if held
3683 mServiceLock.unlock();
3684
Ruben Brunk36597b22015-03-20 22:15:57 -07003685 // Do not clear caller identity, remote caller should be client proccess
3686
Ruben Brunkcc776712015-02-17 20:18:47 -08003687 for (auto& i : evicted) {
3688 if (i.get() != nullptr) {
3689 i->disconnect();
3690 ret = true;
3691 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003692 }
3693
Ruben Brunkcc776712015-02-17 20:18:47 -08003694 // Reacquire mServiceLock
3695 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003696
Ruben Brunkcc776712015-02-17 20:18:47 -08003697 } // lock is destroyed, allow further connect calls
3698
3699 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003700}
3701
Ruben Brunkcc776712015-02-17 20:18:47 -08003702std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003703 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003704 std::shared_ptr<CameraState> state;
3705 {
3706 Mutex::Autolock lock(mCameraStatesLock);
3707 auto iter = mCameraStates.find(cameraId);
3708 if (iter != mCameraStates.end()) {
3709 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003710 }
3711 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003712 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003713}
3714
Austin Borgered99f642023-06-01 16:51:35 -07003715sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003716 // Remove from active clients list
3717 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3718 if (clientDescriptorPtr == nullptr) {
3719 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003720 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003721 return sp<BasicClient>{nullptr};
3722 }
3723
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003724 sp<BasicClient> client = clientDescriptorPtr->getValue();
3725 if (client.get() != nullptr) {
3726 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3727 }
3728 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003729}
3730
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003731void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003732 // Acquire mServiceLock and prevent other clients from connecting
3733 std::unique_ptr<AutoConditionLock> lock =
3734 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3735
Ruben Brunk6267b532015-04-30 17:44:07 -07003736 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003737 for (size_t i = 0; i < newUserIds.size(); i++) {
3738 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003739 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003740 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003741 return;
3742 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003743 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003744 }
3745
Ruben Brunka8ca9152015-04-07 14:23:40 -07003746
Ruben Brunk6267b532015-04-30 17:44:07 -07003747 if (newAllowedUsers == mAllowedUsers) {
3748 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3749 return;
3750 }
3751
3752 logUserSwitch(mAllowedUsers, newAllowedUsers);
3753
3754 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003755
3756 // Current user has switched, evict all current clients.
3757 std::vector<sp<BasicClient>> evicted;
3758 for (auto& i : mActiveClientManager.getAll()) {
3759 auto clientSp = i->getValue();
3760
3761 if (clientSp.get() == nullptr) {
3762 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3763 continue;
3764 }
3765
Ruben Brunk6267b532015-04-30 17:44:07 -07003766 // Don't evict clients that are still allowed.
3767 uid_t clientUid = clientSp->getClientUid();
3768 userid_t clientUserId = multiuser_get_user_id(clientUid);
3769 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3770 continue;
3771 }
3772
Ruben Brunk36597b22015-03-20 22:15:57 -07003773 evicted.push_back(clientSp);
3774
Ruben Brunk36597b22015-03-20 22:15:57 -07003775 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003776 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003777
Ruben Brunk36597b22015-03-20 22:15:57 -07003778 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003779 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003780 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003781 " to user switch.", i->getKey().c_str(),
3782 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003783 i->getOwnerId(), i->getPriority().getScore(),
3784 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003785
3786 }
3787
3788 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3789 // blocking other clients from connecting in mServiceLockWrapper if held.
3790 mServiceLock.unlock();
3791
3792 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08003793 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003794
3795 for (auto& i : evicted) {
3796 i->disconnect();
3797 }
3798
Austin Borger22c5c852024-03-08 13:31:36 -08003799 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003800
3801 // Reacquire mServiceLock
3802 mServiceLock.lock();
3803}
Ruben Brunkcc776712015-02-17 20:18:47 -08003804
Austin Borgered99f642023-06-01 16:51:35 -07003805void CameraService::logEvent(const std::string &event) {
3806 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003807 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003808 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003809 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003810 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003811 mEventLog.add(msg);
3812 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3813 // Error event not added to the dumpsys log before
3814 mEventLog.add(msg);
3815 sServiceErrorEventSet.insert(msg);
3816 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003817}
3818
Austin Borgered99f642023-06-01 16:51:35 -07003819void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3820 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003821 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003822 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3823 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003824}
3825
Austin Borgered99f642023-06-01 16:51:35 -07003826void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3827 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003828 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003829 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3830 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003831}
3832
Austin Borgered99f642023-06-01 16:51:35 -07003833void CameraService::logConnected(const std::string &cameraId, int clientPid,
3834 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003835 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003836 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3837 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003838}
3839
Austin Borgered99f642023-06-01 16:51:35 -07003840void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3841 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003842 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003843 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3844 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003845}
3846
Austin Borgered99f642023-06-01 16:51:35 -07003847void CameraService::logRejected(const std::string &cameraId, int clientPid,
3848 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003849 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003850 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3851 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003852}
3853
Austin Borgered99f642023-06-01 16:51:35 -07003854void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3855 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003856 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003857 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3858 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003859}
3860
Ruben Brunk6267b532015-04-30 17:44:07 -07003861void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3862 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003863 std::string newUsers = toString(newUserIds);
3864 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003865 if (oldUsers.size() == 0) {
3866 oldUsers = "<None>";
3867 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003868 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003869 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3870 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003871}
3872
Austin Borgered99f642023-06-01 16:51:35 -07003873void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003874 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003875 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003876}
3877
Austin Borgered99f642023-06-01 16:51:35 -07003878void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003879 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003880 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003881}
3882
Austin Borgered99f642023-06-01 16:51:35 -07003883void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003884 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003885 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003886}
3887
Austin Borgered99f642023-06-01 16:51:35 -07003888void CameraService::logServiceError(const std::string &msg, int errorCode) {
3889 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3890 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003891}
3892
Ruben Brunk36597b22015-03-20 22:15:57 -07003893status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3894 uint32_t flags) {
3895
Mathias Agopian65ab4712010-07-14 17:59:35 -07003896 // Permission checks
3897 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003898 case SHELL_COMMAND_TRANSACTION: {
3899 int in = data.readFileDescriptor();
3900 int out = data.readFileDescriptor();
3901 int err = data.readFileDescriptor();
3902 int argc = data.readInt32();
3903 Vector<String16> args;
3904 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3905 args.add(data.readString16());
3906 }
3907 sp<IBinder> unusedCallback;
3908 sp<IResultReceiver> resultReceiver;
3909 status_t status;
3910 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3911 return status;
3912 }
3913 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3914 return status;
3915 }
3916 status = shellCommand(in, out, err, args);
3917 if (resultReceiver != nullptr) {
3918 resultReceiver->send(status);
3919 }
3920 return NO_ERROR;
3921 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003922 }
3923
3924 return BnCameraService::onTransact(code, data, reply, flags);
3925}
3926
Mathias Agopian65ab4712010-07-14 17:59:35 -07003927// We share the media players for shutter and recording sound for all clients.
3928// A reference count is kept to determine when we will actually release the
3929// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09003930sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3931 sp<MediaPlayer> mp = new MediaPlayer();
3932 status_t error;
3933 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003934 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003935 error = mp->prepare();
3936 }
3937 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003938 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003939 mp->disconnect();
3940 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003941 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003942 }
3943 return mp;
3944}
3945
username5755fea2018-12-27 09:48:08 +08003946void CameraService::increaseSoundRef() {
3947 Mutex::Autolock lock(mSoundLock);
3948 mSoundRef++;
3949}
3950
3951void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003952 ATRACE_CALL();
3953
username5755fea2018-12-27 09:48:08 +08003954 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3955 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3956 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3957 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3958 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3959 }
3960 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3961 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3962 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3963 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003964 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003965 }
3966 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3967 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3968 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3969 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3970 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003971 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003972}
3973
username5755fea2018-12-27 09:48:08 +08003974void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003975 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003976 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003977 if (--mSoundRef) return;
3978
3979 for (int i = 0; i < NUM_SOUNDS; i++) {
3980 if (mSoundPlayer[i] != 0) {
3981 mSoundPlayer[i]->disconnect();
3982 mSoundPlayer[i].clear();
3983 }
3984 }
3985}
3986
3987void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003988 ATRACE_CALL();
3989
Mathias Agopian65ab4712010-07-14 17:59:35 -07003990 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07003991 if (kind < 0 || kind >= NUM_SOUNDS) {
3992 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
3993 return;
3994 }
3995
Mathias Agopian65ab4712010-07-14 17:59:35 -07003996 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003997 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003998 sp<MediaPlayer> player = mSoundPlayer[kind];
3999 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004000 player->seekTo(0);
4001 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004002 }
4003}
4004
4005// ----------------------------------------------------------------------------
4006
4007CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004008 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004009 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004010 const std::string& clientPackageName, bool systemNativeClient,
4011 const std::optional<std::string>& clientFeatureId,
4012 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004013 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004014 int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004015 int servicePid, int rotationOverride) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004016 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004017 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07004018 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004019 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004020 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004021 clientPid, clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004022 servicePid, rotationOverride),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004023 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004024{
Austin Borger22c5c852024-03-08 13:31:36 -08004025 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004026 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004027
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004028 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004029
username5755fea2018-12-27 09:48:08 +08004030 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004031
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004032 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004033}
4034
Mathias Agopian65ab4712010-07-14 17:59:35 -07004035// tear down the client
4036CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004037 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004038 mDestructionStarted = true;
4039
username5755fea2018-12-27 09:48:08 +08004040 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004041 // unconditionally disconnect. function is idempotent
4042 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004043}
4044
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004045sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4046
Igor Murashkin634a5152013-02-20 17:15:11 -08004047CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004048 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004049 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004050 const std::string& clientPackageName, bool nativeClient,
4051 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004052 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004053 int servicePid, int rotationOverride):
Austin Borger249e6592024-03-10 22:28:11 -07004054 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004055 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004056 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004057 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4058 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004059 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004060 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004061 mDisconnected(false), mUidIsTrusted(false),
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004062 mRotationOverride(rotationOverride),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004063 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004064 mRemoteBinder(remoteCallback),
4065 mOpsActive(false),
4066 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004067{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004068 if (sCameraService == nullptr) {
4069 sCameraService = cameraService;
4070 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004071
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004072 // There are 2 scenarios in which a client won't have AppOps operations
4073 // (both scenarios : native clients)
4074 // 1) It's an system native client*, the package name will be empty
4075 // and it will return from this function in the previous if condition
4076 // (This is the same as the previously existing behavior).
4077 // 2) It is a system native client, but its package name has been
4078 // modified for debugging, however it still must not use AppOps since
4079 // the package name is not a real one.
4080 //
4081 // * system native client - native client with UID < AID_APP_START. It
4082 // doesn't exclude clients not on the system partition.
4083 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004084 mAppOpsManager = std::make_unique<AppOpsManager>();
4085 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004086
Charles Chenf075f082024-03-04 23:32:55 +00004087 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004088}
4089
4090CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004091 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004092 mDestructionStarted = true;
4093}
4094
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004095binder::Status CameraService::BasicClient::disconnect() {
4096 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004097 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004098 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004099 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004100 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004101
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004102 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004103 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004104 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004105 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004106
4107 sp<IBinder> remote = getRemote();
4108 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004109 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004110 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004111
4112 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004113 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004114 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004115 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004116 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004117
Igor Murashkincba2c162013-03-20 15:56:31 -07004118 // client shouldn't be able to call into us anymore
4119 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004120
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004121 const auto& mActivityManager = getActivityManager();
4122 if (mActivityManager) {
4123 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004124 getCallingUid(),
4125 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004126 }
4127
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004128 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004129}
4130
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004131status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4132 // No dumping of clients directly over Binder,
4133 // must go through CameraService::dump
4134 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004135 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004136 return OK;
4137}
4138
Austin Borgered99f642023-06-01 16:51:35 -07004139status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004140 // Can't watch tags directly, must go through CameraService::startWatchingTags
4141 return OK;
4142}
4143
4144status_t CameraService::BasicClient::stopWatchingTags(int) {
4145 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4146 return OK;
4147}
4148
4149status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4150 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4151 return OK;
4152}
4153
Austin Borgered99f642023-06-01 16:51:35 -07004154std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004155 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004156}
4157
Emilian Peev8b64f282021-03-25 16:49:57 -07004158int CameraService::BasicClient::getCameraFacing() const {
4159 return mCameraFacing;
4160}
4161
4162int CameraService::BasicClient::getCameraOrientation() const {
4163 return mOrientation;
4164}
Ruben Brunkcc776712015-02-17 20:18:47 -08004165
4166int CameraService::BasicClient::getClientPid() const {
4167 return mClientPid;
4168}
4169
Ruben Brunk6267b532015-04-30 17:44:07 -07004170uid_t CameraService::BasicClient::getClientUid() const {
4171 return mClientUid;
4172}
4173
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004174bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4175 // Defaults to API2.
4176 return level == API_2;
4177}
4178
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004179status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004180 {
4181 Mutex::Autolock l(mAudioRestrictionLock);
4182 mAudioRestriction = mode;
4183 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004184 sCameraService->updateAudioRestriction();
4185 return OK;
4186}
4187
4188int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004189 return sCameraService->updateAudioRestriction();
4190}
4191
4192int32_t CameraService::BasicClient::getAudioRestriction() const {
4193 Mutex::Autolock l(mAudioRestrictionLock);
4194 return mAudioRestriction;
4195}
4196
4197bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4198 switch (mode) {
4199 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4200 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4201 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4202 return true;
4203 default:
4204 return false;
4205 }
4206}
4207
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004208status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4209 if (mode == AppOpsManager::MODE_ERRORED) {
4210 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004211 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004212 return PERMISSION_DENIED;
4213 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4214 // If the calling Uid is trusted (a native service), the AppOpsManager could
4215 // return MODE_IGNORED. Do not treat such case as error.
4216 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4217 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004218
4219 bool isCameraPrivacyEnabled;
4220 if (flags::camera_privacy_allowlist()) {
4221 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4222 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4223 } else {
4224 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004225 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004226 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004227 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4228 // We prefer to successfully open the camera and perform camera muting
4229 // or blocking in connectHelper as handleAppOpMode can be called before the
4230 // connection has been fully established and at that time camera muting
4231 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004232 if (!isUidActive || !isCameraPrivacyEnabled) {
Austin Borgerfd05d982024-04-22 15:54:50 -07004233 ALOGI("Camera %s: Access for \"%s\" has been restricted."
4234 "uid active: %s, privacy enabled: %s", mCameraIdStr.c_str(),
4235 mClientPackageName.c_str(), isUidActive ? "true" : "false",
4236 isCameraPrivacyEnabled ? "true" : "false");
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004237 // Return the same error as for device policy manager rejection
4238 return -EACCES;
4239 }
4240 }
4241 return OK;
4242}
4243
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004244status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004245 ATRACE_CALL();
4246
Igor Murashkine6800ce2013-03-04 17:25:57 -08004247 {
4248 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004249 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004250 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004251 if (mAppOpsManager != nullptr) {
4252 // Notify app ops that the camera is not available
4253 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004254
Austin Borger5755d9b2024-09-09 11:15:44 -07004255 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4256 toString16(mClientPackageName),
4257 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004258
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004259 // Just check for camera acccess here on open - delay startOp until
4260 // camera frames start streaming in startCameraStreamingOps
4261 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004262 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004263 status_t res = handleAppOpMode(mode);
4264 if (res != OK) {
4265 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004266 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004267 }
4268
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004269 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004270
4271 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004272 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004273
Austin Borgerdddb7552023-03-30 17:53:01 -07004274 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004275
Shuzhen Wang695044d2020-03-06 09:02:23 -08004276 // Notify listeners of camera open/close status
4277 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4278
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004279 return OK;
4280}
4281
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004282status_t CameraService::BasicClient::startCameraStreamingOps() {
4283 ATRACE_CALL();
4284
4285 if (!mOpsActive) {
4286 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4287 return INVALID_OPERATION;
4288 }
4289 if (mOpsStreaming) {
4290 ALOGV("%s: Streaming already active!", __FUNCTION__);
4291 return OK;
4292 }
4293
4294 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004295 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004296
4297 if (mAppOpsManager != nullptr) {
4298 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004299 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4300 toString16(mClientFeatureId),
4301 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004302 status_t res = handleAppOpMode(mode);
4303 if (res != OK) {
4304 return res;
4305 }
4306 }
4307
4308 mOpsStreaming = true;
4309
4310 return OK;
4311}
4312
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004313status_t CameraService::BasicClient::noteAppOp() {
4314 ATRACE_CALL();
4315
4316 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004317 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004318
4319 // noteAppOp is only used for when camera mute is not supported, in order
4320 // to trigger the sensor privacy "Unblock" dialog
4321 if (mAppOpsManager != nullptr) {
4322 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004323 toString16(mClientPackageName), toString16(mClientFeatureId),
4324 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004325 status_t res = handleAppOpMode(mode);
4326 if (res != OK) {
4327 return res;
4328 }
4329 }
4330
4331 return OK;
4332}
4333
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004334status_t CameraService::BasicClient::finishCameraStreamingOps() {
4335 ATRACE_CALL();
4336
4337 if (!mOpsActive) {
4338 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4339 return INVALID_OPERATION;
4340 }
4341 if (!mOpsStreaming) {
4342 ALOGV("%s: Streaming not active!", __FUNCTION__);
4343 return OK;
4344 }
4345
4346 if (mAppOpsManager != nullptr) {
4347 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004348 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004349 mOpsStreaming = false;
4350 }
4351
4352 return OK;
4353}
4354
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004355status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004356 ATRACE_CALL();
4357
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004358 if (mOpsStreaming) {
4359 // Make sure we've notified everyone about camera stopping
4360 finishCameraStreamingOps();
4361 }
4362
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004363 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004364 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004365 mOpsActive = false;
4366
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004367 // This function is called when a client disconnects. This should
4368 // release the camera, but actually only if it was in a proper
4369 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004370 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004371 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004372
Ruben Brunkcc776712015-02-17 20:18:47 -08004373 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004374 sCameraService->updateStatus(StatusInternal::PRESENT,
4375 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004376 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004377 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004378 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4379 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004380 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004381 mOpsCallback.clear();
4382
Austin Borgerdddb7552023-03-30 17:53:01 -07004383 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004384
Shuzhen Wang695044d2020-03-06 09:02:23 -08004385 // Notify listeners of camera open/close status
4386 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4387
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004388 return OK;
4389}
4390
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004391void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004392 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004393 if (mAppOpsManager == nullptr) {
4394 return;
4395 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004396 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004397 if (op != AppOpsManager::OP_CAMERA) {
4398 ALOGW("Unexpected app ops notification received: %d", op);
4399 return;
4400 }
4401
4402 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004403 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004404 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004405 ALOGV("checkOp returns: %d, %s ", res,
4406 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4407 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4408 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4409 "UNKNOWN");
4410
Shuzhen Wang64900852021-02-05 09:03:29 -08004411 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004412 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4413 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004414 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004415 } else if (res == AppOpsManager::MODE_IGNORED) {
4416 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004417
Austin Borgerca1e0062023-06-28 11:32:55 -07004418 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4419 // If not visible, but still active, then we want to block instead of muting the camera.
4420 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4421 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4422
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004423 bool isCameraPrivacyEnabled;
4424 if (flags::camera_privacy_allowlist()) {
4425 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4426 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4427 } else {
4428 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004429 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004430 }
4431
4432 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004433 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4434 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4435 isCameraPrivacyEnabled);
4436 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4437 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4438 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004439 if (!mUidIsTrusted) {
Austin Borger5755d9b2024-09-09 11:15:44 -07004440 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4441 setCameraMute(true);
Austin Borgerca1e0062023-06-28 11:32:55 -07004442 } else {
Austin Borger5755d9b2024-09-09 11:15:44 -07004443 block();
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004444 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004445 }
Evan Severson09ab4002021-02-10 14:15:19 -08004446 } else if (res == AppOpsManager::MODE_ALLOWED) {
4447 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004448 }
4449}
4450
Svet Ganova453d0d2018-01-11 15:37:58 -08004451void CameraService::BasicClient::block() {
4452 ATRACE_CALL();
4453
4454 // Reset the client PID to allow server-initiated disconnect,
4455 // and to prevent further calls by client.
Austin Borger22c5c852024-03-08 13:31:36 -08004456 mClientPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004457 CaptureResultExtras resultExtras; // a dummy result (invalid)
4458 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4459 disconnect();
4460}
4461
Mathias Agopian65ab4712010-07-14 17:59:35 -07004462// ----------------------------------------------------------------------------
4463
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004464void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004465 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004466 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004467 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4468 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4469 api1ErrorCode = CAMERA_ERROR_DISABLED;
4470 }
4471 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004472 } else {
4473 ALOGE("mRemoteCallback is NULL!!");
4474 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004475}
4476
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004477// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004478binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004479 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004480 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004481}
4482
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004483bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4484 return level == API_1;
4485}
4486
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004487CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4488 mClient(client) {
4489}
4490
4491void CameraService::Client::OpsCallback::opChanged(int32_t op,
4492 const String16& packageName) {
4493 sp<BasicClient> client = mClient.promote();
4494 if (client != NULL) {
4495 client->opChanged(op, packageName);
4496 }
4497}
4498
Mathias Agopian65ab4712010-07-14 17:59:35 -07004499// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004500// UidPolicy
4501// ----------------------------------------------------------------------------
4502
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004503void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004504 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004505 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004506
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004507 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004508 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004509 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004510 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004511 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4512 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004513 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004514 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004515 if (res == OK) {
4516 mRegistered = true;
4517 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004518 } else {
4519 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004520 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004521}
4522
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004523void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004524 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004525 return;
4526 }
4527
4528 registerWithActivityManager();
4529}
4530
4531void CameraService::UidPolicy::registerSelf() {
4532 // Use check service to see if the activity service is available
4533 // If not available then register for notifications, instead of blocking
4534 // till the service is ready
4535 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004536 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004537 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004538 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004539 } else {
4540 registerWithActivityManager();
4541 }
4542}
4543
Svet Ganova453d0d2018-01-11 15:37:58 -08004544void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004545 Mutex::Autolock _l(mUidLock);
4546
Steven Moreland2f348142019-07-02 15:59:07 -07004547 mAm.unregisterUidObserver(this);
4548 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004549 mRegistered = false;
4550 mActiveUids.clear();
4551 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004552}
4553
4554void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4555 onUidIdle(uid, disabled);
4556}
4557
4558void CameraService::UidPolicy::onUidActive(uid_t uid) {
4559 Mutex::Autolock _l(mUidLock);
4560 mActiveUids.insert(uid);
4561}
4562
4563void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4564 bool deleted = false;
4565 {
4566 Mutex::Autolock _l(mUidLock);
4567 if (mActiveUids.erase(uid) > 0) {
4568 deleted = true;
4569 }
4570 }
4571 if (deleted) {
4572 sp<CameraService> service = mService.promote();
4573 if (service != nullptr) {
4574 service->blockClientsForUid(uid);
4575 }
4576 }
4577}
4578
Emilian Peev53722fa2019-02-22 17:47:20 -08004579void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004580 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004581 bool procStateChange = false;
4582 {
4583 Mutex::Autolock _l(mUidLock);
4584 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4585 mMonitoredUids[uid].procState != procState) {
4586 mMonitoredUids[uid].procState = procState;
4587 procStateChange = true;
4588 }
4589 }
4590
4591 if (procStateChange) {
4592 sp<CameraService> service = mService.promote();
4593 if (service != nullptr) {
4594 service->notifyMonitoredUids();
4595 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004596 }
4597}
4598
Austin Borgerdddb7552023-03-30 17:53:01 -07004599/**
4600 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4601 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4602 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4603 * monitoredUids. If it is revised above some other monitoredUid, signal
4604 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4605 * foreground apps in split screen - state changes will capture all other cases.
4606 */
4607void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4608 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004609 {
4610 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004611 auto it = mMonitoredUids.find(uid);
4612
4613 if (it != mMonitoredUids.end()) {
4614 if (it->second.hasCamera) {
4615 for (auto &monitoredUid : mMonitoredUids) {
4616 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004617 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004618 notifyUidSet.emplace(monitoredUid.first);
4619 }
4620 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004621 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004622 notifyUidSet.emplace(uid);
4623 } else {
4624 for (auto &monitoredUid : mMonitoredUids) {
4625 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004626 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004627 notifyUidSet.emplace(uid);
4628 }
4629 }
4630 }
4631 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004632 }
4633 }
4634
Austin Borgerdddb7552023-03-30 17:53:01 -07004635 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004636 sp<CameraService> service = mService.promote();
4637 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004638 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004639 }
4640 }
4641}
4642
Austin Borgerdddb7552023-03-30 17:53:01 -07004643/**
4644 * Register a uid for monitoring, and note whether it owns a camera.
4645 */
4646void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004647 Mutex::Autolock _l(mUidLock);
4648 auto it = mMonitoredUids.find(uid);
4649 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004650 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004651 } else {
Austin Borger65577682022-02-17 00:25:43 +00004652 MonitoredUid monitoredUid;
4653 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004654 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004655 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004656 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004657 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004658 if (res != OK) {
4659 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4660 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004661 }
4662
4663 if (openCamera) {
4664 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004665 }
4666}
4667
Austin Borgerdddb7552023-03-30 17:53:01 -07004668/**
4669 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4670 */
4671void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004672 Mutex::Autolock _l(mUidLock);
4673 auto it = mMonitoredUids.find(uid);
4674 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004675 it->second.refCount--;
4676 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004677 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004678 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004679 if (res != OK) {
4680 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4681 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004682 } else if (closeCamera) {
4683 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004684 }
4685 } else {
4686 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4687 }
4688}
4689
Austin Borgered99f642023-06-01 16:51:35 -07004690bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004691 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004692 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004693}
4694
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004695static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4696static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004697
Austin Borgered99f642023-06-01 16:51:35 -07004698bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004699 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004700 // If activity manager is unreachable, assume everything is active
4701 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004702 return true;
4703 }
4704 auto it = mOverrideUids.find(uid);
4705 if (it != mOverrideUids.end()) {
4706 return it->second;
4707 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004708 bool active = mActiveUids.find(uid) != mActiveUids.end();
4709 if (!active) {
4710 // We want active UIDs to always access camera with their first attempt since
4711 // there is no guarantee the app is robustly written and would retry getting
4712 // the camera on failure. The inverse case is not a problem as we would take
4713 // camera away soon once we get the callback that the uid is no longer active.
4714 ActivityManager am;
4715 // Okay to access with a lock held as UID changes are dispatched without
4716 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004717 int64_t startTimeMillis = 0;
4718 do {
4719 // TODO: Fix this b/109950150!
4720 // Okay this is a hack. There is a race between the UID turning active and
4721 // activity being resumed. The proper fix is very risky, so we temporary add
4722 // some polling which should happen pretty rarely anyway as the race is hard
4723 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004724 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004725 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004726 if (active) {
4727 break;
4728 }
4729 if (startTimeMillis <= 0) {
4730 startTimeMillis = uptimeMillis();
4731 }
4732 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004733 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004734 if (remainingTimeMillis <= 0) {
4735 break;
4736 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004737 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4738
4739 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004740 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004741 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004742 } while (true);
4743
Svet Ganov7b4ab782018-03-25 12:48:10 -07004744 if (active) {
4745 // Now that we found out the UID is actually active, cache that
4746 mActiveUids.insert(uid);
4747 }
4748 }
4749 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004750}
4751
Varun Shahb42f1eb2019-04-16 14:45:13 -07004752int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4753 Mutex::Autolock _l(mUidLock);
4754 return getProcStateLocked(uid);
4755}
4756
4757int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4758 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4759 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004760 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004761 }
4762 return procState;
4763}
4764
Austin Borgered99f642023-06-01 16:51:35 -07004765void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4766 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004767 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004768}
4769
Austin Borgered99f642023-06-01 16:51:35 -07004770void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004771 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004772}
4773
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004774void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4775 Mutex::Autolock _l(mUidLock);
4776 ALOGV("UidPolicy: ActivityManager has died");
4777 mRegistered = false;
4778 mActiveUids.clear();
4779}
4780
Austin Borgered99f642023-06-01 16:51:35 -07004781void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004782 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004783 bool wasActive = false;
4784 bool isActive = false;
4785 {
4786 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004787 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004788 mOverrideUids.erase(uid);
4789 if (insert) {
4790 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4791 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004792 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004793 }
4794 if (wasActive != isActive && !isActive) {
4795 sp<CameraService> service = mService.promote();
4796 if (service != nullptr) {
4797 service->blockClientsForUid(uid);
4798 }
4799 }
4800}
4801
4802// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004803// SensorPrivacyPolicy
4804// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004805
4806void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4807{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004808 Mutex::Autolock _l(mSensorPrivacyLock);
4809 if (mRegistered) {
4810 return;
4811 }
Evan Severson09ab4002021-02-10 14:15:19 -08004812 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004813 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004814 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004815 mSpm.addToggleSensorPrivacyListener(this);
4816 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004817 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004818 if (flags::camera_privacy_allowlist()) {
4819 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
4820 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
4821 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4822 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004823 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004824 if (res == OK) {
4825 mRegistered = true;
4826 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4827 }
4828}
4829
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004830void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4831 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004832 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004833 return;
4834 }
4835
4836 registerWithSensorPrivacyManager();
4837}
4838
4839void CameraService::SensorPrivacyPolicy::registerSelf() {
4840 // Use checkservice to see if the sensor_privacy service is available
4841 // If service is not available then register for notification
4842 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004843 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004844 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004845 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004846 } else {
4847 registerWithSensorPrivacyManager();
4848 }
4849}
4850
Michael Grooverd1d435a2018-12-18 17:39:42 -08004851void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4852 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004853 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004854 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004855 mSpm.removeToggleSensorPrivacyListener(this);
4856 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004857 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004858 mRegistered = false;
4859 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4860}
4861
4862bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004863 if (!mRegistered) {
4864 registerWithSensorPrivacyManager();
4865 }
4866
Michael Grooverd1d435a2018-12-18 17:39:42 -08004867 Mutex::Autolock _l(mSensorPrivacyLock);
4868 return mSensorPrivacyEnabled;
4869}
4870
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004871int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
4872 if (!mRegistered) {
4873 registerWithSensorPrivacyManager();
4874 }
4875
4876 Mutex::Autolock _l(mSensorPrivacyLock);
4877 return mCameraPrivacyState;
4878}
4879
Evan Seversond0b69922022-01-27 10:47:34 -08004880bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004881 if (!hasCameraPrivacyFeature()) {
4882 return false;
4883 }
Evan Seversond0b69922022-01-27 10:47:34 -08004884 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004885}
4886
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004887bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
4888 if (!hasCameraPrivacyFeature()) {
Jyoti Bhayana5882b032024-04-26 11:18:58 -07004889 return false;
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004890 }
4891 return mSpm.isCameraPrivacyEnabled(packageName);
4892}
4893
Evan Seversond0b69922022-01-27 10:47:34 -08004894binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004895 int toggleType, int sensor, bool enabled) {
4896 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
4897 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
4898 {
4899 Mutex::Autolock _l(mSensorPrivacyLock);
4900 mSensorPrivacyEnabled = enabled;
4901 }
4902 // if sensor privacy is enabled then block all clients from accessing the camera
4903 if (enabled) {
4904 sp<CameraService> service = mService.promote();
4905 if (service != nullptr) {
4906 service->blockAllClients();
4907 }
4908 }
4909 }
4910 return binder::Status::ok();
4911}
4912
4913binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
4914 int, int sensor, int state) {
4915 if (!flags::camera_privacy_allowlist()
4916 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
4917 return binder::Status::ok();
4918 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08004919 {
4920 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004921 mCameraPrivacyState = state;
4922 }
4923 sp<CameraService> service = mService.promote();
4924 if (!service) {
4925 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004926 }
4927 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004928 if (state == SensorPrivacyManager::ENABLED) {
4929 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08004930 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004931 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004932 }
4933 return binder::Status::ok();
4934}
4935
4936void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4937 Mutex::Autolock _l(mSensorPrivacyLock);
4938 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
4939 mRegistered = false;
4940}
4941
Evan Severson09ab4002021-02-10 14:15:19 -08004942bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08004943 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
4944 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4945 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
4946 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4947 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08004948}
4949
Michael Grooverd1d435a2018-12-18 17:39:42 -08004950// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004951// CameraState
4952// ----------------------------------------------------------------------------
4953
Austin Borgered99f642023-06-01 16:51:35 -07004954CameraService::CameraState::CameraState(const std::string& id, int cost,
4955 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004956 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004957 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004958 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08004959
4960CameraService::CameraState::~CameraState() {}
4961
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004962CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004963 Mutex::Autolock lock(mStatusLock);
4964 return mStatus;
4965}
4966
Austin Borgered99f642023-06-01 16:51:35 -07004967std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08004968 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07004969 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08004970 return res;
4971}
4972
Ruben Brunkcc776712015-02-17 20:18:47 -08004973CameraParameters CameraService::CameraState::getShimParams() const {
4974 return mShimParams;
4975}
4976
4977void CameraService::CameraState::setShimParams(const CameraParameters& params) {
4978 mShimParams = params;
4979}
4980
4981int CameraService::CameraState::getCost() const {
4982 return mCost;
4983}
4984
Austin Borgered99f642023-06-01 16:51:35 -07004985std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004986 return mConflicting;
4987}
4988
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004989SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
4990 return mSystemCameraKind;
4991}
4992
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004993bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
4994 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
4995 != mPhysicalCameras.end();
4996}
4997
Austin Borgered99f642023-06-01 16:51:35 -07004998bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004999 Mutex::Autolock lock(mStatusLock);
5000 auto result = mUnavailablePhysicalIds.insert(physicalId);
5001 return result.second;
5002}
5003
Austin Borgered99f642023-06-01 16:51:35 -07005004bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005005 Mutex::Autolock lock(mStatusLock);
5006 auto count = mUnavailablePhysicalIds.erase(physicalId);
5007 return count > 0;
5008}
5009
Austin Borgered99f642023-06-01 16:51:35 -07005010void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005011 Mutex::Autolock lock(mStatusLock);
5012 mClientPackage = clientPackage;
5013}
5014
Austin Borgered99f642023-06-01 16:51:35 -07005015std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005016 Mutex::Autolock lock(mStatusLock);
5017 return mClientPackage;
5018}
5019
Ruben Brunkcc776712015-02-17 20:18:47 -08005020// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005021// ClientEventListener
5022// ----------------------------------------------------------------------------
5023
5024void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005025 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005026 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005027 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005028 if (basicClient.get() != nullptr) {
5029 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005030 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005031 static_cast<int>(basicClient->getClientUid()));
5032 }
5033}
5034
5035void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005036 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005037 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005038 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005039 if (basicClient.get() != nullptr) {
5040 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005041 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005042 static_cast<int>(basicClient->getClientUid()));
5043 }
5044}
5045
Ruben Brunk99e69712015-05-26 17:25:07 -07005046// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005047// CameraClientManager
5048// ----------------------------------------------------------------------------
5049
Ruben Brunk99e69712015-05-26 17:25:07 -07005050CameraService::CameraClientManager::CameraClientManager() {
5051 setListener(std::make_shared<ClientEventListener>());
5052}
5053
Ruben Brunkcc776712015-02-17 20:18:47 -08005054CameraService::CameraClientManager::~CameraClientManager() {}
5055
5056sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005057 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005058 auto descriptor = get(id);
5059 if (descriptor == nullptr) {
5060 return sp<BasicClient>{nullptr};
5061 }
5062 return descriptor->getValue();
5063}
5064
Austin Borgered99f642023-06-01 16:51:35 -07005065std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005066 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005067 std::ostringstream ret;
5068 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005069 bool hasAny = false;
5070 for (auto& i : all) {
5071 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005072 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005073 int32_t cost = i->getCost();
5074 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005075 int32_t score = i->getPriority().getScore();
5076 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005077 auto conflicting = i->getConflicting();
5078 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005079 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005080 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005081 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005082 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005083 uid_t clientUid = clientSp->getClientUid();
5084 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005085 }
Austin Borgered99f642023-06-01 16:51:35 -07005086 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5087 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005088
Ruben Brunk6267b532015-04-30 17:44:07 -07005089 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005090 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005091 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005092 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005093 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005094 }
5095
Austin Borgered99f642023-06-01 16:51:35 -07005096 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005097 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005098 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005099 }
Austin Borgered99f642023-06-01 16:51:35 -07005100 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005101 }
Austin Borgered99f642023-06-01 16:51:35 -07005102 if (hasAny) ret << "\n";
5103 ret << "]\n";
Yi Kong3ac211f2024-08-12 07:31:44 +08005104 return ret.str();
Ruben Brunkcc776712015-02-17 20:18:47 -08005105}
5106
5107CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005108 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5109 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005110 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005111
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005112 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005113 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005114
Austin Borgered99f642023-06-01 16:51:35 -07005115 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005116 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5117 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005118}
5119
5120CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005121 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005122 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005123 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005124 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005125 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5126 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005127}
5128
5129// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005130// InjectionStatusListener
5131// ----------------------------------------------------------------------------
5132
5133void CameraService::InjectionStatusListener::addListener(
5134 const sp<ICameraInjectionCallback>& callback) {
5135 Mutex::Autolock lock(mListenerLock);
5136 if (mCameraInjectionCallback) return;
5137 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5138 if (res == OK) {
5139 mCameraInjectionCallback = callback;
5140 }
5141}
5142
5143void CameraService::InjectionStatusListener::removeListener() {
5144 Mutex::Autolock lock(mListenerLock);
5145 if (mCameraInjectionCallback == nullptr) {
5146 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5147 return;
5148 }
5149 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5150 mCameraInjectionCallback = nullptr;
5151}
5152
5153void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005154 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005155 if (mCameraInjectionCallback == nullptr) {
5156 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5157 return;
5158 }
Cliff Wud3a05312021-04-26 23:07:31 +08005159
5160 switch (err) {
5161 case -ENODEV:
5162 mCameraInjectionCallback->onInjectionError(
5163 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5164 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005165 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005166 break;
5167 case -EBUSY:
5168 mCameraInjectionCallback->onInjectionError(
5169 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5170 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005171 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005172 break;
5173 case DEAD_OBJECT:
5174 mCameraInjectionCallback->onInjectionError(
5175 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5176 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005177 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005178 break;
5179 case INVALID_OPERATION:
5180 mCameraInjectionCallback->onInjectionError(
5181 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5182 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005183 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005184 break;
5185 case UNKNOWN_TRANSACTION:
5186 mCameraInjectionCallback->onInjectionError(
5187 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5188 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005189 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005190 break;
5191 default:
5192 mCameraInjectionCallback->onInjectionError(
5193 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5194 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005195 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005196 }
Cliff Wud8cae102021-03-11 01:37:42 +08005197}
5198
5199void CameraService::InjectionStatusListener::binderDied(
5200 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005201 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5202 auto parent = mParent.promote();
5203 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005204 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5205 if (clientDescriptor != nullptr) {
5206 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5207 baseClientPtr->stopInjection();
5208 }
Cliff Wu3b268182021-07-06 15:44:43 +08005209 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005210 }
5211}
5212
5213// ----------------------------------------------------------------------------
5214// CameraInjectionSession
5215// ----------------------------------------------------------------------------
5216
5217binder::Status CameraService::CameraInjectionSession::stopInjection() {
5218 Mutex::Autolock lock(mInjectionSessionLock);
5219 auto parent = mParent.promote();
5220 if (parent == nullptr) {
5221 ALOGE("CameraInjectionSession: Parent is gone");
5222 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5223 "Camera service encountered error");
5224 }
Cliff Wud3a05312021-04-26 23:07:31 +08005225
5226 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005227 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5228 if (clientDescriptor != nullptr) {
5229 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5230 res = baseClientPtr->stopInjection();
5231 if (res != OK) {
5232 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5233 " ret != NO_ERROR: %d", res);
5234 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5235 "Camera session encountered error");
5236 }
5237 }
Cliff Wu3b268182021-07-06 15:44:43 +08005238 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005239 return binder::Status::ok();
5240}
5241
5242// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005243
5244static const int kDumpLockRetries = 50;
5245static const int kDumpLockSleep = 60000;
5246
5247static bool tryLock(Mutex& mutex)
5248{
5249 bool locked = false;
5250 for (int i = 0; i < kDumpLockRetries; ++i) {
5251 if (mutex.tryLock() == NO_ERROR) {
5252 locked = true;
5253 break;
5254 }
5255 usleep(kDumpLockSleep);
5256 }
5257 return locked;
5258}
5259
Rucha Katakwardf223072021-06-15 10:21:00 -07005260void CameraService::cacheDump() {
5261 if (mMemFd != -1) {
5262 const Vector<String16> args;
5263 ATRACE_CALL();
5264 // Acquiring service lock here will avoid the deadlock since
5265 // cacheDump will not be called during the second disconnect.
5266 Mutex::Autolock lock(mServiceLock);
5267
5268 Mutex::Autolock l(mCameraStatesLock);
5269 // Start collecting the info for open sessions and store it in temp file.
5270 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005271 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005272 auto clientDescriptor = mActiveClientManager.get(cameraId);
5273 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005274 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005275 // Log the current open session info before device is disconnected.
5276 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5277 }
5278 }
5279 }
5280}
5281
Mathias Agopian65ab4712010-07-14 17:59:35 -07005282status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005283 ATRACE_CALL();
5284
Austin Borgered99f642023-06-01 16:51:35 -07005285 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005286 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005287 getCallingPid(),
5288 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005289 return NO_ERROR;
5290 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005291 bool locked = tryLock(mServiceLock);
5292 // failed to lock - CameraService is probably deadlocked
5293 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005294 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005295 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005296
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005297 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005298 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005299
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005300 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005301 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005302
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005303 if (locked) mServiceLock.unlock();
5304 return NO_ERROR;
5305 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005306 dprintf(fd, "\n== Service global info: ==\n\n");
5307 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005308 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005309 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5310 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005311 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5312 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5313 }
Austin Borgered99f642023-06-01 16:51:35 -07005314 std::string activeClientString = mActiveClientManager.toString();
5315 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5316 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005317 if (mStreamUseCaseOverrides.size() > 0) {
5318 dprintf(fd, "Active stream use case overrides:");
5319 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5320 dprintf(fd, " %" PRId64, useCaseOverride);
5321 }
5322 dprintf(fd, "\n");
5323 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005324
5325 dumpEventLog(fd);
5326
5327 bool stateLocked = tryLock(mCameraStatesLock);
5328 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005329 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005330 }
5331
Emilian Peevbd8c5032018-02-14 23:05:40 +00005332 int argSize = args.size();
5333 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005334 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005335 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005336 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005337 }
5338 break;
5339 }
5340 }
5341
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005342 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005343 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005344
Austin Borgered99f642023-06-01 16:51:35 -07005345 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005346
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005347 CameraParameters p = state.second->getShimParams();
5348 if (!p.isEmpty()) {
5349 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5350 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005351 }
5352
5353 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005354 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005355 // log the current open session info
5356 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005357 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005358 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005359 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005360
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005361 }
5362
5363 if (stateLocked) mCameraStatesLock.unlock();
5364
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005365 if (locked) mServiceLock.unlock();
5366
Emilian Peevf53f66e2017-04-11 14:29:43 +01005367 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005368
5369 dprintf(fd, "\n== Vendor tags: ==\n\n");
5370
5371 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5372 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005373 sp<VendorTagDescriptorCache> cache =
5374 VendorTagDescriptorCache::getGlobalVendorTagCache();
5375 if (cache == NULL) {
5376 dprintf(fd, "No vendor tags.\n");
5377 } else {
5378 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5379 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005380 } else {
5381 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5382 }
5383
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005384 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005385 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005386 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005387
5388 // Process dump arguments, if any
5389 int n = args.size();
5390 String16 verboseOption("-v");
5391 String16 unreachableOption("--unreachable");
5392 for (int i = 0; i < n; i++) {
5393 if (args[i] == verboseOption) {
5394 // change logging level
5395 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005396 std::string levelStr = toStdString(args[i+1]);
5397 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005398 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005399 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005400 } else if (args[i] == unreachableOption) {
5401 // Dump memory analysis
5402 // TODO - should limit be an argument parameter?
5403 UnreachableMemoryInfo info;
5404 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5405 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005406 dprintf(fd, "\n== Unable to dump unreachable memory. "
5407 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005408 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005409 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005410 std::string s = info.ToString(/*log_contents*/ true);
5411 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005412 }
5413 }
5414 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005415
5416 bool serviceLocked = tryLock(mServiceLock);
5417
5418 // Dump info from previous open sessions.
5419 // Reposition the offset to beginning of the file before reading
5420
5421 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5422 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5423 ssize_t size_read;
5424 char buf[4096];
5425 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5426 // Read data from file to a small buffer and write it to fd.
5427 write(fd, buf, size_read);
5428 if (size_read == -1) {
5429 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5430 break;
5431 }
5432 }
5433 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5434 } else {
5435 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5436 }
5437
5438 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005439 return NO_ERROR;
5440}
5441
Rucha Katakwardf223072021-06-15 10:21:00 -07005442void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005443 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005444 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005445 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005446 getFormattedCurrentTime().c_str(),
5447 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005448 dprintf(fd, " Client priority score: %d state: %d\n",
5449 clientDescriptor->getPriority().getScore(),
5450 clientDescriptor->getPriority().getState());
5451 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5452
5453 auto client = clientDescriptor->getValue();
5454 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005455 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005456
5457 client->dumpClient(fd, args);
5458}
5459
Austin Borgered99f642023-06-01 16:51:35 -07005460void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005461 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005462 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005463}
5464
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005465void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005466 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005467
5468 Mutex::Autolock l(mLogLock);
5469 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005470 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005471 }
5472
5473 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005474 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005475 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005476 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005477 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005478 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005479}
5480
Austin Borgered99f642023-06-01 16:51:35 -07005481void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005482 Mutex::Autolock lock(mLogLock);
5483 if (!isClientWatchedLocked(client)) { return; }
5484
5485 std::vector<std::string> dumpVector;
5486 client->dumpWatchedEventsToVector(dumpVector);
5487
5488 if (dumpVector.empty()) { return; }
5489
Austin Borgered99f642023-06-01 16:51:35 -07005490 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005491
Austin Borgered99f642023-06-01 16:51:35 -07005492 std::string currentTime = getFormattedCurrentTime();
5493 dumpString << "Cached @ ";
5494 dumpString << currentTime;
5495 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005496
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005497 size_t i = dumpVector.size();
5498
5499 // Store the string in reverse order (latest last)
5500 while (i > 0) {
5501 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005502 dumpString << cameraId;
5503 dumpString << ":";
5504 dumpString << client->getPackageName();
5505 dumpString << " ";
5506 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005507 }
5508
Austin Borgered99f642023-06-01 16:51:35 -07005509 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005510}
5511
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005512void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005513 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005514 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5515 if (mTorchClientMap[i] == who) {
5516 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005517 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005518 status_t res = mFlashlight->setTorchMode(cameraId, false);
5519 if (res) {
5520 ALOGE("%s: torch client died but couldn't turn off torch: "
5521 "%s (%d)", __FUNCTION__, strerror(-res), res);
5522 return;
5523 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005524 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005525 break;
5526 }
5527 }
5528}
5529
Ruben Brunkcc776712015-02-17 20:18:47 -08005530/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005531
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005532 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005533 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5534 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005535 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005536 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005537 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005538
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005539 // check torch client
5540 handleTorchClientBinderDied(who);
5541
5542 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005543 if(!evictClientIdByRemote(who)) {
5544 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005545 return;
5546 }
5547
Ruben Brunkcc776712015-02-17 20:18:47 -08005548 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5549 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005550}
5551
Austin Borgered99f642023-06-01 16:51:35 -07005552void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005553 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005554}
5555
Austin Borgered99f642023-06-01 16:51:35 -07005556void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005557 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005558 // Do not lock mServiceLock here or can get into a deadlock from
5559 // connect() -> disconnect -> updateStatus
5560
5561 auto state = getCameraState(cameraId);
5562
5563 if (state == nullptr) {
5564 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005565 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005566 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005567 }
5568
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005569 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5570 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5571 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005572 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005573 return;
5574 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005575
Biswarup Pal37a75182024-01-16 15:53:35 +00005576 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5577 CameraMetadata cameraInfo;
5578 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00005579 cameraId, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +00005580 if (res != OK) {
5581 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5582 __FUNCTION__, cameraId.c_str());
5583 } else {
5584 int32_t deviceId = getDeviceId(cameraInfo);
5585 if (deviceId != kDefaultDeviceId) {
5586 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5587 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5588 static_cast<camera_metadata_enum_android_lens_facing_t>(
5589 lensFacingEntry.data.u8[0]);
5590 std::string mappedCameraId;
5591 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5592 mappedCameraId = kVirtualDeviceBackCameraId;
5593 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5594 mappedCameraId = kVirtualDeviceFrontCameraId;
5595 } else {
5596 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5597 __func__);
5598 }
5599 if (!mappedCameraId.empty()) {
5600 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5601 }
5602 }
5603 }
5604 }
5605
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005606 // Collect the logical cameras without holding mStatusLock in updateStatus
5607 // as that can lead to a deadlock(b/162192331).
5608 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005609 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005610 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005611 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005612 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005613 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005614 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5615 auto [deviceId, mappedCameraId] =
5616 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005617
Biswarup Pal37a75182024-01-16 15:53:35 +00005618 if (status != StatusInternal::ENUMERATING) {
5619 // Update torch status if it has a flash unit.
5620 Mutex::Autolock al(mTorchStatusMutex);
5621 TorchModeStatus torchStatus;
5622 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5623 NAME_NOT_FOUND) {
5624 TorchModeStatus newTorchStatus =
5625 status == StatusInternal::PRESENT ?
5626 TorchModeStatus::AVAILABLE_OFF :
5627 TorchModeStatus::NOT_AVAILABLE;
5628 if (torchStatus != newTorchStatus) {
5629 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5630 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005631 }
5632 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005633
Biswarup Pal37a75182024-01-16 15:53:35 +00005634 Mutex::Autolock lock(mStatusListenerLock);
5635 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5636 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005637
Biswarup Pal37a75182024-01-16 15:53:35 +00005638 for (auto& listener : mListenerList) {
5639 bool isVendorListener = listener->isVendorListener();
5640 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5641 listener->getListenerPid(), listener->getListenerUid())) {
5642 ALOGV("Skipping discovery callback for system-only camera device %s",
5643 cameraId.c_str());
5644 continue;
5645 }
5646
5647 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5648 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005649 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005650 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005651 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5652 ret.exceptionCode());
5653 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005654 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005655}
5656
Austin Borgered99f642023-06-01 16:51:35 -07005657void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5658 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005659 auto state = getCameraState(cameraId);
5660 if (state == nullptr) {
5661 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005662 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005663 return;
5664 }
5665 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005666 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005667 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005668 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005669 }
5670
Biswarup Pal37a75182024-01-16 15:53:35 +00005671 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5672 auto [deviceId, mappedCameraId] =
5673 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5674
Shuzhen Wang695044d2020-03-06 09:02:23 -08005675 Mutex::Autolock lock(mStatusListenerLock);
5676
5677 for (const auto& it : mListenerList) {
5678 if (!it->isOpenCloseCallbackAllowed()) {
5679 continue;
5680 }
5681
5682 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005683 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005684 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5685 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005686 } else {
Biswarup Pal37a75182024-01-16 15:53:35 +00005687 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005688 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005689
5690 it->handleBinderStatus(ret,
5691 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5692 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005693 }
5694}
5695
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005696template<class Func>
5697void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005698 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005699 std::initializer_list<StatusInternal> rejectSourceStates,
5700 Func onStatusUpdatedLocked) {
5701 Mutex::Autolock lock(mStatusLock);
5702 StatusInternal oldStatus = mStatus;
5703 mStatus = status;
5704
5705 if (oldStatus == status) {
5706 return;
5707 }
5708
5709 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07005710 cameraId.c_str(), eToI(oldStatus), eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005711
5712 if (oldStatus == StatusInternal::NOT_PRESENT &&
5713 (status != StatusInternal::PRESENT &&
5714 status != StatusInternal::ENUMERATING)) {
5715
5716 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5717 __FUNCTION__);
5718 mStatus = oldStatus;
5719 return;
5720 }
5721
5722 /**
5723 * Sometimes we want to conditionally do a transition.
5724 * For example if a client disconnects, we want to go to PRESENT
5725 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5726 */
5727 for (auto& rejectStatus : rejectSourceStates) {
5728 if (oldStatus == rejectStatus) {
5729 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005730 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005731 mStatus = oldStatus;
5732 return;
5733 }
5734 }
5735
5736 onStatusUpdatedLocked(cameraId, status);
5737}
5738
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005739status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005740 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005741 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005742 if (!status) {
5743 return BAD_VALUE;
5744 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005745 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5746 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005747 // invalid camera ID or the camera doesn't have a flash unit
5748 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005749 }
5750
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005751 *status = mTorchStatusMap.valueAt(index);
5752 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005753}
5754
Austin Borgered99f642023-06-01 16:51:35 -07005755status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005756 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005757 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5758 if (index == NAME_NOT_FOUND) {
5759 return BAD_VALUE;
5760 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005761 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005762
5763 return OK;
5764}
5765
Austin Borgered99f642023-06-01 16:51:35 -07005766std::list<std::string> CameraService::getLogicalCameras(
5767 const std::string& physicalCameraId) {
5768 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005769 Mutex::Autolock lock(mCameraStatesLock);
5770 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005771 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5772 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005773 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005774 }
5775 return retList;
5776}
5777
5778void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005779 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00005780 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005781 // mStatusListenerLock is expected to be locked
5782 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005783 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005784 // Note: we check only the deviceKind of the physical camera id
5785 // since, logical camera ids and their physical camera ids are
5786 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005787 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5788 listener->getListenerPid(), listener->getListenerUid())) {
5789 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005790 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005791 continue;
5792 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005793 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00005794 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005795 listener->handleBinderStatus(ret,
5796 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5797 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5798 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005799 }
5800 }
5801}
5802
Svet Ganova453d0d2018-01-11 15:37:58 -08005803void CameraService::blockClientsForUid(uid_t uid) {
5804 const auto clients = mActiveClientManager.getAll();
5805 for (auto& current : clients) {
5806 if (current != nullptr) {
5807 const auto basicClient = current->getValue();
5808 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5809 basicClient->block();
5810 }
5811 }
5812 }
5813}
5814
Michael Grooverd1d435a2018-12-18 17:39:42 -08005815void CameraService::blockAllClients() {
5816 const auto clients = mActiveClientManager.getAll();
5817 for (auto& current : clients) {
5818 if (current != nullptr) {
5819 const auto basicClient = current->getValue();
5820 if (basicClient.get() != nullptr) {
5821 basicClient->block();
5822 }
5823 }
5824 }
5825}
5826
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005827void CameraService::blockPrivacyEnabledClients() {
5828 const auto clients = mActiveClientManager.getAll();
5829 for (auto& current : clients) {
5830 if (current != nullptr) {
5831 const auto basicClient = current->getValue();
5832 if (basicClient.get() != nullptr) {
5833 std::string pkgName = basicClient->getPackageName();
5834 bool cameraPrivacyEnabled =
5835 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
5836 if (cameraPrivacyEnabled) {
5837 basicClient->block();
5838 }
5839 }
5840 }
5841 }
5842}
5843
Svet Ganova453d0d2018-01-11 15:37:58 -08005844// NOTE: This is a remote API - make sure all args are validated
5845status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005846 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005847 return PERMISSION_DENIED;
5848 }
5849 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5850 return BAD_VALUE;
5851 }
Austin Borgered99f642023-06-01 16:51:35 -07005852 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005853 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005854 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005855 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005856 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005857 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005858 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005859 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005860 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005861 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005862 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005863 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005864 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005865 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005866 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005867 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005868 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005869 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005870 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005871 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005872 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005873 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005874 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005875 handleClearStreamUseCaseOverrides();
5876 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005877 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005878 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07005879 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005880 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07005881 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00005882 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07005883 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005884 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005885 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005886 }
5887 printHelp(err);
5888 return BAD_VALUE;
5889}
5890
5891status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005892 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005893
Svet Ganova453d0d2018-01-11 15:37:58 -08005894 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07005895 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005896 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07005897 } else if ((args[2] != toString16("idle"))) {
5898 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08005899 return BAD_VALUE;
5900 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005901
5902 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005903 if (args.size() >= 5 && args[3] == toString16("--user")) {
5904 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005905 }
5906
5907 uid_t uid;
5908 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5909 return BAD_VALUE;
5910 }
5911
5912 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005913 return NO_ERROR;
5914}
5915
5916status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005917 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005918
5919 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005920 if (args.size() >= 4 && args[2] == toString16("--user")) {
5921 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005922 }
5923
5924 uid_t uid;
5925 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005926 return BAD_VALUE;
5927 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005928
5929 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005930 return NO_ERROR;
5931}
5932
5933status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005934 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005935
5936 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005937 if (args.size() >= 4 && args[2] == toString16("--user")) {
5938 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005939 }
5940
5941 uid_t uid;
5942 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005943 return BAD_VALUE;
5944 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005945
5946 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005947 return dprintf(out, "active\n");
5948 } else {
5949 return dprintf(out, "idle\n");
5950 }
5951}
5952
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005953status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005954 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005955 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
5956 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
5957 Mutex::Autolock lock(mServiceLock);
5958
5959 mOverrideRotateAndCropMode = rotateValue;
5960
5961 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
5962
5963 const auto clients = mActiveClientManager.getAll();
5964 for (auto& current : clients) {
5965 if (current != nullptr) {
5966 const auto basicClient = current->getValue();
5967 if (basicClient.get() != nullptr) {
5968 basicClient->setRotateAndCropOverride(rotateValue);
5969 }
5970 }
5971 }
5972
5973 return OK;
5974}
5975
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005976status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
5977 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07005978 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005979 if ((*end != '\0') ||
5980 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
5981 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
5982 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
5983 return BAD_VALUE;
5984 }
5985
5986 Mutex::Autolock lock(mServiceLock);
5987 mOverrideAutoframingMode = autoframingValue;
5988
5989 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
5990
5991 const auto clients = mActiveClientManager.getAll();
5992 for (auto& current : clients) {
5993 if (current != nullptr) {
5994 const auto basicClient = current->getValue();
5995 if (basicClient.get() != nullptr) {
5996 basicClient->setAutoframingOverride(autoframingValue);
5997 }
5998 }
5999 }
6000
6001 return OK;
6002}
6003
Ravneetaeb20dc2022-03-30 05:33:03 +00006004status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006005 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006006
6007 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6008
6009 Mutex::Autolock lock(mServiceLock);
6010
6011 mCameraServiceWatchdogEnabled = enableWatchdog;
6012
6013 const auto clients = mActiveClientManager.getAll();
6014 for (auto& current : clients) {
6015 if (current != nullptr) {
6016 const auto basicClient = current->getValue();
6017 if (basicClient.get() != nullptr) {
6018 basicClient->setCameraServiceWatchdog(enableWatchdog);
6019 }
6020 }
6021 }
6022
6023 return OK;
6024}
6025
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006026status_t CameraService::handleGetRotateAndCrop(int out) {
6027 Mutex::Autolock lock(mServiceLock);
6028
6029 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6030}
6031
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006032status_t CameraService::handleGetAutoframing(int out) {
6033 Mutex::Autolock lock(mServiceLock);
6034
6035 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6036}
6037
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006038status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6039 char *endPtr;
6040 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006041 std::string maskString = toStdString(args[1]);
6042 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006043
6044 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006045 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006046 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6047
6048 Mutex::Autolock lock(mServiceLock);
6049
6050 mImageDumpMask = maskValue;
6051
6052 return OK;
6053}
6054
6055status_t CameraService::handleGetImageDumpMask(int out) {
6056 Mutex::Autolock lock(mServiceLock);
6057
6058 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6059}
6060
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006061status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006062 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006063 if (errno != 0) return BAD_VALUE;
6064
6065 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6066 Mutex::Autolock lock(mServiceLock);
6067
6068 mOverrideCameraMuteMode = (muteValue == 1);
6069
6070 const auto clients = mActiveClientManager.getAll();
6071 for (auto& current : clients) {
6072 if (current != nullptr) {
6073 const auto basicClient = current->getValue();
6074 if (basicClient.get() != nullptr) {
6075 if (basicClient->supportsCameraMute()) {
6076 basicClient->setCameraMute(mOverrideCameraMuteMode);
6077 }
6078 }
6079 }
6080 }
6081
6082 return OK;
6083}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006084
Shuzhen Wang16610a62022-12-15 22:38:07 -08006085status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6086 std::vector<int64_t> useCasesOverride;
6087 for (size_t i = 1; i < args.size(); i++) {
6088 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006089 std::string arg = toStdString(args[i]);
6090 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006091 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006092 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006093 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006094 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006095 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006096 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006097 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006098 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006099 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006100 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006101 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006102 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006103 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6104 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006105 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006106 return BAD_VALUE;
6107 }
6108 useCasesOverride.push_back(useCase);
6109 }
6110
6111 Mutex::Autolock lock(mServiceLock);
6112 mStreamUseCaseOverrides = std::move(useCasesOverride);
6113
6114 return OK;
6115}
6116
6117void CameraService::handleClearStreamUseCaseOverrides() {
6118 Mutex::Autolock lock(mServiceLock);
6119 mStreamUseCaseOverrides.clear();
6120}
6121
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006122status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6123 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006124 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006125 if ((*end != '\0') ||
6126 (zoomOverrideValue != -1 &&
6127 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6128 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6129 return BAD_VALUE;
6130 }
6131
6132 Mutex::Autolock lock(mServiceLock);
6133 mZoomOverrideValue = zoomOverrideValue;
6134
6135 const auto clients = mActiveClientManager.getAll();
6136 for (auto& current : clients) {
6137 if (current != nullptr) {
6138 const auto basicClient = current->getValue();
6139 if (basicClient.get() != nullptr) {
6140 if (basicClient->supportsZoomOverride()) {
6141 basicClient->setZoomOverride(mZoomOverrideValue);
6142 }
6143 }
6144 }
6145 }
6146
6147 return OK;
6148}
6149
Avichal Rakesh84147132021-11-11 17:47:11 -08006150status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006151 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006152 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006153 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006154 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006155 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006156 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006157 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006158 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006159 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006160 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006161 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006162 dprintf(outFd, "Camera service watch commands:\n"
6163 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6164 " starts watching the provided tags for clients with provided package\n"
6165 " recognizes tag shorthands like '3a'\n"
6166 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006167 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006168 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006169 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006170 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006171 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006172 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006173 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006174}
6175
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006176status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6177 Mutex::Autolock lock(mLogLock);
6178 size_t tagsIdx; // index of '-m'
6179 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006180 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006181 if (tagsIdx < args.size() - 1) {
6182 tags = args[tagsIdx + 1];
6183 } else {
6184 dprintf(outFd, "No tags provided.\n");
6185 return BAD_VALUE;
6186 }
6187
6188 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006189 // watch all clients if no clients are provided
6190 String16 clients = toString16(kWatchAllClientsFlag);
6191 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006192 clientsIdx++);
6193 if (clientsIdx < args.size() - 1) {
6194 clients = args[clientsIdx + 1];
6195 }
Austin Borgered99f642023-06-01 16:51:35 -07006196 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006197
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006198 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006199 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006200
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006201 bool serviceLock = tryLock(mServiceLock);
6202 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006203 auto cameraClients = mActiveClientManager.getAll();
6204 for (const auto &clientDescriptor: cameraClients) {
6205 if (clientDescriptor == nullptr) { continue; }
6206 sp<BasicClient> client = clientDescriptor->getValue();
6207 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006208
6209 if (isClientWatchedLocked(client.get())) {
6210 client->startWatchingTags(mMonitorTags, outFd);
6211 numWatchedClients++;
6212 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006213 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006214 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6215
6216 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006217 return OK;
6218}
6219
6220status_t CameraService::stopWatchingTags(int outFd) {
6221 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006222 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006223 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006224
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006225 mWatchedClientPackages.clear();
6226 mWatchedClientsDumpCache.clear();
6227
6228 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006229 auto cameraClients = mActiveClientManager.getAll();
6230 for (const auto &clientDescriptor : cameraClients) {
6231 if (clientDescriptor == nullptr) { continue; }
6232 sp<BasicClient> client = clientDescriptor->getValue();
6233 if (client.get() == nullptr) { continue; }
6234 client->stopWatchingTags(outFd);
6235 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006236 dprintf(outFd, "Stopped watching all clients.\n");
6237 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006238 return OK;
6239}
6240
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006241status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6242 Mutex::Autolock lock(mLogLock);
6243 size_t clearedSize = mWatchedClientsDumpCache.size();
6244 mWatchedClientsDumpCache.clear();
6245 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6246 return OK;
6247}
6248
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006249status_t CameraService::printWatchedTags(int outFd) {
6250 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006251 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006252
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006253 bool printedSomething = false; // tracks if any monitoring information was printed
6254 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006255
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006256 bool serviceLock = tryLock(mServiceLock);
6257 // get all watched clients that are currently connected
6258 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6259 if (clientDescriptor == nullptr) { continue; }
6260
6261 sp<BasicClient> client = clientDescriptor->getValue();
6262 if (client.get() == nullptr) { continue; }
6263 if (!isClientWatchedLocked(client.get())) { continue; }
6264
6265 std::vector<std::string> dumpVector;
6266 client->dumpWatchedEventsToVector(dumpVector);
6267
6268 size_t printIdx = dumpVector.size();
6269 if (printIdx == 0) {
6270 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006271 }
6272
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006273 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006274 const std::string &cameraId = clientDescriptor->getKey();
6275 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006276 while(printIdx > 0) {
6277 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006278 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006279 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006280 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006281 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006282 printedSomething = true;
6283
6284 connectedMonitoredClients.emplace(client->getPackageName());
6285 }
6286 if (serviceLock) { mServiceLock.unlock(); }
6287
6288 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6289 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006290 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006291 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6292 continue;
6293 }
6294
Austin Borgered99f642023-06-01 16:51:35 -07006295 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006296 dprintf(outFd, "%s\n", kv.second.c_str());
6297 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006298 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006299
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006300 if (!printedSomething) {
6301 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006302 }
6303
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006304 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006305}
6306
Avichal Rakesh84147132021-11-11 17:47:11 -08006307// Print all events in vector `events' that came after lastPrintedEvent
6308void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006309 const std::string &cameraId,
6310 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006311 const std::vector<std::string> &events,
6312 const std::string &lastPrintedEvent) {
6313 if (events.empty()) { return; }
6314
6315 // index of lastPrintedEvent in events.
6316 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6317 size_t lastPrintedIdx;
6318 for (lastPrintedIdx = 0;
6319 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6320 lastPrintedIdx++);
6321
6322 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6323
Avichal Rakesh84147132021-11-11 17:47:11 -08006324 // print events in chronological order (latest event last)
6325 size_t idxToPrint = lastPrintedIdx;
6326 do {
6327 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006328 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6329 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006330 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006331}
6332
6333// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6334// command should be interrupted if the user presses the return key, or if user loses any way to
6335// signal interrupt.
6336// If timeoutMs == 0, this function will always return false
6337bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6338 struct timeval startTime;
6339 int startTimeError = gettimeofday(&startTime, nullptr);
6340 if (startTimeError) {
6341 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6342 return true;
6343 }
6344
6345 const nfds_t numFds = 1;
6346 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6347
6348 struct timeval currTime;
6349 char buffer[2];
6350 while(true) {
6351 int currTimeError = gettimeofday(&currTime, nullptr);
6352 if (currTimeError) {
6353 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6354 return true;
6355 }
6356
6357 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6358 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6359 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6360
6361 if (remainingTimeMs <= 0) {
6362 // No user interrupt within timeoutMs, don't interrupt watch command
6363 return false;
6364 }
6365
6366 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6367 if (numFdsUpdated < 0) {
6368 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6369 return true;
6370 }
6371
6372 if (numFdsUpdated == 0) {
6373 // No user input within timeoutMs, don't interrupt watch command
6374 return false;
6375 }
6376
6377 if (!(pollFd.revents & POLLIN)) {
6378 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6379 return true;
6380 }
6381
6382 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6383 if (sizeRead < 0) {
6384 dprintf(outFd, "Error reading user input. Exiting.\n");
6385 return true;
6386 }
6387
6388 if (sizeRead == 0) {
6389 // Reached end of input fd (can happen if input is piped)
6390 // User has no way to signal an interrupt, so interrupt here
6391 return true;
6392 }
6393
6394 if (buffer[0] == '\n') {
6395 // User pressed return, interrupt watch command.
6396 return true;
6397 }
6398 }
6399}
6400
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006401status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6402 int inFd, int outFd) {
6403 // Figure out refresh interval, if present in args
6404 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006405 if (args.size() > 2) {
6406 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006407 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006408 intervalIdx++);
6409
6410 size_t intervalValIdx = intervalIdx + 1;
6411 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006412 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006413 if (errno) { return BAD_VALUE; }
6414 }
6415 }
6416
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006417 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6418 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006419
Avichal Rakesh84147132021-11-11 17:47:11 -08006420 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006421 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006422
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006423 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006424 bool serviceLock = tryLock(mServiceLock);
6425 auto cameraClients = mActiveClientManager.getAll();
6426 if (serviceLock) { mServiceLock.unlock(); }
6427
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006428 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006429 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006430 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006431
6432 sp<BasicClient> client = clientDescriptor->getValue();
6433 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006434 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006435
Austin Borgered99f642023-06-01 16:51:35 -07006436 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006437 // This also initializes the map entries with an empty string
6438 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6439
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006440 std::vector<std::string> latestEvents;
6441 client->dumpWatchedEventsToVector(latestEvents);
6442
6443 if (!latestEvents.empty()) {
6444 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006445 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006446 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006447 latestEvents,
6448 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006449 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006450 }
6451 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006452 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006453 break;
6454 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006455 }
6456 return OK;
6457}
6458
Austin Borgered99f642023-06-01 16:51:35 -07006459void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006460 mWatchedClientPackages.clear();
6461
Austin Borgered99f642023-06-01 16:51:35 -07006462 std::istringstream iss(clients);
6463 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006464
Austin Borgered99f642023-06-01 16:51:35 -07006465 while (std::getline(iss, nextClient, ',')) {
6466 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006467 // Don't need to track any other package if 'all' is present
6468 mWatchedClientPackages.clear();
6469 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6470 break;
6471 }
6472
6473 // track package names
6474 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006475 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006476}
6477
Svet Ganova453d0d2018-01-11 15:37:58 -08006478status_t CameraService::printHelp(int out) {
6479 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006480 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6481 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6482 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006483 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6484 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6485 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006486 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6487 " Valid values 0=false, 1=true, 2=auto\n"
6488 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006489 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6490 " Valid values 0=OFF, 1=ON for JPEG\n"
6491 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006492 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006493 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6494 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6495 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6496 " on. In case the number of usecases is smaller than the number of streams, the\n"
6497 " last use case is assigned to all the remaining streams. In case of multiple\n"
6498 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6499 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6500 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6501 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006502 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6503 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006504 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6505 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006506 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006507 " help print this message\n");
6508}
6509
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006510bool CameraService::isClientWatched(const BasicClient *client) {
6511 Mutex::Autolock lock(mLogLock);
6512 return isClientWatchedLocked(client);
6513}
6514
6515bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6516 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6517 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6518}
6519
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006520int32_t CameraService::updateAudioRestriction() {
6521 Mutex::Autolock lock(mServiceLock);
6522 return updateAudioRestrictionLocked();
6523}
6524
6525int32_t CameraService::updateAudioRestrictionLocked() {
6526 int32_t mode = 0;
6527 // iterate through all active client
6528 for (const auto& i : mActiveClientManager.getAll()) {
6529 const auto clientSp = i->getValue();
6530 mode |= clientSp->getAudioRestriction();
6531 }
6532
6533 bool modeChanged = (mAudioRestriction != mode);
6534 mAudioRestriction = mode;
6535 if (modeChanged) {
6536 mAppOps.setCameraAudioRestriction(mode);
6537 }
6538 return mode;
6539}
6540
Austin Borgered99f642023-06-01 16:51:35 -07006541status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006542 sp<BasicClient> clientSp) {
6543 std::unique_ptr<AutoConditionLock> lock =
6544 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6545 status_t res = NO_ERROR;
6546 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006547 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006548 mInjectionStatusListener->notifyInjectionError(
6549 externalCamId, UNKNOWN_TRANSACTION);
6550 clientSp->notifyError(
6551 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6552 CaptureResultExtras());
6553
6554 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6555 // other clients from connecting in mServiceLockWrapper if held
6556 mServiceLock.unlock();
6557
6558 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006559 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006560 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006561 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006562
6563 // Reacquire mServiceLock
6564 mServiceLock.lock();
6565 }
6566
6567 return res;
6568}
6569
Cliff Wud3a05312021-04-26 23:07:31 +08006570void CameraService::clearInjectionParameters() {
6571 {
6572 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006573 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006574 mInjectionInternalCamId = "";
6575 }
6576 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006577 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006578}
6579
Biswarup Pal37a75182024-01-16 15:53:35 +00006580} // namespace android