blob: 378eb4ad6a5d308e7f4c978ba27944a58d9a136f [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"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070085#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000086#include "utils/TagMonitor.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070087#include "utils/CameraServiceProxyWrapper.h"
Shuzhen Wang045be6c2023-10-12 10:01:10 -070088#include "utils/SessionConfigurationUtils.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080090namespace {
91 const char* kPermissionServiceName = "permission";
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
Rucha Katakward9ea6452021-05-06 11:57:16 -0700168// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700169static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700170
Austin Borger74fca042022-05-23 12:41:21 -0700171CameraService::CameraService(
Austin Borger249e6592024-03-10 22:28:11 -0700172 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,
173 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils) :
174 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils == nullptr ?
175 std::make_shared<AttributionAndPermissionUtils>()\
176 : attributionAndPermissionUtils),
Austin Borger74fca042022-05-23 12:41:21 -0700177 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
178 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800179 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800180 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700181 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700182 mSoundRef(0), mInitialized(false),
183 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000184 ALOGI("CameraService started (pid=%d)", getpid());
Austin Borger249e6592024-03-10 22:28:11 -0700185 mAttributionAndPermissionUtils->setCameraService(this);
Ruben Brunkcc776712015-02-17 20:18:47 -0800186 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700187 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
188 if (mMemFd == -1) {
189 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
190 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700191}
192
Charles Chena7b613c2023-01-24 21:57:33 +0000193// Enable processes with isolated AID to request the binder
194void CameraService::instantiate() {
195 CameraService::publish(true);
196}
197
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800198void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700199 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800200 return;
201 }
202
203 ALOGV("appops service registered. setting camera audio restriction");
204 mAppOps.setCameraAudioRestriction(mAudioRestriction);
205}
206
Iliyan Malchev8951a972011-04-14 16:55:59 -0700207void CameraService::onFirstRef()
208{
Ruben Brunkcc776712015-02-17 20:18:47 -0800209 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800210
Iliyan Malchev8951a972011-04-14 16:55:59 -0700211 BnCameraService::onFirstRef();
212
Ruben Brunk99e69712015-05-26 17:25:07 -0700213 // Update battery life tracking if service is restarting
214 BatteryNotifier& notifier(BatteryNotifier::getInstance());
215 notifier.noteResetCamera();
216 notifier.noteResetFlashlight();
217
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800218 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800219
Emilian Peevf53f66e2017-04-11 14:29:43 +0100220 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800221 if (res == OK) {
222 mInitialized = true;
223 }
224
Svet Ganova453d0d2018-01-11 15:37:58 -0800225 mUidPolicy = new UidPolicy(this);
226 mUidPolicy->registerSelf();
Austin Borger249e6592024-03-10 22:28:11 -0700227 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this, mAttributionAndPermissionUtils);
Michael Grooverd1d435a2018-12-18 17:39:42 -0800228 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800229 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800230
231 // appops function setCamerAudioRestriction uses getService which
232 // is blocking till the appops service is ready. To enable early
233 // boot availability for cameraservice, use checkService which is
234 // non blocking and register for notifications
235 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700236 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800237 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700238 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800239 } else {
240 mAppOps.setCameraAudioRestriction(mAudioRestriction);
241 }
242
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700243 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
244 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000245 // Deprecated, so it will fail to register on newer devices
246 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700247 __FUNCTION__);
248 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700249
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700250 if (!AidlCameraService::registerService(this)) {
251 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
252 }
253
Shuzhen Wang24b44152019-09-20 10:38:11 -0700254 // This needs to be last call in this function, so that it's as close to
255 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700256 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700257 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800258}
259
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800260status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800261 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100262
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800263 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000264 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800265 {
266 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800267
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800268 if (nullptr == mCameraProviderManager.get()) {
269 mCameraProviderManager = new CameraProviderManager();
270 res = mCameraProviderManager->initialize(this);
271 if (res != OK) {
272 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
273 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700274 logServiceError("Unable to initialize camera provider manager",
275 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800276 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100277 }
278 }
279
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800280 // Setup vendor tags before we call get_camera_info the first time
281 // because HAL might need to setup static vendor keys in get_camera_info
282 // TODO: maybe put this into CameraProviderManager::initialize()?
283 mCameraProviderManager->setUpVendorTags();
284
285 if (nullptr == mFlashlight.get()) {
286 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700287 }
288
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800289 res = mFlashlight->findFlashUnits();
290 if (res != OK) {
291 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
292 }
293
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000294 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800295 }
296
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800297 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700298 if (getCameraState(cameraId) == nullptr) {
299 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800300 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000301 if (unavailPhysicalIds.count(cameraId) > 0) {
302 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700303 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000304 }
305 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800306 }
307
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700308 // Derive primary rear/front cameras, and filter their charactierstics.
309 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700310 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700311 // Assume internal cameras are advertised from the same
312 // provider. If multiple providers are registered at different time,
313 // and each provider contains multiple internal color cameras, the current
314 // logic may filter the characteristics of more than one front/rear color
315 // cameras.
316 Mutex::Autolock l(mServiceLock);
317 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700318 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700319
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800320 return OK;
321}
322
Austin Borgered99f642023-06-01 16:51:35 -0700323void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700324 SystemCameraKind systemCameraKind) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000325 // Get the device id and app-visible camera id for the given HAL-visible camera id.
326 auto [deviceId, mappedCameraId] =
327 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
328
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800329 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800330 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700331 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
332 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000333 ALOGV("%s: Skipping torch callback for system-only camera device %s",
334 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700335 continue;
336 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000337
Austin Borgere8e2c422022-05-12 13:45:24 -0700338 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Biswarup Pal37a75182024-01-16 15:53:35 +0000339 mappedCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700340 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
341 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Biswarup Pal37a75182024-01-16 15:53:35 +0000342
343 // Only cameras of the default device can be remapped to a different camera (using
344 // remapCameraIds method), so do the following only if the camera is associated with the
345 // default device.
346 if (deviceId == kDefaultDeviceId) {
347 // For the default device, also trigger the torch callbacks for cameras that were
348 // remapped to the current cameraId for the specific package that this listener belongs
349 // to.
350 std::vector<std::string> remappedCameraIds =
351 findOriginalIdsForRemappedCameraId(cameraId, i->getListenerUid());
352 for (auto &remappedCameraId: remappedCameraIds) {
353 ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
354 remappedCameraId, kDefaultDeviceId);
355 i->handleBinderStatus(ret,
356 "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
357 __FUNCTION__, i->getListenerUid(), i->getListenerPid(),
358 ret.exceptionCode());
359 }
malikakash82ed4352023-07-21 22:44:34 +0000360 }
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800361 }
362}
363
Mathias Agopian65ab4712010-07-14 17:59:35 -0700364CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800365 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800366 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800367 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800368 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700369}
370
Emilian Peevaee727d2017-05-04 16:35:48 +0100371void CameraService::onNewProviderRegistered() {
372 enumerateProviders();
373}
374
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700375void CameraService::filterAPI1SystemCameraLocked(
376 const std::vector<std::string> &normalDeviceIds) {
377 mNormalDeviceIdsWithoutSystemCamera.clear();
Biswarup Pal37a75182024-01-16 15:53:35 +0000378 for (auto &cameraId : normalDeviceIds) {
379 if (vd_flags::camera_device_awareness()) {
380 CameraMetadata cameraInfo;
381 status_t res = mCameraProviderManager->getCameraCharacteristics(
382 cameraId, false, &cameraInfo, false);
383 int32_t deviceId = kDefaultDeviceId;
384 if (res != OK) {
385 ALOGW("%s: Not able to get camera characteristics for camera id %s",
386 __FUNCTION__, cameraId.c_str());
387 } else {
388 deviceId = getDeviceId(cameraInfo);
389 }
390 // Cameras associated with non-default device id's (i.e., virtual cameras) can never be
391 // system cameras, so skip for non-default device id's.
392 if (deviceId != kDefaultDeviceId) {
393 continue;
394 }
395 }
396
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700397 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Biswarup Pal37a75182024-01-16 15:53:35 +0000398 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
399 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700400 continue;
401 }
402 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700403 // All system camera ids will necessarily come after public camera
404 // device ids as per the HAL interface contract.
405 break;
406 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000407 mNormalDeviceIdsWithoutSystemCamera.push_back(cameraId);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700408 }
409 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
410 mNormalDeviceIdsWithoutSystemCamera.size());
411}
412
Austin Borgered99f642023-06-01 16:51:35 -0700413status_t CameraService::getSystemCameraKind(const std::string& cameraId,
414 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700415 auto state = getCameraState(cameraId);
416 if (state != nullptr) {
417 *kind = state->getSystemCameraKind();
418 return OK;
419 }
420 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700421 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700422}
423
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800424void CameraService::updateCameraNumAndIds() {
425 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700426 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
427 // Excludes hidden secure cameras
428 mNumberOfCameras =
429 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
430 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800431 mNormalDeviceIds =
432 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700433 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800434}
435
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700436void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700437 // To claim to be S Performance primary cameras, the cameras must be
438 // backward compatible. So performance class primary camera Ids must be API1
439 // compatible.
440 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
441 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
442 int facing = -1;
443 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800444 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -0700445 getDeviceVersion(cameraId, /*overrideToPortrait*/false, /*out*/&portraitRotation,
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800446 /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700447 if (facing == -1) {
448 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
449 return;
450 }
451
452 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
453 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700454 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
455 if (res == OK) {
456 mPerfClassPrimaryCameraIds.insert(cameraId);
457 } else {
458 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
459 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
460 break;
461 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700462
463 if (facing == hardware::CAMERA_FACING_BACK) {
464 firstRearCameraSeen = true;
465 }
466 if (facing == hardware::CAMERA_FACING_FRONT) {
467 firstFrontCameraSeen = true;
468 }
469 }
470
471 if (firstRearCameraSeen && firstFrontCameraSeen) {
472 break;
473 }
474 }
475}
476
Austin Borgered99f642023-06-01 16:51:35 -0700477void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700478 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100479 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
480 if (res != OK) {
481 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
482 return;
483 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000484 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700485 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
486 if (res != OK) {
487 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
488 return;
489 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000490 std::vector<std::string> physicalCameraIds;
491 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700492 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100493 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700494 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100495 }
496
497 {
498 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700499 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000500 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100501 }
502
Austin Borgered99f642023-06-01 16:51:35 -0700503 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100504 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700505 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800506
Austin Borgered99f642023-06-01 16:51:35 -0700507 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100508 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800509
510 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700511 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100512}
513
Austin Borgered99f642023-06-01 16:51:35 -0700514void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800515 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700516 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100517 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700518 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100519 }
520
521 {
522 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700523 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100524 }
525}
526
Austin Borgered99f642023-06-01 16:51:35 -0700527void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800528 CameraDeviceStatus newHalStatus) {
529 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700530 cameraId.c_str(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700531
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800532 StatusInternal newStatus = mapToInternal(newHalStatus);
533
Austin Borgered99f642023-06-01 16:51:35 -0700534 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800535
536 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700537 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100538 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700539 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100540
541 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700542 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100543
Austin Borgered99f642023-06-01 16:51:35 -0700544 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700545 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700546 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700547 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700548 return;
549 }
550
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800551 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800552
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800553 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800554 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700555 return;
556 }
557
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800558 if (newStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000559 logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
560 oldStatus, newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800561 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
562 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700563 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000564 mVirtualDeviceCameraIdMapper.removeCamera(cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800565
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800566 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700567 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800568 // Don't do this in updateStatus to avoid deadlock over mServiceLock
569 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700570
Ruben Brunkcc776712015-02-17 20:18:47 -0800571 // Remove cached shim parameters
572 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700573
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800574 // Remove online as well as offline client from the list of active clients,
575 // if they are present
Austin Borgered99f642023-06-01 16:51:35 -0700576 clientToDisconnectOnline = removeClientLocked(cameraId);
577 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700578 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800579
Austin Borgered99f642023-06-01 16:51:35 -0700580 disconnectClient(cameraId, clientToDisconnectOnline);
581 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700582
Austin Borgered99f642023-06-01 16:51:35 -0700583 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800584 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800585 if (oldStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000586 logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
587 oldStatus, newStatus));
Ruben Brunka8ca9152015-04-07 14:23:40 -0700588 }
Austin Borgered99f642023-06-01 16:51:35 -0700589 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700590 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800591}
Igor Murashkincba2c162013-03-20 15:56:31 -0700592
Austin Borgered99f642023-06-01 16:51:35 -0700593void CameraService::onDeviceStatusChanged(const std::string& id,
594 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800595 CameraDeviceStatus newHalStatus) {
596 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700597 __FUNCTION__, id.c_str(), physicalId.c_str(), newHalStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800598
599 StatusInternal newStatus = mapToInternal(newHalStatus);
600
601 std::shared_ptr<CameraState> state = getCameraState(id);
602
603 if (state == nullptr) {
604 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700605 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800606 return;
607 }
608
609 StatusInternal logicalCameraStatus = state->getStatus();
610 if (logicalCameraStatus != StatusInternal::PRESENT &&
611 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
612 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Austin Borgered99f642023-06-01 16:51:35 -0700613 __FUNCTION__, physicalId.c_str(), newHalStatus, logicalCameraStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800614 return;
615 }
616
617 bool updated = false;
618 if (newStatus == StatusInternal::PRESENT) {
619 updated = state->removeUnavailablePhysicalId(physicalId);
620 } else {
621 updated = state->addUnavailablePhysicalId(physicalId);
622 }
623
624 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700625 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800626 if (newStatus == StatusInternal::PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000627 logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800628 } else {
Henri Chataingbcb99452023-11-01 17:40:30 +0000629 logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800630 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700631 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
632 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
633 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700634 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700635 return;
636 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800637 Mutex::Autolock lock(mStatusListenerLock);
638 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700639 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
640 listener->getListenerPid(), listener->getListenerUid())) {
641 ALOGV("Skipping discovery callback for system-only camera device %s",
642 id.c_str());
643 continue;
644 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700645 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Biswarup Pal37a75182024-01-16 15:53:35 +0000646 mapToInterface(newStatus), id, physicalId, kDefaultDeviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700647 listener->handleBinderStatus(ret,
648 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
649 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
650 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800651 }
652 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700653}
654
Austin Borgered99f642023-06-01 16:51:35 -0700655void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800656 if (clientToDisconnect.get() != nullptr) {
657 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700658 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800659 // Notify the client of disconnection
660 clientToDisconnect->notifyError(
661 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
662 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800663 clientToDisconnect->disconnect();
664 }
665}
666
Austin Borgered99f642023-06-01 16:51:35 -0700667void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800668 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700669 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
670 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
671 if (res != OK) {
672 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700673 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700674 return;
675 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800676 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700677 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800678}
679
Austin Borgered99f642023-06-01 16:51:35 -0700680void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700681 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
682 Mutex::Autolock al(mTorchStatusMutex);
683 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
684}
685
Austin Borgered99f642023-06-01 16:51:35 -0700686void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800687 int32_t newStrengthLevel) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000688 // Get the device id and app-visible camera id for the given HAL-visible camera id.
689 auto [deviceId, mappedCameraId] =
690 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
691
Rucha Katakwar38284522021-11-10 11:25:21 -0800692 Mutex::Autolock lock(mStatusListenerLock);
693 for (auto& i : mListenerList) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000694 auto ret = i->getListener()->onTorchStrengthLevelChanged(mappedCameraId,
695 newStrengthLevel, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700696 i->handleBinderStatus(ret,
697 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
698 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800699 }
700}
701
Austin Borgered99f642023-06-01 16:51:35 -0700702void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700703 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800704 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700705 __FUNCTION__, cameraId.c_str(), newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800706
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800707 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800708 status_t res = getTorchStatusLocked(cameraId, &status);
709 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700710 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700711 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800712 return;
713 }
714 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800715 return;
716 }
717
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800718 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800719 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800720 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
721 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800722 return;
723 }
724
Ruben Brunkcc776712015-02-17 20:18:47 -0800725 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700726 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700727 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700728 auto iter = mTorchUidMap.find(cameraId);
729 if (iter != mTorchUidMap.end()) {
730 int oldUid = iter->second.second;
731 int newUid = iter->second.first;
732 BatteryNotifier& notifier(BatteryNotifier::getInstance());
733 if (oldUid != newUid) {
734 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800735 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700736 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700737 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800738 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700739 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700740 }
741 iter->second.second = newUid;
742 } else {
743 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800744 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700745 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700746 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700747 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700748 }
749 }
750 }
751 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700752 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800753}
754
Austin Borger249e6592024-03-10 22:28:11 -0700755bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700756 // Returns false if this is not an automotive device type.
757 if (!isAutomotiveDevice())
758 return false;
759
760 // Returns false if no camera id is provided.
Austin Borger1c1bee02023-06-01 16:51:35 -0700761 if (cam_id.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700762 return false;
763
764 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
765 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
766 // This isn't a known camera ID, so it's not a system camera.
767 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
768 return false;
769 }
770
771 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
772 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
773 return false;
774 }
775
776 CameraMetadata cameraInfo;
777 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borger1c1bee02023-06-01 16:51:35 -0700778 cam_id, false, &cameraInfo, false);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700779 if (res != OK){
780 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
781 cam_id.c_str());
782 return false;
783 }
784
785 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
786 if (auto_location.count != 1)
787 return false;
788
789 uint8_t location = auto_location.data.u8[0];
790 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
791 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
792 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
793 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
794 return false;
795 }
796
797 return true;
798}
799
Biswarup Pal37a75182024-01-16 15:53:35 +0000800Status CameraService::getNumberOfCameras(int32_t type, int32_t deviceId, int32_t devicePolicy,
801 int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700802 ATRACE_CALL();
Biswarup Pal37a75182024-01-16 15:53:35 +0000803 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
804 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
805 *numCameras = mVirtualDeviceCameraIdMapper.getNumberOfCameras(deviceId);
806 return Status::ok();
807 }
808
Emilian Peevaee727d2017-05-04 16:35:48 +0100809 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700810 bool hasSystemCameraPermissions =
Austin Borger22c5c852024-03-08 13:31:36 -0800811 hasPermissionsForSystemCamera(std::string(), getCallingPid(),
812 getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700813 switch (type) {
814 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700815 if (hasSystemCameraPermissions) {
816 *numCameras = static_cast<int>(mNormalDeviceIds.size());
817 } else {
818 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
819 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800820 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700821 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700822 if (hasSystemCameraPermissions) {
823 *numCameras = mNumberOfCameras;
824 } else {
825 *numCameras = mNumberOfCamerasWithoutSystemCamera;
826 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800827 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700828 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800829 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700830 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800831 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
832 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700833 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800834 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700835}
836
malikakash73125c62023-07-21 22:44:34 +0000837Status CameraService::remapCameraIds(const hardware::CameraIdRemapping& cameraIdRemapping) {
Austin Borgered99f642023-06-01 16:51:35 -0700838 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -0800839 const int pid = getCallingPid();
840 const int uid = getCallingUid();
malikakash82ed4352023-07-21 22:44:34 +0000841 ALOGE("%s: Permission Denial: can't configure camera ID mapping pid=%d, uid=%d",
842 __FUNCTION__, pid, uid);
843 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
844 "Permission Denial: no permission to configure camera id mapping");
845 }
846 TCameraIdRemapping cameraIdRemappingMap{};
malikakash214f6e62023-08-10 23:50:56 +0000847 binder::Status parseStatus = parseCameraIdRemapping(cameraIdRemapping, &cameraIdRemappingMap);
malikakash82ed4352023-07-21 22:44:34 +0000848 if (!parseStatus.isOk()) {
849 return parseStatus;
850 }
851 remapCameraIds(cameraIdRemappingMap);
852 return Status::ok();
853}
854
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700855Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
Biswarup Pal37a75182024-01-16 15:53:35 +0000856 int32_t deviceId, int32_t devicePolicy,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700857 /* out */
858 hardware::camera2::impl::CameraMetadataNative* request) {
859 ATRACE_CALL();
860
861 if (!flags::feature_combination_query()) {
862 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
863 "Camera subsystem doesn't support this method!");
864 }
865 if (!mInitialized) {
866 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
867 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
868 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
869 }
870
Biswarup Pal37a75182024-01-16 15:53:35 +0000871 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
872 devicePolicy, getCallingUid());
873 if (!cameraIdOptional.has_value()) {
874 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
875 unresolvedCameraId.c_str(), deviceId);
876 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
877 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
878 }
879 std::string cameraId = cameraIdOptional.value();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700880
881 binder::Status res;
882 if (request == nullptr) {
883 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
884 "Camera %s: Error creating default request", cameraId.c_str());
885 return res;
886 }
887 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
888 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
889 cameraId, templateId, &tempId);
890 if (!res.isOk()) {
891 ALOGE("%s: Camera %s: failed to map request Template %d",
892 __FUNCTION__, cameraId.c_str(), templateId);
893 return res;
894 }
895
896 if (shouldRejectSystemCameraConnection(cameraId)) {
897 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
898 "request for system only device %s: ", cameraId.c_str());
899 }
900
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700901 CameraMetadata metadata;
902 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
903 if (err == OK) {
904 request->swap(metadata);
905 } else if (err == BAD_VALUE) {
906 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
907 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
908 cameraId.c_str(), templateId, strerror(-err), err);
909 } else {
910 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
911 "Camera %s: Error creating default request for template %d: %s (%d)",
912 cameraId.c_str(), templateId, strerror(-err), err);
913 }
914 return res;
915}
916
917Status CameraService::isSessionConfigurationWithParametersSupported(
918 const std::string& unresolvedCameraId,
919 const SessionConfiguration& sessionConfiguration,
Biswarup Pal37a75182024-01-16 15:53:35 +0000920 int32_t deviceId, int32_t devicePolicy,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700921 /*out*/
922 bool* supported) {
923 ATRACE_CALL();
924
925 if (!flags::feature_combination_query()) {
926 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
927 "Camera subsystem doesn't support this method!");
928 }
929 if (!mInitialized) {
930 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
931 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
932 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
933 }
934
Biswarup Pal37a75182024-01-16 15:53:35 +0000935 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
936 devicePolicy, getCallingUid());
937 if (!cameraIdOptional.has_value()) {
938 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
939 unresolvedCameraId.c_str(), deviceId);
940 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
941 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
942 }
943 std::string cameraId = cameraIdOptional.value();
944
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700945 if (supported == nullptr) {
946 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
947 unresolvedCameraId.c_str());
948 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
949 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
950 }
951
952 if (shouldRejectSystemCameraConnection(cameraId)) {
953 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
954 "session configuration with parameters support for system only device %s: ",
955 cameraId.c_str());
956 }
957
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700958 *supported = false;
959 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(cameraId.c_str(),
960 sessionConfiguration, /*mOverrideForPerfClass*/false, /*checkSessionParams*/true,
961 supported);
962 binder::Status res;
963 switch (ret) {
964 case OK:
965 // Expected, do nothing.
966 break;
967 case INVALID_OPERATION: {
968 std::string msg = fmt::sprintf(
969 "Camera %s: Session configuration query not supported!",
970 cameraId.c_str());
971 ALOGD("%s: %s", __FUNCTION__, msg.c_str());
972 res = STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
973 }
974
975 break;
976 default: {
977 std::string msg = fmt::sprintf( "Camera %s: Error: %s (%d)", cameraId.c_str(),
978 strerror(-ret), ret);
979 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
980 res = STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT,
981 msg.c_str());
982 }
983 }
984
985 return res;
986}
987
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800988Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +0000989 int targetSdkVersion, bool overrideToPortrait,
990 const SessionConfiguration& sessionConfiguration, int32_t deviceId, int32_t devicePolicy,
991 /*out*/ CameraMetadata* outMetadata) {
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800992 ATRACE_CALL();
993
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800994 if (outMetadata == nullptr) {
995 std::string msg =
996 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
997 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
998 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
999 }
1000
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001001 if (!mInitialized) {
1002 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1003 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
1004 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
1005 }
1006
Biswarup Pal37a75182024-01-16 15:53:35 +00001007 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001008 devicePolicy, getCallingUid());
Biswarup Pal37a75182024-01-16 15:53:35 +00001009 if (!cameraIdOptional.has_value()) {
1010 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001011 unresolvedCameraId.c_str(), deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001012 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1013 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1014 }
1015 std::string cameraId = cameraIdOptional.value();
1016
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001017 if (shouldRejectSystemCameraConnection(cameraId)) {
1018 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1019 "Unable to retrieve camera"
1020 "characteristics for system only device %s: ",
1021 cameraId.c_str());
1022 }
1023
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001024 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1025 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
1026
1027 status_t ret = mCameraProviderManager->getSessionCharacteristics(
1028 cameraId, sessionConfiguration, overrideForPerfClass, overrideToPortrait, outMetadata);
1029
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001030 switch (ret) {
1031 case OK:
1032 // Expected, no handling needed.
1033 break;
1034 case INVALID_OPERATION: {
1035 std::string msg = fmt::sprintf(
1036 "Camera %s: Session characteristics query not supported!",
1037 cameraId.c_str());
1038 ALOGD("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001039 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1040 outMetadata->clear();
1041 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1042 }
1043 break;
1044 case NAME_NOT_FOUND: {
1045 std::string msg = fmt::sprintf(
1046 "Camera %s: Unknown camera ID.",
1047 cameraId.c_str());
1048 ALOGD("%s: %s", __FUNCTION__, msg.c_str());
1049 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1050 outMetadata->clear();
1051 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001052 }
1053 break;
1054 default: {
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001055 std::string msg = fmt::sprintf(
1056 "Unable to retrieve session characteristics for camera device %s: "
1057 "Error: %s (%d)",
1058 cameraId.c_str(), strerror(-ret), ret);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001059 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001060 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1061 outMetadata->clear();
1062 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001063 }
1064 }
1065
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001066 return filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
1067}
1068
1069Status CameraService::filterSensitiveMetadataIfNeeded(
1070 const std::string& cameraId, CameraMetadata* metadata) {
1071 int callingPid = getCallingPid();
1072 int callingUid = getCallingUid();
1073
1074 if (callingPid == getpid()) {
1075 // Caller is cameraserver; no need to remove keys
1076 return Status::ok();
1077 }
1078
1079 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1080 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1081 ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
1082 metadata->clear();
1083 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1084 "Unable to retrieve camera kind for device %s", cameraId.c_str());
1085 }
1086 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
1087 // Attempting to query system only camera without system camera permission would have
1088 // failed the shouldRejectSystemCameraConnection in the caller. So if we get here
1089 // for a system only camera, then the caller has the required permission.
1090 // No need to remove keys
1091 return Status::ok();
1092 }
1093
1094 std::vector<int32_t> tagsRemoved;
Biswarup Pale506e732024-03-27 13:46:20 +00001095 // Get the device id that owns this camera.
1096 auto [cameraOwnerDeviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1097 cameraId);
1098 bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid,
1099 cameraOwnerDeviceId);
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001100 if (hasCameraPermission) {
1101 // Caller has camera permission; no need to remove keys
1102 return Status::ok();
1103 }
1104
1105 status_t ret = metadata->removePermissionEntries(
1106 mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1107 if (ret != OK) {
1108 metadata->clear();
1109 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1110 "Failed to remove camera characteristics needing camera permission "
1111 "for device %s:%s (%d)",
1112 cameraId.c_str(), strerror(-ret), ret);
1113 }
1114
1115 if (!tagsRemoved.empty()) {
1116 ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1117 tagsRemoved.data(), tagsRemoved.size());
1118 if (ret != OK) {
1119 metadata->clear();
1120 return STATUS_ERROR_FMT(
1121 ERROR_INVALID_OPERATION,
1122 "Failed to insert camera keys needing permission for device %s: %s (%d)",
1123 cameraId.c_str(), strerror(-ret), ret);
1124 }
1125 }
1126 return Status::ok();
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001127}
1128
malikakash82ed4352023-07-21 22:44:34 +00001129Status CameraService::parseCameraIdRemapping(
1130 const hardware::CameraIdRemapping& cameraIdRemapping,
malikakash214f6e62023-08-10 23:50:56 +00001131 /* out */ TCameraIdRemapping* cameraIdRemappingMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001132 std::string packageName;
1133 std::string cameraIdToReplace, updatedCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001134 for (const auto& packageIdRemapping: cameraIdRemapping.packageIdRemappings) {
malikakash82ed4352023-07-21 22:44:34 +00001135 packageName = packageIdRemapping.packageName;
malikakash0894f5b2023-08-10 22:46:47 +00001136 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001137 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1138 "CameraIdRemapping: Package name cannot be empty");
1139 }
malikakash214f6e62023-08-10 23:50:56 +00001140 if (packageIdRemapping.cameraIdsToReplace.size()
1141 != packageIdRemapping.updatedCameraIds.size()) {
malikakash82ed4352023-07-21 22:44:34 +00001142 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1143 "CameraIdRemapping: Mismatch in CameraId Remapping lists sizes for package %s",
malikakash73125c62023-07-21 22:44:34 +00001144 packageName.c_str());
malikakash82ed4352023-07-21 22:44:34 +00001145 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001146 for (size_t i = 0; i < packageIdRemapping.cameraIdsToReplace.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -07001147 cameraIdToReplace = packageIdRemapping.cameraIdsToReplace[i];
1148 updatedCameraId = packageIdRemapping.updatedCameraIds[i];
malikakash0894f5b2023-08-10 22:46:47 +00001149 if (cameraIdToReplace.empty() || updatedCameraId.empty()) {
malikakash214f6e62023-08-10 23:50:56 +00001150 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1151 "CameraIdRemapping: Camera Id cannot be empty for package %s",
Austin Borgered99f642023-06-01 16:51:35 -07001152 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001153 }
1154 if (cameraIdToReplace == updatedCameraId) {
1155 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1156 "CameraIdRemapping: CameraIdToReplace cannot be the same"
1157 " as updatedCameraId for %s",
Austin Borgered99f642023-06-01 16:51:35 -07001158 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001159 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001160
1161 // Do not allow any camera remapping that involves a virtual camera.
1162 auto [deviceIdForCameraToReplace, _] =
1163 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1164 cameraIdToReplace);
1165 if (deviceIdForCameraToReplace != kDefaultDeviceId) {
1166 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1167 "CameraIdRemapping: CameraIdToReplace cannot be a virtual camera");
1168 }
1169 [[maybe_unused]] auto [deviceIdForUpdatedCamera, unusedMappedCameraId] =
1170 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(updatedCameraId);
1171 if (deviceIdForUpdatedCamera != kDefaultDeviceId) {
1172 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1173 "CameraIdRemapping: UpdatedCameraId cannot be a virtual camera");
1174 }
1175
malikakash214f6e62023-08-10 23:50:56 +00001176 (*cameraIdRemappingMap)[packageName][cameraIdToReplace] = updatedCameraId;
malikakash82ed4352023-07-21 22:44:34 +00001177 }
1178 }
1179 return Status::ok();
1180}
1181
1182void CameraService::remapCameraIds(const TCameraIdRemapping& cameraIdRemapping) {
1183 // Acquire mServiceLock and prevent other clients from connecting
1184 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1185 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1186
malikakashedb38962023-09-06 00:03:35 +00001187 // Collect all existing clients for camera Ids that are being
1188 // remapped in the new cameraIdRemapping, but only if they were being used by a
1189 // targeted packageName.
malikakash82ed4352023-07-21 22:44:34 +00001190 std::vector<sp<BasicClient>> clientsToDisconnect;
Austin Borgered99f642023-06-01 16:51:35 -07001191 std::vector<std::string> cameraIdsToUpdate;
malikakash82ed4352023-07-21 22:44:34 +00001192 for (const auto& [packageName, injectionMap] : cameraIdRemapping) {
1193 for (auto& [id0, id1] : injectionMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001194 ALOGI("%s: UPDATE:= %s: %s: %s", __FUNCTION__, packageName.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001195 id0.c_str(), id1.c_str());
1196 auto clientDescriptor = mActiveClientManager.get(id0);
1197 if (clientDescriptor != nullptr) {
1198 sp<BasicClient> clientSp = clientDescriptor->getValue();
1199 if (clientSp->getPackageName() == packageName) {
malikakashedb38962023-09-06 00:03:35 +00001200 // This camera is being used by a targeted packageName and
1201 // being remapped to a new camera Id. We should disconnect it.
malikakash82ed4352023-07-21 22:44:34 +00001202 clientsToDisconnect.push_back(clientSp);
1203 cameraIdsToUpdate.push_back(id0);
1204 }
1205 }
1206 }
1207 }
1208
malikakashedb38962023-09-06 00:03:35 +00001209 for (auto& clientSp : clientsToDisconnect) {
malikakashf4c80f22023-09-25 21:50:28 +00001210 // Notify the clients about the disconnection.
1211 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
malikakashedb38962023-09-06 00:03:35 +00001212 CaptureResultExtras{});
1213 }
malikakash82ed4352023-07-21 22:44:34 +00001214
1215 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1216 // blocking other clients from connecting in mServiceLockWrapper if held.
1217 mServiceLock.unlock();
1218
malikakashedb38962023-09-06 00:03:35 +00001219 // Clear calling identity for disconnect() PID checks.
Austin Borger22c5c852024-03-08 13:31:36 -08001220 int64_t token = clearCallingIdentity();
malikakashedb38962023-09-06 00:03:35 +00001221
malikakash82ed4352023-07-21 22:44:34 +00001222 // Disconnect clients.
1223 for (auto& clientSp : clientsToDisconnect) {
malikakashedb38962023-09-06 00:03:35 +00001224 // This also triggers a call to updateStatus() which also reads mCameraIdRemapping
1225 // and requires mCameraIdRemappingLock.
malikakash82ed4352023-07-21 22:44:34 +00001226 clientSp->disconnect();
1227 }
1228
malikakashedb38962023-09-06 00:03:35 +00001229 // Invoke destructors (which call disconnect()) now while we don't hold the mServiceLock.
1230 clientsToDisconnect.clear();
1231
Austin Borger22c5c852024-03-08 13:31:36 -08001232 restoreCallingIdentity(token);
malikakash82ed4352023-07-21 22:44:34 +00001233 mServiceLock.lock();
malikakashedb38962023-09-06 00:03:35 +00001234
1235 {
1236 Mutex::Autolock lock(mCameraIdRemappingLock);
1237 // Update mCameraIdRemapping.
1238 mCameraIdRemapping.clear();
1239 mCameraIdRemapping.insert(cameraIdRemapping.begin(), cameraIdRemapping.end());
1240 }
malikakash82ed4352023-07-21 22:44:34 +00001241}
1242
malikakash22af94c2023-12-04 18:13:14 +00001243Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001244 const std::string& cameraId,
1245 const CameraMetadata& sessionParams) {
1246 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001247 const int pid = getCallingPid();
1248 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001249 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1250 __FUNCTION__, pid, uid);
1251 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1252 "Permission Denial: no permission to inject session params");
1253 }
1254
Biswarup Pal37a75182024-01-16 15:53:35 +00001255 // Do not allow session params injection for a virtual camera.
1256 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1257 if (deviceId != kDefaultDeviceId) {
1258 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1259 "Cannot inject session params for a virtual camera");
1260 }
1261
malikakash22af94c2023-12-04 18:13:14 +00001262 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1263 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1264
1265 auto clientDescriptor = mActiveClientManager.get(cameraId);
1266 if (clientDescriptor == nullptr) {
1267 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1268 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1269 "No active client for camera id %s", cameraId.c_str());
1270 }
1271
1272 sp<BasicClient> clientSp = clientDescriptor->getValue();
1273 status_t res = clientSp->injectSessionParams(sessionParams);
1274
1275 if (res != OK) {
1276 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1277 "Error injecting session params into camera \"%s\": %s (%d)",
1278 cameraId.c_str(), strerror(-res), res);
1279 }
1280 return Status::ok();
1281}
1282
Austin Borgered99f642023-06-01 16:51:35 -07001283std::vector<std::string> CameraService::findOriginalIdsForRemappedCameraId(
1284 const std::string& inputCameraId, int clientUid) {
1285 std::string packageName = getPackageNameFromUid(clientUid);
1286 std::vector<std::string> cameraIds;
malikakash82ed4352023-07-21 22:44:34 +00001287 Mutex::Autolock lock(mCameraIdRemappingLock);
1288 if (auto packageMapIter = mCameraIdRemapping.find(packageName);
1289 packageMapIter != mCameraIdRemapping.end()) {
1290 for (auto& [id0, id1]: packageMapIter->second) {
1291 if (id1 == inputCameraId) {
1292 cameraIds.push_back(id0);
1293 }
1294 }
1295 }
1296 return cameraIds;
1297}
1298
Austin Borgered99f642023-06-01 16:51:35 -07001299std::string CameraService::resolveCameraId(
1300 const std::string& inputCameraId,
malikakashedb38962023-09-06 00:03:35 +00001301 int clientUid,
Austin Borgered99f642023-06-01 16:51:35 -07001302 const std::string& packageName) {
1303 std::string packageNameVal = packageName;
malikakashedb38962023-09-06 00:03:35 +00001304 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001305 packageNameVal = getPackageNameFromUid(clientUid);
1306 }
malikakash65d20692023-09-07 01:06:33 +00001307 if (clientUid < AID_APP_START || packageNameVal.empty()) {
malikakashedb38962023-09-06 00:03:35 +00001308 // We shouldn't remap cameras for processes with system/vendor UIDs.
1309 return inputCameraId;
1310 }
malikakash82ed4352023-07-21 22:44:34 +00001311 Mutex::Autolock lock(mCameraIdRemappingLock);
1312 if (auto packageMapIter = mCameraIdRemapping.find(packageNameVal);
1313 packageMapIter != mCameraIdRemapping.end()) {
malikakash82ed4352023-07-21 22:44:34 +00001314 auto packageMap = packageMapIter->second;
1315 if (auto replacementIdIter = packageMap.find(inputCameraId);
1316 replacementIdIter != packageMap.end()) {
malikakashedb38962023-09-06 00:03:35 +00001317 ALOGI("%s: resolveCameraId: remapping cameraId %s for %s to %s",
malikakash82ed4352023-07-21 22:44:34 +00001318 __FUNCTION__, inputCameraId.c_str(),
malikakashedb38962023-09-06 00:03:35 +00001319 packageNameVal.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001320 replacementIdIter->second.c_str());
1321 return replacementIdIter->second;
1322 }
1323 }
1324 return inputCameraId;
1325}
1326
Biswarup Pal37a75182024-01-16 15:53:35 +00001327std::optional<std::string> CameraService::resolveCameraId(
1328 const std::string& inputCameraId,
1329 int32_t deviceId,
1330 int32_t devicePolicy,
1331 int clientUid,
1332 const std::string& packageName) {
1333 if ((deviceId == kDefaultDeviceId)
1334 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1335 auto [storedDeviceId, _] =
1336 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1337 if (storedDeviceId != kDefaultDeviceId) {
1338 // Trying to access a virtual camera from default-policy device context, we should fail.
1339 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1340 inputCameraId.c_str(), deviceId);
1341 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1342 return std::nullopt;
1343 }
1344 return resolveCameraId(inputCameraId, clientUid, packageName);
1345 }
1346
1347 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1348}
1349
1350Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait, int32_t deviceId,
1351 int32_t devicePolicy, CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001352 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001353 Mutex::Autolock l(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001354 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId, deviceId, devicePolicy);
1355 if (cameraIdStr.empty()) {
1356 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
1357 cameraId, deviceId);
1358 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1359 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1360 }
malikakashedb38962023-09-06 00:03:35 +00001361
Austin Borgered99f642023-06-01 16:51:35 -07001362 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001363 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1364 "characteristics for system only device %s: ", cameraIdStr.c_str());
1365 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001366
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001367 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001368 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001369 return STATUS_ERROR(ERROR_DISCONNECTED,
1370 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001371 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001372 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001373 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001374 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1375 if (hasSystemCameraPermissions) {
1376 cameraIdBound = mNumberOfCameras;
1377 }
1378 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001379 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1380 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001381 }
1382
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001383 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001384 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001385 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borgered99f642023-06-01 16:51:35 -07001386 cameraIdStr, overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001387 if (err != OK) {
1388 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1389 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1390 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001391 logServiceError(std::string("Error retrieving camera info from device ")
1392 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001393 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001394
Ruben Brunkcc776712015-02-17 20:18:47 -08001395 return ret;
1396}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001397
Biswarup Pal37a75182024-01-16 15:53:35 +00001398std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1399 int32_t deviceId, int32_t devicePolicy) {
1400 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1401 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1402 std::optional<std::string> cameraIdOptional =
1403 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1404 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1405 }
1406
1407 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001408 auto callingPid = getCallingPid();
1409 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001410 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1411 callingPid, callingUid, /* checkCameraPermissions= */ false);
1412 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001413 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001414 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001415 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1416 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1417 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001418 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001419 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001420
Biswarup Pal37a75182024-01-16 15:53:35 +00001421 std::string unresolvedCameraId = (*cameraIds)[cameraIdInt];
1422 return resolveCameraId(unresolvedCameraId, getCallingUid());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001423}
1424
Biswarup Pal37a75182024-01-16 15:53:35 +00001425std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1426 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001427 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001428 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001429}
1430
Austin Borgered99f642023-06-01 16:51:35 -07001431Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +00001432 int targetSdkVersion, bool overrideToPortrait, int32_t deviceId, int32_t devicePolicy,
1433 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001434 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001435
Zhijun He2b59be82013-09-25 10:14:30 -07001436 if (!cameraInfo) {
1437 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001438 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001439 }
1440
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001441 if (!mInitialized) {
1442 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001443 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001444 return STATUS_ERROR(ERROR_DISCONNECTED,
1445 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001446 }
1447
Biswarup Pal37a75182024-01-16 15:53:35 +00001448 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
1449 devicePolicy, getCallingUid());
1450 if (!cameraIdOptional.has_value()) {
1451 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1452 unresolvedCameraId.c_str(), deviceId);
1453 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1454 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1455 }
1456 std::string cameraId = cameraIdOptional.value();
1457
Austin Borgered99f642023-06-01 16:51:35 -07001458 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001459 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001460 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001461 }
1462
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001463 bool overrideForPerfClass =
1464 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001465 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001466 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borgered99f642023-06-01 16:51:35 -07001467 cameraId, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001468 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001469 if (res == NAME_NOT_FOUND) {
1470 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001471 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001472 strerror(-res), res);
1473 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001474 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1475 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001476 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001477 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001478 strerror(-res), res);
1479 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001480 }
Emilian Peeve20c6372018-08-14 18:45:53 +01001481
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001482 return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -07001483}
1484
Biswarup Pal37a75182024-01-16 15:53:35 +00001485Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId, int32_t deviceId,
1486 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001487 ATRACE_CALL();
1488 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001489
Biswarup Pal37a75182024-01-16 15:53:35 +00001490 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
1491 devicePolicy, getCallingUid());
1492 if (!cameraIdOptional.has_value()) {
1493 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1494 unresolvedCameraId.c_str(), deviceId);
1495 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1496 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1497 }
1498 std::string cameraId = cameraIdOptional.value();
1499
Rucha Katakwar38284522021-11-10 11:25:21 -08001500 if (!mInitialized) {
1501 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1502 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1503 }
1504
Biswarup Pal37a75182024-01-16 15:53:35 +00001505 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001506 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1507 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1508 }
1509
Austin Borgered99f642023-06-01 16:51:35 -07001510 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001511 if (res != OK) {
1512 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001513 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001514 strerror(-res), res);
1515 }
1516 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1517 return Status::ok();
1518}
1519
Austin Borgered99f642023-06-01 16:51:35 -07001520std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001521 time_t now = time(nullptr);
1522 char formattedTime[64];
1523 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001524 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001525}
1526
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001527Status CameraService::getCameraVendorTagDescriptor(
1528 /*out*/
1529 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001530 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001531 if (!mInitialized) {
1532 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001533 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001534 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001535 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1536 if (globalDescriptor != nullptr) {
1537 *desc = *(globalDescriptor.get());
1538 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001539 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001540}
1541
Emilian Peev71c73a22017-03-21 16:35:51 +00001542Status CameraService::getCameraVendorTagCache(
1543 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1544 ATRACE_CALL();
1545 if (!mInitialized) {
1546 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1547 return STATUS_ERROR(ERROR_DISCONNECTED,
1548 "Camera subsystem not available");
1549 }
1550 sp<VendorTagDescriptorCache> globalCache =
1551 VendorTagDescriptorCache::getGlobalVendorTagCache();
1552 if (globalCache != nullptr) {
1553 *cache = *(globalCache.get());
1554 }
1555 return Status::ok();
1556}
1557
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001558void CameraService::clearCachedVariables() {
1559 BasicClient::BasicClient::sCameraService = nullptr;
1560}
1561
Austin Borgered99f642023-06-01 16:51:35 -07001562std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001563 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001564 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001565
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001566 int deviceVersion = 0;
1567
Emilian Peevf53f66e2017-04-11 14:29:43 +01001568 status_t res;
1569 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001570 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001571 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001572 if (res != OK || transport == IPCTransport::INVALID) {
1573 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001574 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001575 return std::make_pair(-1, IPCTransport::INVALID) ;
1576 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001577 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001578
Emilian Peevf53f66e2017-04-11 14:29:43 +01001579 hardware::CameraInfo info;
1580 if (facing) {
Austin Borgered99f642023-06-01 16:51:35 -07001581 res = mCameraProviderManager->getCameraInfo(cameraId, overrideToPortrait,
Austin Borger18b30a72022-10-27 12:20:29 -07001582 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001583 if (res != OK) {
1584 return std::make_pair(-1, IPCTransport::INVALID);
1585 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001586 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001587 if (orientation) {
1588 *orientation = info.orientation;
1589 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001590 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001591
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001592 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001593}
1594
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001595Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001596 switch(err) {
1597 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001598 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001599 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001600 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1601 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001602 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001603 return STATUS_ERROR(ERROR_DISCONNECTED,
1604 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001605 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001606 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1607 "Camera HAL encountered error %d: %s",
1608 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001609 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001610}
1611
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001612Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001613 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1614 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001615 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001616 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001617 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
malikakash73125c62023-07-21 22:44:34 +00001618 bool forceSlowJpegMode, const std::string& originalCameraId,
1619 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001620 // For HIDL devices
1621 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1622 // Create CameraClient based on device version reported by the HAL.
1623 int deviceVersion = deviceVersionAndTransport.first;
1624 switch(deviceVersion) {
1625 case CAMERA_DEVICE_API_VERSION_1_0:
1626 ALOGE("Camera using old HAL version: %d", deviceVersion);
1627 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1628 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001629 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001630 break;
1631 case CAMERA_DEVICE_API_VERSION_3_0:
1632 case CAMERA_DEVICE_API_VERSION_3_1:
1633 case CAMERA_DEVICE_API_VERSION_3_2:
1634 case CAMERA_DEVICE_API_VERSION_3_3:
1635 case CAMERA_DEVICE_API_VERSION_3_4:
1636 case CAMERA_DEVICE_API_VERSION_3_5:
1637 case CAMERA_DEVICE_API_VERSION_3_6:
1638 case CAMERA_DEVICE_API_VERSION_3_7:
1639 break;
1640 default:
1641 // Should not be reachable
1642 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1643 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1644 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001645 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001646 }
1647 }
1648 if (effectiveApiLevel == API_1) { // Camera1 API route
1649 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001650 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001651 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001652 api1CameraId, facing, sensorOrientation,
Chengfei Taobe683db2023-01-31 18:52:49 +00001653 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait,
1654 forceSlowJpegMode);
1655 ALOGI("%s: Camera1 API (legacy), override to portrait %d, forceSlowJpegMode %d",
1656 __FUNCTION__, overrideToPortrait, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001657 } else { // Camera2 API route
1658 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1659 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001660 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001661 cameraService->mCameraServiceProxyWrapper,
1662 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001663 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
malikakash82ed4352023-07-21 22:44:34 +00001664 overrideForPerfClass, overrideToPortrait, originalCameraId);
Austin Borger18b30a72022-10-27 12:20:29 -07001665 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001666 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001667 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001668}
1669
Austin Borgered99f642023-06-01 16:51:35 -07001670std::string CameraService::toString(std::set<userid_t> intSet) {
1671 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001672 bool first = true;
1673 for (userid_t i : intSet) {
1674 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001675 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001676 first = false;
1677 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001678 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001679 }
1680 }
Austin Borgered99f642023-06-01 16:51:35 -07001681 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001682}
1683
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001684int32_t CameraService::mapToInterface(TorchModeStatus status) {
1685 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1686 switch (status) {
1687 case TorchModeStatus::NOT_AVAILABLE:
1688 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1689 break;
1690 case TorchModeStatus::AVAILABLE_OFF:
1691 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1692 break;
1693 case TorchModeStatus::AVAILABLE_ON:
1694 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1695 break;
1696 default:
1697 ALOGW("Unknown new flash status: %d", status);
1698 }
1699 return serviceStatus;
1700}
1701
1702CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1703 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1704 switch (status) {
1705 case CameraDeviceStatus::NOT_PRESENT:
1706 serviceStatus = StatusInternal::NOT_PRESENT;
1707 break;
1708 case CameraDeviceStatus::PRESENT:
1709 serviceStatus = StatusInternal::PRESENT;
1710 break;
1711 case CameraDeviceStatus::ENUMERATING:
1712 serviceStatus = StatusInternal::ENUMERATING;
1713 break;
1714 default:
1715 ALOGW("Unknown new HAL device status: %d", status);
1716 }
1717 return serviceStatus;
1718}
1719
1720int32_t CameraService::mapToInterface(StatusInternal status) {
1721 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1722 switch (status) {
1723 case StatusInternal::NOT_PRESENT:
1724 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1725 break;
1726 case StatusInternal::PRESENT:
1727 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1728 break;
1729 case StatusInternal::ENUMERATING:
1730 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1731 break;
1732 case StatusInternal::NOT_AVAILABLE:
1733 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1734 break;
1735 case StatusInternal::UNKNOWN:
1736 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1737 break;
1738 default:
1739 ALOGW("Unknown new internal device status: %d", status);
1740 }
1741 return serviceStatus;
1742}
1743
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001744Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001745 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001746
Austin Borgered99f642023-06-01 16:51:35 -07001747 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001748 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001749 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001750 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001751 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1752 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001753 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Chengfei Taobe683db2023-01-31 18:52:49 +00001754 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true,
Austin Borgered99f642023-06-01 16:51:35 -07001755 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001756 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001757 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001758 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001759 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001760}
1761
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001762Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001763 /*out*/
1764 CameraParameters* parameters) {
1765
1766 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1767
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001768 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001769
1770 if (parameters == NULL) {
1771 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001772 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001773 }
1774
malikakashedb38962023-09-06 00:03:35 +00001775 std::string unresolvedCameraId = std::to_string(cameraId);
1776 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08001777 getCallingUid());
Ruben Brunkcc776712015-02-17 20:18:47 -08001778
1779 // Check if we already have parameters
1780 {
1781 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001782 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001783 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001784 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001785 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001786 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001787 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001788 }
1789 CameraParameters p = cameraState->getShimParams();
1790 if (!p.isEmpty()) {
1791 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001792 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001793 }
1794 }
1795
Austin Borger22c5c852024-03-08 13:31:36 -08001796 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001797 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001798 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001799 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001800 // Error already logged by callee
1801 return ret;
1802 }
1803
1804 // Check for parameters again
1805 {
1806 // Scope for service lock
1807 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001808 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001809 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001810 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001811 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001812 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001813 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001814 CameraParameters p = cameraState->getShimParams();
1815 if (!p.isEmpty()) {
1816 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001817 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001818 }
1819 }
1820
Ruben Brunkcc776712015-02-17 20:18:47 -08001821 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1822 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001823 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001824}
1825
Austin Borgered99f642023-06-01 16:51:35 -07001826Status CameraService::validateConnectLocked(const std::string& cameraId,
1827 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001828 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001829
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001830#ifdef __BRILLO__
1831 UNUSED(clientName8);
1832 UNUSED(clientUid);
1833 UNUSED(clientPid);
1834 UNUSED(originalClientPid);
1835#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001836 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1837 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001838 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001839 return allowed;
1840 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001841#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001842
Austin Borger22c5c852024-03-08 13:31:36 -08001843 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001844
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001845 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001846 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1847 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001848 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001849 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001850 }
1851
Ruben Brunkcc776712015-02-17 20:18:47 -08001852 if (getCameraState(cameraId) == nullptr) {
1853 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001854 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001855 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001856 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001857 }
1858
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001859 status_t err = checkIfDeviceIsUsable(cameraId);
1860 if (err != NO_ERROR) {
1861 switch(err) {
1862 case -ENODEV:
1863 case -EBUSY:
1864 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001865 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001866 default:
1867 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001868 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001869 }
1870 }
1871 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001872}
1873
Austin Borgered99f642023-06-01 16:51:35 -07001874Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1875 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001876 /*out*/int& originalClientPid) const {
Austin Borger22c5c852024-03-08 13:31:36 -08001877 int callingPid = getCallingPid();
1878 int callingUid = getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001879
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001880 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001881 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001882 clientUid = callingUid;
1883 } else if (!isTrustedCallingUid(callingUid)) {
1884 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1885 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001886 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1887 "Untrusted caller (calling PID %d, UID %d) trying to "
1888 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001889 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001890 clientName.c_str(), clientPid, clientUid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001891 }
1892
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001893 // Check if we can trust clientPid
1894 if (clientPid == USE_CALLING_PID) {
1895 clientPid = callingPid;
1896 } else if (!isTrustedCallingUid(callingUid)) {
1897 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1898 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001899 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1900 "Untrusted caller (calling PID %d, UID %d) trying to "
1901 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001902 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001903 clientName.c_str(), clientPid, clientUid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001904 }
1905
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001906 if (shouldRejectSystemCameraConnection(cameraId)) {
1907 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1908 cameraId.c_str());
1909 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001910 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001911 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001912 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1913 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001914 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001915 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001916 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001917 }
1918
Biswarup Pale506e732024-03-27 13:46:20 +00001919 // Get the device id that owns this camera.
1920 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1921
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001922 // If it's not calling from cameraserver, check the permission if the
1923 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1924 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001925 bool checkPermissionForCamera =
Biswarup Pale506e732024-03-27 13:46:20 +00001926 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName, deviceId);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001927 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001928 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001929 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001930 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1931 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001932 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001933 }
1934
Svet Ganova453d0d2018-01-11 15:37:58 -08001935 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001936 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001937 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001938 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1939 clientPid, clientUid);
1940 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001941 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1942 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001943 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001944 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001945 }
1946
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001947 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1948 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1949 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1950 if ((!isAutomotivePrivilegedClient(callingUid) ||
1951 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1952 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001953 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1954 return STATUS_ERROR_FMT(ERROR_DISABLED,
1955 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001956 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001957 }
1958
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001959 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1960 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001961 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001962 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001963
Ruben Brunk6267b532015-04-30 17:44:07 -07001964 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001965
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001966 // For non-system clients : Only allow clients who are being used by the current foreground
1967 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08001968 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001969 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001970 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1971 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001972 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001973 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1974 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001975 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001976 }
1977
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001978 if (flags::camera_hsum_permission()) {
1979 // If the System User tries to access the camera when the device is running in
1980 // headless system user mode, ensure that client has the required permission
1981 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07001982 if (isHeadlessSystemUserMode()
1983 && (clientUserId == USER_SYSTEM)
1984 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001985 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
1986 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1987 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1988 User without camera headless system user permission",
Austin Borger249e6592024-03-10 22:28:11 -07001989 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001990 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001991 }
1992
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001993 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001994}
1995
Austin Borgered99f642023-06-01 16:51:35 -07001996status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001997 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001998 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001999 if (cameraState == nullptr) {
2000 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07002001 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002002 return -ENODEV;
2003 }
2004
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002005 StatusInternal currentStatus = cameraState->getStatus();
2006 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002007 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07002008 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002009 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002010 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002011 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07002012 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002013 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07002014 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002015
Ruben Brunkcc776712015-02-17 20:18:47 -08002016 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08002017}
2018
Ruben Brunkcc776712015-02-17 20:18:47 -08002019void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002020 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08002021
Ruben Brunkcc776712015-02-17 20:18:47 -08002022 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002023 auto clientDescriptor =
2024 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002025 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08002026 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
2027
2028 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002029 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08002030
2031 if (evicted.size() > 0) {
2032 // This should never happen - clients should already have been removed in disconnect
2033 for (auto& i : evicted) {
2034 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07002035 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002036 }
2037
2038 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
2039 __FUNCTION__);
2040 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002041
2042 // And register a death notification for the client callback. Do
2043 // this last to avoid Binder policy where a nested Binder
2044 // transaction might be pre-empted to service the client death
2045 // notification if the client process dies before linkToDeath is
2046 // invoked.
2047 sp<IBinder> remoteCallback = client->getRemote();
2048 if (remoteCallback != nullptr) {
2049 remoteCallback->linkToDeath(this);
2050 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002051}
2052
Austin Borgered99f642023-06-01 16:51:35 -07002053status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
2054 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
2055 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08002056 /*out*/
2057 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07002058 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002059 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08002060 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002061 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08002062 DescriptorPtr clientDescriptor;
2063 {
2064 if (effectiveApiLevel == API_1) {
2065 // If we are using API1, any existing client for this camera ID with the same remote
2066 // should be returned rather than evicted to allow MediaRecorder to work properly.
2067
2068 auto current = mActiveClientManager.get(cameraId);
2069 if (current != nullptr) {
2070 auto clientSp = current->getValue();
2071 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002072 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07002073 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002074 " API level, evicting prior client...");
2075 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002076 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002077 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002078 *client = clientSp;
2079 return NO_ERROR;
2080 }
2081 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002082 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002083 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08002084
Ruben Brunkcc776712015-02-17 20:18:47 -08002085 // Get state for the given cameraId
2086 auto state = getCameraState(cameraId);
2087 if (state == nullptr) {
2088 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07002089 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002090 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07002091 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002092 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002093
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002094 sp<IServiceManager> sm = defaultServiceManager();
2095 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08002096 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002097 // If processinfo service is not available and the client is automotive privileged
2098 // client used for safety critical uses cases such as rear-view and surround-view which
2099 // needs to be available before android boot completes, then use the hardcoded values
2100 // for the process state and priority score. As this scenario is before android system
2101 // services are up and client is native client, hence using NATIVE_ADJ as the priority
2102 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
2103 // visible on the top.
2104 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2105 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2106 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
2107 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
2108 } else {
2109 // Get current active client PIDs
2110 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
2111 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002112
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002113 std::vector<int> priorityScores(ownerPids.size());
2114 std::vector<int> states(ownerPids.size());
2115
2116 // Get priority scores of all active PIDs
2117 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
2118 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
2119 if (err != OK) {
2120 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
2121 return err;
2122 }
2123
2124 // Update all active clients' priorities
2125 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
2126 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
2127 pidToPriorityMap.emplace(ownerPids[i],
2128 resource_policy::ClientPriority(priorityScores[i], states[i],
2129 /* isVendorClient won't get copied over*/ false,
2130 /* oomScoreOffset won't get copied over*/ 0));
2131 }
2132 mActiveClientManager.updatePriorities(pidToPriorityMap);
2133
2134 int32_t actualScore = priorityScores[priorityScores.size() - 1];
2135 int32_t actualState = states[states.size() - 1];
2136
2137 // Make descriptor for incoming client. We store the oomScoreOffset
2138 // since we might need it later on new handleEvictionsLocked and
2139 // ProcessInfoService would not take that into account.
2140 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2141 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2142 state->getConflicting(), actualScore, clientPid, actualState,
2143 oomScoreOffset, systemNativeClient);
2144 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002145
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002146 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
2147
Ruben Brunkcc776712015-02-17 20:18:47 -08002148 // Find clients that would be evicted
2149 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
2150
2151 // If the incoming client was 'evicted,' higher priority clients have the camera in the
2152 // background, so we cannot do evictions
2153 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2154 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2155 " priority).", clientPid);
2156
2157 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002158 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002159 auto incompatibleClients =
2160 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2161
Austin Borgered99f642023-06-01 16:51:35 -07002162 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2163 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2164 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002165 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002166
2167 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002168 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002169 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002170 i->getKey().c_str(),
2171 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002172 i->getOwnerId(), i->getPriority().getScore(),
2173 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002174 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002175 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2176 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002177 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002178 }
2179
2180 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002181 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002182 mEventLog.add(msg);
2183
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002184 auto current = mActiveClientManager.get(cameraId);
2185 if (current != nullptr) {
2186 return -EBUSY; // CAMERA_IN_USE
2187 } else {
2188 return -EUSERS; // MAX_CAMERAS_IN_USE
2189 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002190 }
2191
2192 for (auto& i : evicted) {
2193 sp<BasicClient> clientSp = i->getValue();
2194 if (clientSp.get() == nullptr) {
2195 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2196
2197 // TODO: Remove this
2198 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2199 __FUNCTION__);
2200 mActiveClientManager.remove(i);
2201 continue;
2202 }
2203
2204 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002205 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002206 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002207
Ruben Brunkcc776712015-02-17 20:18:47 -08002208 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002209 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002210 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2211 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002212 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002213 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002214 i->getPriority().getState(), cameraId.c_str(),
2215 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002216 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002217
2218 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002219 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002220 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002221 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002222 }
2223
Ruben Brunkcc776712015-02-17 20:18:47 -08002224 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2225 // other clients from connecting in mServiceLockWrapper if held
2226 mServiceLock.unlock();
2227
2228 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002229 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002230
2231 // Destroy evicted clients
2232 for (auto& i : evictedClients) {
2233 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002234 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002235 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002236
Austin Borger22c5c852024-03-08 13:31:36 -08002237 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002238
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002239 for (const auto& i : evictedClients) {
2240 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002241 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002242 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2243 if (ret == TIMED_OUT) {
2244 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002245 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2246 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002247 return -EBUSY;
2248 }
2249 if (ret != NO_ERROR) {
2250 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002251 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2252 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002253 return ret;
2254 }
2255 }
2256
2257 evictedClients.clear();
2258
Ruben Brunkcc776712015-02-17 20:18:47 -08002259 // Once clients have been disconnected, relock
2260 mServiceLock.lock();
2261
2262 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2263 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2264 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002265 }
2266
Ruben Brunkcc776712015-02-17 20:18:47 -08002267 *partial = clientDescriptor;
2268 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002269}
2270
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002271Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002272 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002273 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07002274 const std::string& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002275 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08002276 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002277 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07002278 bool overrideToPortrait,
Chengfei Taobe683db2023-01-31 18:52:49 +00002279 bool forceSlowJpegMode,
Biswarup Pal37a75182024-01-16 15:53:35 +00002280 int32_t deviceId,
2281 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002282 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002283 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002284 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002285 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002286
Biswarup Pal37a75182024-01-16 15:53:35 +00002287 std::string cameraIdStr = cameraIdIntToStr(api1CameraId, deviceId, devicePolicy);
2288 if (cameraIdStr.empty()) {
2289 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
2290 api1CameraId, deviceId);
2291 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2292 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2293 }
malikakashedb38962023-09-06 00:03:35 +00002294
Ruben Brunkcc776712015-02-17 20:18:47 -08002295 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002296 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
2297 clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002298 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002299 overrideToPortrait, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002300
Biswarup Pal37a75182024-01-16 15:53:35 +00002301 if (!ret.isOk()) {
2302 logRejected(cameraIdStr, getCallingPid(), clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002303 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002304 }
2305
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002306 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002307
2308 const sp<IServiceManager> sm(defaultServiceManager());
2309 const auto& mActivityManager = getActivityManager();
2310 if (mActivityManager) {
2311 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002312 getCallingUid(),
2313 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002314 }
2315
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002316 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002317}
2318
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002319bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2320 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002321 // If the client is not a vendor client, don't add listener if
2322 // a) the camera is a publicly hidden secure camera OR
2323 // b) the camera is a system only camera and the client doesn't
2324 // have android.permission.SYSTEM_CAMERA permissions.
2325 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2326 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002327 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002328 return true;
2329 }
2330 return false;
2331}
2332
Austin Borgered99f642023-06-01 16:51:35 -07002333bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002334 // Rules for rejection:
2335 // 1) If cameraserver tries to access this camera device, accept the
2336 // connection.
2337 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002338 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002339 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2340 // and the serving thread is a non hwbinder thread, the client must have
2341 // android.permission.SYSTEM_CAMERA permissions to connect.
2342
Austin Borger22c5c852024-03-08 13:31:36 -08002343 int cPid = getCallingPid();
2344 int cUid = getCallingUid();
2345 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002346 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2347 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002348 // This isn't a known camera ID, so it's not a system camera
2349 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2350 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002351 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002352
2353 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002354 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002355 return false;
2356 }
2357 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002358 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002359 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2360 return true;
2361 }
2362 // (3) Here we only check for permissions if it is a system only camera device. This is since
2363 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2364 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2365 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002366 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002367 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002368 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2369 cameraId.c_str());
2370 return true;
2371 }
2372
2373 return false;
2374}
2375
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002376Status CameraService::connectDevice(
2377 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002378 const std::string& unresolvedCameraId,
2379 const std::string& clientPackageName,
2380 const std::optional<std::string>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002381 int clientUid, int oomScoreOffset, int targetSdkVersion,
Biswarup Pal37a75182024-01-16 15:53:35 +00002382 bool overrideToPortrait, int32_t deviceId, int32_t devicePolicy,
Ruben Brunkcc776712015-02-17 20:18:47 -08002383 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002384 sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002385 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002386 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002387 sp<CameraDeviceClient> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002388 std::string clientPackageNameAdj = clientPackageName;
Austin Borger22c5c852024-03-08 13:31:36 -08002389 int callingPid = getCallingPid();
2390 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002391 bool systemNativeClient = false;
Austin Borger22c5c852024-03-08 13:31:36 -08002392 if (callerHasSystemUid() && (clientPackageNameAdj.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002393 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borgered99f642023-06-01 16:51:35 -07002394 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002395 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002396 }
Austin Borger249e6592024-03-10 22:28:11 -07002397
Biswarup Pal37a75182024-01-16 15:53:35 +00002398 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
2399 devicePolicy, callingUid, clientPackageNameAdj);
2400 if (!cameraIdOptional.has_value()) {
2401 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
2402 unresolvedCameraId.c_str(), deviceId);
2403 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2404 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2405 }
2406 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002407
2408 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002409 std::string msg =
2410 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
2411 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
2412 cameraId.c_str());
2413 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2414 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002415 }
2416
Austin Borger9bfa0a72022-08-03 17:50:40 -07002417 userid_t clientUserId = multiuser_get_user_id(clientUid);
Austin Borger9bfa0a72022-08-03 17:50:40 -07002418 if (clientUid == USE_CALLING_UID) {
2419 clientUserId = multiuser_get_user_id(callingUid);
2420 }
2421
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002422 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2423 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002424 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2425 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002426 std::string msg = "Camera disabled by device policy";
2427 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2428 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002429 }
2430
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002431 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002432 if (oomScoreOffset > 0
2433 && !hasPermissionsForSystemCamera(cameraId, callingPid,
Austin Borger249e6592024-03-10 22:28:11 -07002434 callingUid)
2435 && !isTrustedCallingUid(callingUid)) {
Austin Borgered99f642023-06-01 16:51:35 -07002436 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002437 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07002438 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2439 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2440 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002441 }
2442
Austin Borgered99f642023-06-01 16:51:35 -07002443 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
2444 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002445 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
malikakash73125c62023-07-21 22:44:34 +00002446 targetSdkVersion, overrideToPortrait, /*forceSlowJpegMode*/false, unresolvedCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002447 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002448
Biswarup Pal37a75182024-01-16 15:53:35 +00002449 if (!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002450 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002451 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002452 }
2453
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002454 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002455 Mutex::Autolock lock(mServiceLock);
2456
2457 // Clear the previous cached logs and reposition the
2458 // file offset to beginning of the file to log new data.
2459 // If either truncate or lseek fails, close the previous file and create a new one.
2460 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2461 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2462 // Close the previous memfd.
2463 close(mMemFd);
2464 // If failure to wipe the data, then create a new file and
2465 // assign the new value to mMemFd.
2466 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2467 if (mMemFd == -1) {
2468 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2469 }
2470 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002471 const sp<IServiceManager> sm(defaultServiceManager());
2472 const auto& mActivityManager = getActivityManager();
2473 if (mActivityManager) {
2474 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002475 callingUid,
2476 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002477 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002478 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002479}
2480
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002481bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2482 int callingPid, int callingUid) {
2483 if (!isAutomotiveDevice()) {
2484 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2485 }
2486
2487 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2488 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2489 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2490 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2491 "using camera %s", callingUid, cam_id.c_str());
2492 return false;
2493 }
2494
2495 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2496 return true;
2497 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2498 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002499 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2500 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002501 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2502 return false;
2503 } else {
2504 return true;
2505 }
2506 }
2507 return false;
2508}
2509
Austin Borgered99f642023-06-01 16:51:35 -07002510std::string CameraService::getPackageNameFromUid(int clientUid) {
2511 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002512
Avichal Rakesh5788fec2024-03-15 14:39:20 -07002513 sp<IPermissionController> permCtrl;
2514 if (flags::cache_permission_services()) {
2515 permCtrl = getPermissionController();
2516 } else {
2517 sp<IServiceManager> sm = defaultServiceManager();
2518#pragma clang diagnostic push
2519#pragma clang diagnostic ignored "-Wdeprecated-declarations"
2520 // Using deprecated function to preserve functionality until the
2521 // cache_permission_services flag is removed.
2522 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
2523#pragma clang diagnostic pop
2524 if (binder == 0) {
2525 ALOGE("Cannot get permission service");
2526 permCtrl = nullptr;
2527 } else {
2528 permCtrl = interface_cast<IPermissionController>(binder);
2529 }
2530 }
2531
2532 if (permCtrl == nullptr) {
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002533 // Return empty package name and the further interaction
2534 // with camera will likely fail
2535 return packageName;
2536 }
2537
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002538 Vector<String16> packages;
2539
2540 permCtrl->getPackagesForUid(clientUid, packages);
2541
2542 if (packages.isEmpty()) {
2543 ALOGE("No packages for calling UID %d", clientUid);
2544 // Return empty package name and the further interaction
2545 // with camera will likely fail
2546 return packageName;
2547 }
2548
2549 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002550 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002551
2552 return packageName;
2553}
2554
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002555template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002556Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2557 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2558 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002559 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002560 bool overrideToPortrait, bool forceSlowJpegMode, const std::string& originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002561 /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002562 binder::Status ret = binder::Status::ok();
2563
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002564 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002565 std::string clientPackageName;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002566 int packageUid = (clientUid == USE_CALLING_UID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002567 getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002568 if (clientPackageNameMaybe.size() <= 0) {
2569 // NDK calls don't come with package names, but we need one for various cases.
2570 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2571 // do exist. For all authentication cases, all packages under the same UID get the
2572 // same permissions, so picking any associated package name is sufficient. For some
2573 // other cases, this may give inaccurate names for clients in logs.
2574 isNonSystemNdk = true;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002575 clientPackageName = getPackageNameFromUid(packageUid);
2576 } else {
2577 clientPackageName = clientPackageNameMaybe;
2578 }
2579
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002580 int originalClientPid = 0;
2581
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002582 int packagePid = (clientPid == USE_CALLING_PID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002583 getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002584 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002585 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002586 static_cast<int>(effectiveApiLevel));
2587
Shuzhen Wang316781a2020-08-18 18:11:01 -07002588 nsecs_t openTimeNs = systemTime();
2589
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002590 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002591 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002592 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002593
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002594 {
2595 // Acquire mServiceLock and prevent other clients from connecting
2596 std::unique_ptr<AutoConditionLock> lock =
2597 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2598
2599 if (lock == nullptr) {
2600 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2601 , clientPid);
2602 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2603 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002604 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002605 }
2606
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002607 // Enforce client permissions and do basic validity checks
Biswarup Pal37a75182024-01-16 15:53:35 +00002608 if (!(ret = validateConnectLocked(cameraId, clientPackageName,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002609 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2610 return ret;
2611 }
2612
2613 // Check the shim parameters after acquiring lock, if they have already been updated and
2614 // we were doing a shim update, return immediately
2615 if (shimUpdateOnly) {
2616 auto cameraState = getCameraState(cameraId);
2617 if (cameraState != nullptr) {
2618 if (!cameraState->getShimParams().isEmpty()) return ret;
2619 }
2620 }
2621
2622 status_t err;
2623
2624 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002625 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002626 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002627 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2628 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002629 switch (err) {
2630 case -ENODEV:
2631 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2632 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002633 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002634 case -EBUSY:
2635 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2636 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002637 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002638 case -EUSERS:
2639 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2640 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002641 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002642 default:
2643 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2644 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002645 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002646 }
2647 }
2648
2649 if (clientTmp.get() != nullptr) {
2650 // Handle special case for API1 MediaRecorder where the existing client is returned
2651 device = static_cast<CLIENT*>(clientTmp.get());
2652 return ret;
2653 }
2654
2655 // give flashlight a chance to close devices if necessary.
2656 mFlashlight->prepareDeviceOpen(cameraId);
2657
Austin Borger18b30a72022-10-27 12:20:29 -07002658 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002659 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07002660 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
2661 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002662 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002663 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002664 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002665 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002666 }
2667
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002668 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002669 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002670 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002671 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002672 clientFeatureId, cameraId, api1CameraId, facing,
2673 orientation, clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002674 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
malikakash82ed4352023-07-21 22:44:34 +00002675 overrideToPortrait, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002676 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002677 return ret;
2678 }
2679 client = static_cast<CLIENT*>(tmp.get());
2680
2681 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2682 __FUNCTION__);
2683
Austin Borgered99f642023-06-01 16:51:35 -07002684 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002685 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002686 if (err != OK) {
2687 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002688 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002689 mServiceLock.unlock();
2690 client->disconnect();
2691 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002692 switch(err) {
2693 case BAD_VALUE:
2694 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002695 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002696 case -EBUSY:
2697 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002698 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002699 case -EUSERS:
2700 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2701 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002702 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002703 case PERMISSION_DENIED:
2704 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002705 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002706 case -EACCES:
2707 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002708 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002709 case -ENODEV:
2710 default:
2711 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002712 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002713 strerror(-err), err);
2714 }
2715 }
2716
2717 // Update shim paremeters for legacy clients
2718 if (effectiveApiLevel == API_1) {
2719 // Assume we have always received a Client subclass for API1
2720 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2721 String8 rawParams = shimClient->getParameters();
2722 CameraParameters params(rawParams);
2723
2724 auto cameraState = getCameraState(cameraId);
2725 if (cameraState != nullptr) {
2726 cameraState->setShimParams(params);
2727 } else {
2728 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002729 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002730 }
2731 }
2732
Ravneetaeb20dc2022-03-30 05:33:03 +00002733 // Enable/disable camera service watchdog
2734 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2735
Emilian Peev6d45db82024-01-18 20:11:54 +00002736 CameraMetadata chars;
2737 bool rotateAndCropSupported = true;
2738 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
2739 &chars, overrideToPortrait);
2740 if (err == OK) {
2741 auto availableRotateCropEntry = chars.find(
2742 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2743 if (availableRotateCropEntry.count <= 1) {
2744 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002745 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002746 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002747 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2748 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002749 }
2750
Emilian Peev6d45db82024-01-18 20:11:54 +00002751 if (rotateAndCropSupported) {
2752 // Set rotate-and-crop override behavior
2753 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2754 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
2755 } else if (overrideToPortrait && portraitRotation != 0) {
2756 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2757 switch (portraitRotation) {
2758 case 90:
2759 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2760 break;
2761 case 180:
2762 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2763 break;
2764 case 270:
2765 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2766 break;
2767 default:
2768 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2769 break;
2770 }
2771 client->setRotateAndCropOverride(rotateAndCropMode);
2772 } else {
2773 client->setRotateAndCropOverride(
2774 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2775 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2776 }
2777 }
2778
2779 bool autoframingSupported = true;
2780 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2781 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2782 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2783 autoframingSupported = false;
2784 }
2785
2786 if (autoframingSupported) {
2787 // Set autoframing override behaviour
2788 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2789 client->setAutoframingOverride(mOverrideAutoframingMode);
2790 } else {
2791 client->setAutoframingOverride(
2792 mCameraServiceProxyWrapper->getAutoframingOverride(
2793 clientPackageName));
2794 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002795 }
2796
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002797 bool isCameraPrivacyEnabled;
2798 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002799 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002800 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2801 toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2802 } else {
2803 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002804 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002805 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002806
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002807 if (client->supportsCameraMute()) {
2808 client->setCameraMute(
2809 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2810 } else if (isCameraPrivacyEnabled) {
2811 // no camera mute supported, but privacy is on! => disconnect
2812 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2813 client->getPackageName().c_str(), cameraId.c_str());
2814 // Do not hold mServiceLock while disconnecting clients, but
2815 // retain the condition blocking other clients from connecting
2816 // in mServiceLockWrapper if held.
2817 mServiceLock.unlock();
2818 // Clear caller identity temporarily so client disconnect PID
2819 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002820 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002821 // Note AppOp to trigger the "Unblock" dialog
2822 client->noteAppOp();
2823 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002824 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002825 // Reacquire mServiceLock
2826 mServiceLock.lock();
2827
2828 return STATUS_ERROR_FMT(ERROR_DISABLED,
2829 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002830 }
2831
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002832 if (shimUpdateOnly) {
2833 // If only updating legacy shim parameters, immediately disconnect client
2834 mServiceLock.unlock();
2835 client->disconnect();
2836 mServiceLock.lock();
2837 } else {
2838 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002839 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002840 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002841
2842 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002843 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002844 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002845 } // lock is destroyed, allow further connect calls
2846
2847 // Important: release the mutex here so the client can call back into the service from its
2848 // destructor (can be at the end of the call)
2849 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002850
2851 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002852 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002853 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002854
Cliff Wud3a05312021-04-26 23:07:31 +08002855 {
2856 Mutex::Autolock lock(mInjectionParametersLock);
2857 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2858 mInjectionInitPending = false;
2859 status_t res = NO_ERROR;
2860 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2861 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002862 sp<BasicClient> clientSp = clientDescriptor->getValue();
2863 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2864 if(res != OK) {
2865 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2866 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002867 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002868 }
2869 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002870 if (res != OK) {
2871 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2872 }
2873 } else {
2874 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002875 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002876 res = NO_INIT;
2877 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2878 }
2879 }
2880 }
2881
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002882 return ret;
2883}
2884
Austin Borgered99f642023-06-01 16:51:35 -07002885status_t CameraService::addOfflineClient(const std::string &cameraId,
2886 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002887 if (offlineClient.get() == nullptr) {
2888 return BAD_VALUE;
2889 }
2890
2891 {
2892 // Acquire mServiceLock and prevent other clients from connecting
2893 std::unique_ptr<AutoConditionLock> lock =
2894 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2895
2896 if (lock == nullptr) {
2897 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2898 , __FUNCTION__, offlineClient->getClientPid());
2899 return TIMED_OUT;
2900 }
2901
2902 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2903 if (onlineClientDesc.get() == nullptr) {
2904 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2905 cameraId.c_str());
2906 return BAD_VALUE;
2907 }
2908
2909 // Offline clients do not evict or conflict with other online devices. Resource sharing
2910 // conflicts are handled by the camera provider which will either succeed or fail before
2911 // reaching this method.
2912 const auto& onlinePriority = onlineClientDesc->getPriority();
2913 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2914 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002915 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002916 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002917 // native clients don't have offline processing support.
2918 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002919 if (offlineClientDesc == nullptr) {
2920 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2921 return BAD_VALUE;
2922 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002923
2924 // Allow only one offline device per camera
2925 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2926 if (!incompatibleClients.empty()) {
2927 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2928 return BAD_VALUE;
2929 }
2930
Austin Borgered99f642023-06-01 16:51:35 -07002931 std::string monitorTags = isClientWatched(offlineClient.get())
2932 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002933 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002934 if (err != OK) {
2935 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2936 return err;
2937 }
2938
2939 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2940 if (evicted.size() > 0) {
2941 for (auto& i : evicted) {
2942 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002943 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002944 }
2945
2946 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2947 "properly", __FUNCTION__);
2948
2949 return BAD_VALUE;
2950 }
2951
2952 logConnectedOffline(offlineClientDesc->getKey(),
2953 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002954 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002955
2956 sp<IBinder> remoteCallback = offlineClient->getRemote();
2957 if (remoteCallback != nullptr) {
2958 remoteCallback->linkToDeath(this);
2959 }
2960 } // lock is destroyed, allow further connect calls
2961
2962 return OK;
2963}
2964
Austin Borgered99f642023-06-01 16:51:35 -07002965Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +00002966 int32_t torchStrength, const sp<IBinder>& clientBinder, int32_t deviceId,
2967 int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002968 Mutex::Autolock lock(mServiceLock);
2969
2970 ATRACE_CALL();
2971 if (clientBinder == nullptr) {
2972 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2973 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2974 "Torch client binder in null.");
2975 }
2976
Austin Borger22c5c852024-03-08 13:31:36 -08002977 int uid = getCallingUid();
Biswarup Pal37a75182024-01-16 15:53:35 +00002978 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
2979 devicePolicy, uid);
2980 if (!cameraIdOptional.has_value()) {
2981 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
2982 unresolvedCameraId.c_str(), deviceId);
2983 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2984 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2985 }
2986 std::string cameraId = cameraIdOptional.value();
2987
Austin Borgered99f642023-06-01 16:51:35 -07002988 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002989 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002990 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002991 }
2992
2993 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002994 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002995 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002996 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002997 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002998 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002999 }
3000
3001 StatusInternal cameraStatus = state->getStatus();
3002 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
3003 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07003004 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08003005 (int)cameraStatus);
3006 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003007 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003008 }
3009
3010 {
3011 Mutex::Autolock al(mTorchStatusMutex);
3012 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003013 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08003014 if (err != OK) {
3015 if (err == NAME_NOT_FOUND) {
3016 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003017 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003018 }
3019 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003020 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003021 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
3022 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003023 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08003024 }
3025
3026 if (status == TorchModeStatus::NOT_AVAILABLE) {
3027 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
3028 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003029 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003030 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3031 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003032 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003033 } else {
3034 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003035 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003036 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3037 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003038 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003039 }
3040 }
3041 }
3042
3043 {
3044 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003045 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08003046 }
3047 // Check if the current torch strength level is same as the new one.
3048 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07003049 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003050
Austin Borgered99f642023-06-01 16:51:35 -07003051 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003052
3053 if (err != OK) {
3054 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003055 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08003056 switch (err) {
3057 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003058 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
3059 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003060 errorCode = ERROR_ILLEGAL_ARGUMENT;
3061 break;
3062 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003063 msg = fmt::sprintf("Camera \"%s\" is in use",
3064 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003065 errorCode = ERROR_CAMERA_IN_USE;
3066 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08003067 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07003068 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08003069 "valid range.", torchStrength);
3070 errorCode = ERROR_ILLEGAL_ARGUMENT;
3071 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08003072 default:
Austin Borgered99f642023-06-01 16:51:35 -07003073 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08003074 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08003075 }
Austin Borgered99f642023-06-01 16:51:35 -07003076 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3077 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003078 }
3079
3080 {
3081 // update the link to client's death
3082 // Store the last client that turns on each camera's torch mode.
3083 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003084 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08003085 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003086 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08003087 } else {
3088 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
3089 mTorchClientMap.replaceValueAt(index, clientBinder);
3090 }
3091 clientBinder->linkToDeath(this);
3092 }
3093
Austin Borger22c5c852024-03-08 13:31:36 -08003094 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08003095 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07003096 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08003097 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07003098 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003099 }
3100 return Status::ok();
3101}
3102
malikakash73125c62023-07-21 22:44:34 +00003103Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Biswarup Pal37a75182024-01-16 15:53:35 +00003104 const sp<IBinder>& clientBinder, int32_t deviceId, int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003105 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003106
3107 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07003108 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003109 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003110 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
3111 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003112 }
3113
Austin Borger22c5c852024-03-08 13:31:36 -08003114 int uid = getCallingUid();
Biswarup Pal37a75182024-01-16 15:53:35 +00003115 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
3116 devicePolicy, uid);
3117 if (!cameraIdOptional.has_value()) {
3118 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
3119 unresolvedCameraId.c_str(), deviceId);
3120 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3121 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3122 }
3123 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003124
Austin Borgered99f642023-06-01 16:51:35 -07003125 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003126 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07003127 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003128 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003129 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07003130 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003131 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07003132 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003133 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003134 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003135 }
3136
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003137 StatusInternal cameraStatus = state->getStatus();
3138 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003139 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07003140 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
3141 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003142 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003143 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003144 }
3145
3146 {
3147 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003148 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003149 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003150 if (err != OK) {
3151 if (err == NAME_NOT_FOUND) {
3152 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003153 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003154 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003155 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003156 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003157 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07003158 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003159 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003160 }
3161
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003162 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003163 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003164 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003165 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003166 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3167 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003168 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003169 } else {
3170 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003171 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003172 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3173 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003174 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003175 }
3176 }
3177 }
3178
Ruben Brunk99e69712015-05-26 17:25:07 -07003179 {
3180 // Update UID map - this is used in the torch status changed callbacks, so must be done
3181 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003182 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003183 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003184 }
3185
Austin Borgered99f642023-06-01 16:51:35 -07003186 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003187
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003188 if (err != OK) {
3189 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003190 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003191 switch (err) {
3192 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003193 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3194 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003195 errorCode = ERROR_ILLEGAL_ARGUMENT;
3196 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003197 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003198 msg = fmt::sprintf("Camera \"%s\" is in use",
3199 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003200 errorCode = ERROR_CAMERA_IN_USE;
3201 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003202 default:
Austin Borgered99f642023-06-01 16:51:35 -07003203 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003204 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003205 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003206 errorCode = ERROR_INVALID_OPERATION;
3207 }
Austin Borgered99f642023-06-01 16:51:35 -07003208 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3209 logServiceError(msg, errorCode);
3210 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003211 }
3212
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003213 {
3214 // update the link to client's death
3215 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003216 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003217 if (enabled) {
3218 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003219 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003220 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003221 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003222 mTorchClientMap.replaceValueAt(index, clientBinder);
3223 }
3224 clientBinder->linkToDeath(this);
3225 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003226 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003227 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003228 }
3229
Austin Borger22c5c852024-03-08 13:31:36 -08003230 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003231 std::string torchState = enabled ? "on" : "off";
3232 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3233 torchState.c_str(), clientPid);
3234 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003235 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003236}
3237
Austin Borgered99f642023-06-01 16:51:35 -07003238void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3239 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3240 mTorchUidMap[cameraId].first = uid;
3241 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003242 } else {
3243 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003244 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003245 }
3246}
3247
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003248Status CameraService::notifySystemEvent(int32_t eventId,
3249 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003250 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003251 const int selfPid = getpid();
3252
3253 // Permission checks
3254 if (pid != selfPid) {
3255 // Ensure we're being called by system_server, or similar process with
3256 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003257 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003258 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003259 ALOGE("Permission Denial: cannot send updates to camera service about system"
3260 " events from pid=%d, uid=%d", pid, uid);
3261 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003262 "No permission to send updates to camera service about system events"
3263 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003264 }
3265 }
3266
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003267 ATRACE_CALL();
3268
Ruben Brunk36597b22015-03-20 22:15:57 -07003269 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003270 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003271 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003272 // from a system server crash
3273 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003274 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003275 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003276 break;
3277 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003278 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3279 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003280 if (args.size() != 1) {
3281 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3282 "USB Device Event requires 1 argument");
3283 }
3284
Valentin Iftime29e2e152021-08-13 15:17:33 +02003285 // Notify CameraProviderManager for lazy HALs
3286 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3287 std::to_string(args[0]));
3288 break;
3289 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003290 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003291 default: {
3292 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3293 eventId);
3294 break;
3295 }
3296 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003297 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003298}
3299
Emilian Peev53722fa2019-02-22 17:47:20 -08003300void CameraService::notifyMonitoredUids() {
3301 Mutex::Autolock lock(mStatusListenerLock);
3302
3303 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003304 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003305 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3306 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003307 }
3308}
3309
Austin Borgerdddb7552023-03-30 17:53:01 -07003310void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3311 Mutex::Autolock lock(mStatusListenerLock);
3312
3313 for (const auto& it : mListenerList) {
3314 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3315 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3316 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3317 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3318 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3319 }
3320 }
3321}
3322
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003323Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003324 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003325 const int selfPid = getpid();
3326
3327 // Permission checks
3328 if (pid != selfPid) {
3329 // Ensure we're being called by system_server, or similar process with
3330 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003331 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003332 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003333 ALOGE("Permission Denial: cannot send updates to camera service about device"
3334 " state changes from pid=%d, uid=%d", pid, uid);
3335 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3336 "No permission to send updates to camera service about device state"
3337 " changes from pid=%d, uid=%d", pid, uid);
3338 }
3339 }
3340
3341 ATRACE_CALL();
3342
Austin Borger18b30a72022-10-27 12:20:29 -07003343 {
3344 Mutex::Autolock lock(mServiceLock);
3345 mDeviceState = newState;
3346 }
3347
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003348 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003349
3350 return Status::ok();
3351}
3352
Emilian Peev8b64f282021-03-25 16:49:57 -07003353Status CameraService::notifyDisplayConfigurationChange() {
3354 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003355 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003356 const int selfPid = getpid();
3357
3358 // Permission checks
3359 if (callingPid != selfPid) {
3360 // Ensure we're being called by system_server, or similar process with
3361 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003362 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003363 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003364 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3365 " changes from pid=%d, uid=%d", callingPid, uid);
3366 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3367 "No permission to send updates to camera service about orientation"
3368 " changes from pid=%d, uid=%d", callingPid, uid);
3369 }
3370 }
3371
3372 Mutex::Autolock lock(mServiceLock);
3373
3374 // Don't do anything if rotate-and-crop override via cmd is active
3375 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3376
3377 const auto clients = mActiveClientManager.getAll();
3378 for (auto& current : clients) {
3379 if (current != nullptr) {
3380 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003381 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3382 basicClient->setRotateAndCropOverride(
3383 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3384 basicClient->getPackageName(),
3385 basicClient->getCameraFacing(),
3386 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003387 }
3388 }
3389 }
3390
3391 return Status::ok();
3392}
3393
Biswarup Pal37a75182024-01-16 15:53:35 +00003394// TODO(b/291736219): This to be made device-aware.
Emilian Peev8b64f282021-03-25 16:49:57 -07003395Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003396 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3397 ATRACE_CALL();
3398 if (!concurrentCameraIds) {
3399 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3400 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3401 }
3402
3403 if (!mInitialized) {
3404 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003405 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003406 return STATUS_ERROR(ERROR_DISCONNECTED,
3407 "Camera subsystem is not available");
3408 }
3409 // First call into the provider and get the set of concurrent camera
3410 // combinations
3411 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003412 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003413 for (auto &combination : concurrentCameraCombinations) {
3414 std::vector<std::string> validCombination;
3415 for (auto &cameraId : combination) {
3416 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003417 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003418 if (state == nullptr) {
3419 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3420 continue;
3421 }
3422 StatusInternal status = state->getStatus();
3423 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3424 continue;
3425 }
Austin Borgered99f642023-06-01 16:51:35 -07003426 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003427 continue;
3428 }
3429 validCombination.push_back(cameraId);
3430 }
3431 if (validCombination.size() != 0) {
3432 concurrentCameraIds->push_back(std::move(validCombination));
3433 }
3434 }
3435 return Status::ok();
3436}
3437
3438Status CameraService::isConcurrentSessionConfigurationSupported(
3439 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003440 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003441 if (!isSupported) {
3442 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3443 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3444 }
3445
3446 if (!mInitialized) {
3447 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3448 return STATUS_ERROR(ERROR_DISCONNECTED,
3449 "Camera subsystem is not available");
3450 }
3451
3452 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003453 int callingPid = getCallingPid();
3454 int callingUid = getCallingUid();
Biswarup Pale506e732024-03-27 13:46:20 +00003455 // TODO(b/291736219): Pass deviceId owning the camera if we make this method device-aware.
Austin Borger249e6592024-03-10 22:28:11 -07003456 bool hasCameraPermission = ((callingPid == getpid()) ||
Biswarup Pale506e732024-03-27 13:46:20 +00003457 hasPermissionsForCamera(callingPid, callingUid, kDefaultDeviceId));
Austin Borger249e6592024-03-10 22:28:11 -07003458 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003459 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3460 "android.permission.CAMERA needed to call"
3461 "isConcurrentSessionConfigurationSupported");
3462 }
3463
3464 status_t res =
3465 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003466 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3467 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003468 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003469 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003470 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003471 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3472 "support %s (%d)", strerror(-res), res);
3473 }
3474 return Status::ok();
3475}
3476
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003477Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3478 /*out*/
3479 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003480 return addListenerHelper(listener, cameraStatuses);
3481}
3482
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003483binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3484 std::vector<hardware::CameraStatus>* cameraStatuses) {
3485 return addListenerHelper(listener, cameraStatuses, false, true);
3486}
3487
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003488Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3489 /*out*/
3490 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003491 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003492 ATRACE_CALL();
3493
Igor Murashkinbfc99152013-02-27 12:55:20 -08003494 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003495
Ruben Brunk3450ba72015-06-16 11:00:37 -07003496 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003497 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003498 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003499 }
3500
Austin Borger22c5c852024-03-08 13:31:36 -08003501 auto clientPid = getCallingPid();
3502 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003503 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003504
Igor Murashkinbfc99152013-02-27 12:55:20 -08003505 Mutex::Autolock lock(mServiceLock);
3506
Ruben Brunkcc776712015-02-17 20:18:47 -08003507 {
3508 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003509 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003510 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003511 ALOGW("%s: Tried to add listener %p which was already subscribed",
3512 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003513 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003514 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003515 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003516
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003517 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003518 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3519 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003520 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003521 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003522 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003523 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003524 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3525 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3526 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003527 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003528 // The listener still needs to be added to the list of listeners, regardless of what
3529 // permissions the listener process has / whether it is a vendor listener. Since it might be
3530 // eligible to listen to other camera ids.
3531 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003532 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003533 }
3534
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003535 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003536 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003537 Mutex::Autolock lock(mCameraStatesLock);
3538 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003539 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3540 auto [deviceId, mappedCameraId] =
3541 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3542
3543 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003544 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003545 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3546 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003547 }
3548 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003549 // Remove the camera statuses that should be hidden from the client, we do
3550 // this after collecting the states in order to avoid holding
3551 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3552 // the same time.
3553 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3554 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003555 std::string cameraId = s.cameraId;
3556 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
3557 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM,
3558 clientUid);
3559 if (!cameraIdOptional.has_value()) {
3560 std::string msg =
3561 fmt::sprintf(
3562 "Camera %s: Invalid camera id for device id %d",
3563 s.cameraId.c_str(), s.deviceId);
3564 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3565 return true;
3566 }
3567 cameraId = cameraIdOptional.value();
3568 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3569 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3570 ALOGE("%s: Invalid camera id %s, skipping status update",
3571 __FUNCTION__, s.cameraId.c_str());
3572 return true;
3573 }
3574 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3575 clientUid);
3576 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003577
Biswarup Pal37a75182024-01-16 15:53:35 +00003578 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003579 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003580 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003581 // Add only default device cameras here, as virtual cameras currently don't support torch
3582 // anyway. Note that this is a simplification of the implementation here, and we should
3583 // change this when virtual cameras support torch.
3584 if (s.deviceId == kDefaultDeviceId) {
3585 idsChosenForCallback.insert(s.cameraId);
3586 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003587 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003588
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003589 /*
3590 * Immediately signal current torch status to this listener only
3591 * This may be a subset of all the devices, so don't include it in the response directly
3592 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003593 {
3594 Mutex::Autolock al(mTorchStatusMutex);
3595 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003596 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003597 // The camera id is visible to the client. Fine to send torch
3598 // callback.
3599 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003600 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3601 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003602 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003603 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003604 }
3605
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003606 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003607}
Ruben Brunkcc776712015-02-17 20:18:47 -08003608
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003609Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003610 ATRACE_CALL();
3611
Igor Murashkinbfc99152013-02-27 12:55:20 -08003612 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3613
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003614 if (listener == 0) {
3615 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003616 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003617 }
3618
Igor Murashkinbfc99152013-02-27 12:55:20 -08003619 Mutex::Autolock lock(mServiceLock);
3620
Ruben Brunkcc776712015-02-17 20:18:47 -08003621 {
3622 Mutex::Autolock lock(mStatusListenerLock);
3623 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003624 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003625 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003626 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003627 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003628 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003629 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003630 }
3631 }
3632
3633 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3634 __FUNCTION__, listener.get());
3635
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003636 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003637}
3638
Austin Borgered99f642023-06-01 16:51:35 -07003639Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003640
3641 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003642 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3643
3644 if (parameters == NULL) {
3645 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003646 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003647 }
3648
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003649 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003650
3651 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003652 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003653 // Error logged by caller
3654 return ret;
3655 }
3656
3657 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003658
Austin Borgered99f642023-06-01 16:51:35 -07003659 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003660
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003661 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003662}
3663
Austin Borgered99f642023-06-01 16:51:35 -07003664Status CameraService::supportsCameraApi(const std::string& unresolvedCameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003665 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003666 ATRACE_CALL();
3667
malikakashedb38962023-09-06 00:03:35 +00003668 const std::string cameraId = resolveCameraId(
Austin Borger22c5c852024-03-08 13:31:36 -08003669 unresolvedCameraId, getCallingUid());
malikakash82ed4352023-07-21 22:44:34 +00003670
Austin Borgered99f642023-06-01 16:51:35 -07003671 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003672
3673 switch (apiVersion) {
3674 case API_VERSION_1:
3675 case API_VERSION_2:
3676 break;
3677 default:
Austin Borgered99f642023-06-01 16:51:35 -07003678 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3679 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3680 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003681 }
3682
Austin Borger18b30a72022-10-27 12:20:29 -07003683 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -07003684 auto deviceVersionAndTransport = getDeviceVersion(cameraId, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003685 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003686 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3687 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3688 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003689 }
3690 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3691 int deviceVersion = deviceVersionAndTransport.first;
3692 switch (deviceVersion) {
3693 case CAMERA_DEVICE_API_VERSION_1_0:
3694 case CAMERA_DEVICE_API_VERSION_3_0:
3695 case CAMERA_DEVICE_API_VERSION_3_1:
3696 if (apiVersion == API_VERSION_2) {
3697 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003698 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003699 *isSupported = false;
3700 } else { // if (apiVersion == API_VERSION_1) {
3701 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003702 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003703 *isSupported = true;
3704 }
3705 break;
3706 case CAMERA_DEVICE_API_VERSION_3_2:
3707 case CAMERA_DEVICE_API_VERSION_3_3:
3708 case CAMERA_DEVICE_API_VERSION_3_4:
3709 case CAMERA_DEVICE_API_VERSION_3_5:
3710 case CAMERA_DEVICE_API_VERSION_3_6:
3711 case CAMERA_DEVICE_API_VERSION_3_7:
3712 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003713 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003714 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003715 break;
3716 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003717 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3718 deviceVersion, cameraId.c_str());
3719 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3720 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003721 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003722 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003723 } else {
3724 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003725 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003726 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003727}
3728
Austin Borgered99f642023-06-01 16:51:35 -07003729Status CameraService::isHiddenPhysicalCamera(const std::string& unresolvedCameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003730 /*out*/ bool *isSupported) {
3731 ATRACE_CALL();
3732
malikakashedb38962023-09-06 00:03:35 +00003733 const std::string cameraId = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08003734 getCallingUid());
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003735
Austin Borgered99f642023-06-01 16:51:35 -07003736 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3737 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003738
3739 return Status::ok();
3740}
3741
Cliff Wud8cae102021-03-11 01:37:42 +08003742Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003743 const std::string& packageName, const std::string& internalCamId,
3744 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003745 const sp<ICameraInjectionCallback>& callback,
3746 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003747 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003748 ATRACE_CALL();
3749
Austin Borgered99f642023-06-01 16:51:35 -07003750 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003751 const int pid = getCallingPid();
3752 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003753 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3754 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003755 "Permission Denial: no permission to inject camera");
3756 }
3757
3758 // Do not allow any camera injection that injects or replaces a virtual camera.
3759 auto [deviceIdForInternalCamera, _] =
3760 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3761 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3762 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3763 "Cannot replace a virtual camera");
3764 }
3765 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3766 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3767 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3768 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3769 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003770 }
3771
3772 ALOGV(
3773 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3774 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003775 __FUNCTION__, packageName.c_str(),
3776 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003777
Cliff Wud3a05312021-04-26 23:07:31 +08003778 {
3779 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003780 mInjectionInternalCamId = internalCamId;
3781 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003782 mInjectionStatusListener->addListener(callback);
3783 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003784 status_t res = NO_ERROR;
3785 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3786 // If the client already exists, we can directly connect to the camera device through the
3787 // client's injectCamera(), otherwise we need to wait until the client is established
3788 // (execute connectHelper()) before injecting the camera to the camera device.
3789 if (clientDescriptor != nullptr) {
3790 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003791 sp<BasicClient> clientSp = clientDescriptor->getValue();
3792 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3793 if(res != OK) {
3794 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3795 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003796 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003797 }
3798 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003799 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003800 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3801 }
3802 } else {
3803 mInjectionInitPending = true;
3804 }
3805 }
Cliff Wud8cae102021-03-11 01:37:42 +08003806
Cliff Wud3a05312021-04-26 23:07:31 +08003807 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003808}
3809
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003810Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003811 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003812 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3813 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3814 return Status::ok();
3815}
3816
Ruben Brunkcc776712015-02-17 20:18:47 -08003817void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003818 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003819 for (auto& i : mActiveClientManager.getAll()) {
3820 auto clientSp = i->getValue();
3821 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003822 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003823 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003824 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003825 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003826 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003827}
3828
Ruben Brunkcc776712015-02-17 20:18:47 -08003829bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003830 bool ret = false;
3831 {
3832 // Acquire mServiceLock and prevent other clients from connecting
3833 std::unique_ptr<AutoConditionLock> lock =
3834 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003835
Ruben Brunkcc776712015-02-17 20:18:47 -08003836 std::vector<sp<BasicClient>> evicted;
3837 for (auto& i : mActiveClientManager.getAll()) {
3838 auto clientSp = i->getValue();
3839 if (clientSp.get() == nullptr) {
3840 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3841 mActiveClientManager.remove(i);
3842 continue;
3843 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003844 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003845 mActiveClientManager.remove(i);
3846 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003847
Ruben Brunkcc776712015-02-17 20:18:47 -08003848 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003849 clientSp->notifyError(
3850 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003851 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003852 }
3853 }
3854
Ruben Brunkcc776712015-02-17 20:18:47 -08003855 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3856 // other clients from connecting in mServiceLockWrapper if held
3857 mServiceLock.unlock();
3858
Ruben Brunk36597b22015-03-20 22:15:57 -07003859 // Do not clear caller identity, remote caller should be client proccess
3860
Ruben Brunkcc776712015-02-17 20:18:47 -08003861 for (auto& i : evicted) {
3862 if (i.get() != nullptr) {
3863 i->disconnect();
3864 ret = true;
3865 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003866 }
3867
Ruben Brunkcc776712015-02-17 20:18:47 -08003868 // Reacquire mServiceLock
3869 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003870
Ruben Brunkcc776712015-02-17 20:18:47 -08003871 } // lock is destroyed, allow further connect calls
3872
3873 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003874}
3875
Ruben Brunkcc776712015-02-17 20:18:47 -08003876std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003877 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003878 std::shared_ptr<CameraState> state;
3879 {
3880 Mutex::Autolock lock(mCameraStatesLock);
3881 auto iter = mCameraStates.find(cameraId);
3882 if (iter != mCameraStates.end()) {
3883 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003884 }
3885 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003886 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003887}
3888
Austin Borgered99f642023-06-01 16:51:35 -07003889sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003890 // Remove from active clients list
3891 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3892 if (clientDescriptorPtr == nullptr) {
3893 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003894 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003895 return sp<BasicClient>{nullptr};
3896 }
3897
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003898 sp<BasicClient> client = clientDescriptorPtr->getValue();
3899 if (client.get() != nullptr) {
3900 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3901 }
3902 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003903}
3904
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003905void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003906 // Acquire mServiceLock and prevent other clients from connecting
3907 std::unique_ptr<AutoConditionLock> lock =
3908 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3909
Ruben Brunk6267b532015-04-30 17:44:07 -07003910 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003911 for (size_t i = 0; i < newUserIds.size(); i++) {
3912 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003913 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003914 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003915 return;
3916 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003917 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003918 }
3919
Ruben Brunka8ca9152015-04-07 14:23:40 -07003920
Ruben Brunk6267b532015-04-30 17:44:07 -07003921 if (newAllowedUsers == mAllowedUsers) {
3922 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3923 return;
3924 }
3925
3926 logUserSwitch(mAllowedUsers, newAllowedUsers);
3927
3928 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003929
3930 // Current user has switched, evict all current clients.
3931 std::vector<sp<BasicClient>> evicted;
3932 for (auto& i : mActiveClientManager.getAll()) {
3933 auto clientSp = i->getValue();
3934
3935 if (clientSp.get() == nullptr) {
3936 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3937 continue;
3938 }
3939
Ruben Brunk6267b532015-04-30 17:44:07 -07003940 // Don't evict clients that are still allowed.
3941 uid_t clientUid = clientSp->getClientUid();
3942 userid_t clientUserId = multiuser_get_user_id(clientUid);
3943 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3944 continue;
3945 }
3946
Ruben Brunk36597b22015-03-20 22:15:57 -07003947 evicted.push_back(clientSp);
3948
Ruben Brunk36597b22015-03-20 22:15:57 -07003949 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003950 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003951
Ruben Brunk36597b22015-03-20 22:15:57 -07003952 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003953 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003954 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003955 " to user switch.", i->getKey().c_str(),
3956 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003957 i->getOwnerId(), i->getPriority().getScore(),
3958 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003959
3960 }
3961
3962 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3963 // blocking other clients from connecting in mServiceLockWrapper if held.
3964 mServiceLock.unlock();
3965
3966 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08003967 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003968
3969 for (auto& i : evicted) {
3970 i->disconnect();
3971 }
3972
Austin Borger22c5c852024-03-08 13:31:36 -08003973 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003974
3975 // Reacquire mServiceLock
3976 mServiceLock.lock();
3977}
Ruben Brunkcc776712015-02-17 20:18:47 -08003978
Austin Borgered99f642023-06-01 16:51:35 -07003979void CameraService::logEvent(const std::string &event) {
3980 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003981 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003982 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003983 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003984 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003985 mEventLog.add(msg);
3986 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3987 // Error event not added to the dumpsys log before
3988 mEventLog.add(msg);
3989 sServiceErrorEventSet.insert(msg);
3990 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003991}
3992
Austin Borgered99f642023-06-01 16:51:35 -07003993void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3994 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003995 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003996 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3997 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003998}
3999
Austin Borgered99f642023-06-01 16:51:35 -07004000void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
4001 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004002 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004003 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
4004 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004005}
4006
Austin Borgered99f642023-06-01 16:51:35 -07004007void CameraService::logConnected(const std::string &cameraId, int clientPid,
4008 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004009 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004010 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
4011 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004012}
4013
Austin Borgered99f642023-06-01 16:51:35 -07004014void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
4015 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004016 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004017 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
4018 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004019}
4020
Austin Borgered99f642023-06-01 16:51:35 -07004021void CameraService::logRejected(const std::string &cameraId, int clientPid,
4022 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004023 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07004024 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
4025 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004026}
4027
Austin Borgered99f642023-06-01 16:51:35 -07004028void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
4029 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07004030 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07004031 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
4032 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07004033}
4034
Ruben Brunk6267b532015-04-30 17:44:07 -07004035void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
4036 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07004037 std::string newUsers = toString(newUserIds);
4038 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004039 if (oldUsers.size() == 0) {
4040 oldUsers = "<None>";
4041 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07004042 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07004043 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
4044 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004045}
4046
Austin Borgered99f642023-06-01 16:51:35 -07004047void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004048 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004049 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004050}
4051
Austin Borgered99f642023-06-01 16:51:35 -07004052void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004053 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004054 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004055}
4056
Austin Borgered99f642023-06-01 16:51:35 -07004057void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004058 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004059 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07004060}
4061
Austin Borgered99f642023-06-01 16:51:35 -07004062void CameraService::logServiceError(const std::string &msg, int errorCode) {
4063 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
4064 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004065}
4066
Ruben Brunk36597b22015-03-20 22:15:57 -07004067status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4068 uint32_t flags) {
4069
Mathias Agopian65ab4712010-07-14 17:59:35 -07004070 // Permission checks
4071 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004072 case SHELL_COMMAND_TRANSACTION: {
4073 int in = data.readFileDescriptor();
4074 int out = data.readFileDescriptor();
4075 int err = data.readFileDescriptor();
4076 int argc = data.readInt32();
4077 Vector<String16> args;
4078 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
4079 args.add(data.readString16());
4080 }
4081 sp<IBinder> unusedCallback;
4082 sp<IResultReceiver> resultReceiver;
4083 status_t status;
4084 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
4085 return status;
4086 }
4087 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
4088 return status;
4089 }
4090 status = shellCommand(in, out, err, args);
4091 if (resultReceiver != nullptr) {
4092 resultReceiver->send(status);
4093 }
4094 return NO_ERROR;
4095 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004096 }
4097
4098 return BnCameraService::onTransact(code, data, reply, flags);
4099}
4100
Mathias Agopian65ab4712010-07-14 17:59:35 -07004101// We share the media players for shutter and recording sound for all clients.
4102// A reference count is kept to determine when we will actually release the
4103// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09004104sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
4105 sp<MediaPlayer> mp = new MediaPlayer();
4106 status_t error;
4107 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08004108 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09004109 error = mp->prepare();
4110 }
4111 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004112 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09004113 mp->disconnect();
4114 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004115 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004116 }
4117 return mp;
4118}
4119
username5755fea2018-12-27 09:48:08 +08004120void CameraService::increaseSoundRef() {
4121 Mutex::Autolock lock(mSoundLock);
4122 mSoundRef++;
4123}
4124
4125void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004126 ATRACE_CALL();
4127
username5755fea2018-12-27 09:48:08 +08004128 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
4129 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
4130 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
4131 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
4132 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4133 }
4134 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
4135 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4136 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4137 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004138 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08004139 }
4140 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4141 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4142 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4143 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4144 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004145 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004146}
4147
username5755fea2018-12-27 09:48:08 +08004148void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004149 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004150 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004151 if (--mSoundRef) return;
4152
4153 for (int i = 0; i < NUM_SOUNDS; i++) {
4154 if (mSoundPlayer[i] != 0) {
4155 mSoundPlayer[i]->disconnect();
4156 mSoundPlayer[i].clear();
4157 }
4158 }
4159}
4160
4161void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004162 ATRACE_CALL();
4163
Mathias Agopian65ab4712010-07-14 17:59:35 -07004164 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004165 if (kind < 0 || kind >= NUM_SOUNDS) {
4166 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4167 return;
4168 }
4169
Mathias Agopian65ab4712010-07-14 17:59:35 -07004170 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004171 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004172 sp<MediaPlayer> player = mSoundPlayer[kind];
4173 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004174 player->seekTo(0);
4175 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004176 }
4177}
4178
4179// ----------------------------------------------------------------------------
4180
4181CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004182 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004183 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004184 const std::string& clientPackageName, bool systemNativeClient,
4185 const std::optional<std::string>& clientFeatureId,
4186 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004187 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004188 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004189 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004190 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004191 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07004192 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004193 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004194 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004195 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004196 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004197 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004198{
Austin Borger22c5c852024-03-08 13:31:36 -08004199 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004200 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004201
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004202 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004203
username5755fea2018-12-27 09:48:08 +08004204 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004205
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004206 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004207}
4208
Mathias Agopian65ab4712010-07-14 17:59:35 -07004209// tear down the client
4210CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004211 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004212 mDestructionStarted = true;
4213
username5755fea2018-12-27 09:48:08 +08004214 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004215 // unconditionally disconnect. function is idempotent
4216 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004217}
4218
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004219sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4220
Igor Murashkin634a5152013-02-20 17:15:11 -08004221CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004222 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004223 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004224 const std::string& clientPackageName, bool nativeClient,
4225 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004226 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004227 int servicePid, bool overrideToPortrait):
Austin Borger249e6592024-03-10 22:28:11 -07004228 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004229 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004230 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004231 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4232 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004233 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004234 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004235 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07004236 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004237 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004238 mRemoteBinder(remoteCallback),
4239 mOpsActive(false),
4240 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004241{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004242 if (sCameraService == nullptr) {
4243 sCameraService = cameraService;
4244 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004245
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004246 // There are 2 scenarios in which a client won't have AppOps operations
4247 // (both scenarios : native clients)
4248 // 1) It's an system native client*, the package name will be empty
4249 // and it will return from this function in the previous if condition
4250 // (This is the same as the previously existing behavior).
4251 // 2) It is a system native client, but its package name has been
4252 // modified for debugging, however it still must not use AppOps since
4253 // the package name is not a real one.
4254 //
4255 // * system native client - native client with UID < AID_APP_START. It
4256 // doesn't exclude clients not on the system partition.
4257 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004258 mAppOpsManager = std::make_unique<AppOpsManager>();
4259 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004260
Charles Chenf075f082024-03-04 23:32:55 +00004261 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004262}
4263
4264CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004265 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004266 mDestructionStarted = true;
4267}
4268
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004269binder::Status CameraService::BasicClient::disconnect() {
4270 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004271 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004272 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004273 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004274 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004275
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004276 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004277 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004278 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004279 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004280
4281 sp<IBinder> remote = getRemote();
4282 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004283 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004284 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004285
4286 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004287 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004288 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004289 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004290 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004291
Igor Murashkincba2c162013-03-20 15:56:31 -07004292 // client shouldn't be able to call into us anymore
4293 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004294
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004295 const auto& mActivityManager = getActivityManager();
4296 if (mActivityManager) {
4297 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004298 getCallingUid(),
4299 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004300 }
4301
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004302 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004303}
4304
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004305status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4306 // No dumping of clients directly over Binder,
4307 // must go through CameraService::dump
4308 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004309 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004310 return OK;
4311}
4312
Austin Borgered99f642023-06-01 16:51:35 -07004313status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004314 // Can't watch tags directly, must go through CameraService::startWatchingTags
4315 return OK;
4316}
4317
4318status_t CameraService::BasicClient::stopWatchingTags(int) {
4319 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4320 return OK;
4321}
4322
4323status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4324 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4325 return OK;
4326}
4327
Austin Borgered99f642023-06-01 16:51:35 -07004328std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004329 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004330}
4331
Emilian Peev8b64f282021-03-25 16:49:57 -07004332int CameraService::BasicClient::getCameraFacing() const {
4333 return mCameraFacing;
4334}
4335
4336int CameraService::BasicClient::getCameraOrientation() const {
4337 return mOrientation;
4338}
Ruben Brunkcc776712015-02-17 20:18:47 -08004339
4340int CameraService::BasicClient::getClientPid() const {
4341 return mClientPid;
4342}
4343
Ruben Brunk6267b532015-04-30 17:44:07 -07004344uid_t CameraService::BasicClient::getClientUid() const {
4345 return mClientUid;
4346}
4347
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004348bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4349 // Defaults to API2.
4350 return level == API_2;
4351}
4352
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004353status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004354 {
4355 Mutex::Autolock l(mAudioRestrictionLock);
4356 mAudioRestriction = mode;
4357 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004358 sCameraService->updateAudioRestriction();
4359 return OK;
4360}
4361
4362int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004363 return sCameraService->updateAudioRestriction();
4364}
4365
4366int32_t CameraService::BasicClient::getAudioRestriction() const {
4367 Mutex::Autolock l(mAudioRestrictionLock);
4368 return mAudioRestriction;
4369}
4370
4371bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4372 switch (mode) {
4373 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4374 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4375 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4376 return true;
4377 default:
4378 return false;
4379 }
4380}
4381
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004382status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4383 if (mode == AppOpsManager::MODE_ERRORED) {
4384 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004385 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004386 return PERMISSION_DENIED;
4387 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4388 // If the calling Uid is trusted (a native service), the AppOpsManager could
4389 // return MODE_IGNORED. Do not treat such case as error.
4390 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4391 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004392
4393 bool isCameraPrivacyEnabled;
4394 if (flags::camera_privacy_allowlist()) {
4395 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4396 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4397 } else {
4398 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004399 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004400 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004401 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4402 // We prefer to successfully open the camera and perform camera muting
4403 // or blocking in connectHelper as handleAppOpMode can be called before the
4404 // connection has been fully established and at that time camera muting
4405 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004406 if (!isUidActive || !isCameraPrivacyEnabled) {
4407 ALOGI("Camera %s: Access for \"%s\" has been restricted",
Austin Borgered99f642023-06-01 16:51:35 -07004408 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004409 // Return the same error as for device policy manager rejection
4410 return -EACCES;
4411 }
4412 }
4413 return OK;
4414}
4415
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004416status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004417 ATRACE_CALL();
4418
Igor Murashkine6800ce2013-03-04 17:25:57 -08004419 {
4420 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004421 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004422 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004423 if (mAppOpsManager != nullptr) {
4424 // Notify app ops that the camera is not available
4425 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004426
4427 if (flags::watch_foreground_changes()) {
4428 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4429 toString16(mClientPackageName),
4430 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4431 } else {
4432 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004433 toString16(mClientPackageName), mOpsCallback);
Austin Borgerca1e0062023-06-28 11:32:55 -07004434 }
Igor Murashkine6800ce2013-03-04 17:25:57 -08004435
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004436 // Just check for camera acccess here on open - delay startOp until
4437 // camera frames start streaming in startCameraStreamingOps
4438 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004439 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004440 status_t res = handleAppOpMode(mode);
4441 if (res != OK) {
4442 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004443 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004444 }
4445
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004446 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004447
4448 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004449 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004450
Austin Borgerdddb7552023-03-30 17:53:01 -07004451 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004452
Shuzhen Wang695044d2020-03-06 09:02:23 -08004453 // Notify listeners of camera open/close status
4454 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4455
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004456 return OK;
4457}
4458
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004459status_t CameraService::BasicClient::startCameraStreamingOps() {
4460 ATRACE_CALL();
4461
4462 if (!mOpsActive) {
4463 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4464 return INVALID_OPERATION;
4465 }
4466 if (mOpsStreaming) {
4467 ALOGV("%s: Streaming already active!", __FUNCTION__);
4468 return OK;
4469 }
4470
4471 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004472 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004473
4474 if (mAppOpsManager != nullptr) {
4475 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004476 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4477 toString16(mClientFeatureId),
4478 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004479 status_t res = handleAppOpMode(mode);
4480 if (res != OK) {
4481 return res;
4482 }
4483 }
4484
4485 mOpsStreaming = true;
4486
4487 return OK;
4488}
4489
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004490status_t CameraService::BasicClient::noteAppOp() {
4491 ATRACE_CALL();
4492
4493 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004494 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004495
4496 // noteAppOp is only used for when camera mute is not supported, in order
4497 // to trigger the sensor privacy "Unblock" dialog
4498 if (mAppOpsManager != nullptr) {
4499 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004500 toString16(mClientPackageName), toString16(mClientFeatureId),
4501 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004502 status_t res = handleAppOpMode(mode);
4503 if (res != OK) {
4504 return res;
4505 }
4506 }
4507
4508 return OK;
4509}
4510
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004511status_t CameraService::BasicClient::finishCameraStreamingOps() {
4512 ATRACE_CALL();
4513
4514 if (!mOpsActive) {
4515 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4516 return INVALID_OPERATION;
4517 }
4518 if (!mOpsStreaming) {
4519 ALOGV("%s: Streaming not active!", __FUNCTION__);
4520 return OK;
4521 }
4522
4523 if (mAppOpsManager != nullptr) {
4524 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004525 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004526 mOpsStreaming = false;
4527 }
4528
4529 return OK;
4530}
4531
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004532status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004533 ATRACE_CALL();
4534
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004535 if (mOpsStreaming) {
4536 // Make sure we've notified everyone about camera stopping
4537 finishCameraStreamingOps();
4538 }
4539
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004540 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004541 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004542 mOpsActive = false;
4543
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004544 // This function is called when a client disconnects. This should
4545 // release the camera, but actually only if it was in a proper
4546 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004547 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004548 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004549
Ruben Brunkcc776712015-02-17 20:18:47 -08004550 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004551 sCameraService->updateStatus(StatusInternal::PRESENT,
4552 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004553 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004554 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004555 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4556 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004557 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004558 mOpsCallback.clear();
4559
Austin Borgerdddb7552023-03-30 17:53:01 -07004560 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004561
Shuzhen Wang695044d2020-03-06 09:02:23 -08004562 // Notify listeners of camera open/close status
4563 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4564
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004565 return OK;
4566}
4567
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004568void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004569 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004570 if (mAppOpsManager == nullptr) {
4571 return;
4572 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004573 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004574 if (op != AppOpsManager::OP_CAMERA) {
4575 ALOGW("Unexpected app ops notification received: %d", op);
4576 return;
4577 }
4578
4579 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004580 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004581 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004582 ALOGV("checkOp returns: %d, %s ", res,
4583 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4584 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4585 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4586 "UNKNOWN");
4587
Shuzhen Wang64900852021-02-05 09:03:29 -08004588 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004589 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4590 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004591 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004592 } else if (res == AppOpsManager::MODE_IGNORED) {
4593 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004594
Austin Borgerca1e0062023-06-28 11:32:55 -07004595 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4596 // If not visible, but still active, then we want to block instead of muting the camera.
4597 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4598 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4599
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004600 bool isCameraPrivacyEnabled;
4601 if (flags::camera_privacy_allowlist()) {
4602 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4603 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4604 } else {
4605 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004606 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004607 }
4608
4609 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004610 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4611 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4612 isCameraPrivacyEnabled);
4613 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4614 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4615 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004616 if (!mUidIsTrusted) {
Austin Borgerca1e0062023-06-28 11:32:55 -07004617 if (flags::watch_foreground_changes()) {
4618 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4619 setCameraMute(true);
4620 } else {
4621 block();
4622 }
4623 } else {
4624 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4625 setCameraMute(true);
4626 } else if (!isUidActive
4627 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4628 block();
4629 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004630 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004631 }
Evan Severson09ab4002021-02-10 14:15:19 -08004632 } else if (res == AppOpsManager::MODE_ALLOWED) {
4633 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004634 }
4635}
4636
Svet Ganova453d0d2018-01-11 15:37:58 -08004637void CameraService::BasicClient::block() {
4638 ATRACE_CALL();
4639
4640 // Reset the client PID to allow server-initiated disconnect,
4641 // and to prevent further calls by client.
Austin Borger22c5c852024-03-08 13:31:36 -08004642 mClientPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004643 CaptureResultExtras resultExtras; // a dummy result (invalid)
4644 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4645 disconnect();
4646}
4647
Mathias Agopian65ab4712010-07-14 17:59:35 -07004648// ----------------------------------------------------------------------------
4649
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004650void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004651 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004652 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004653 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4654 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4655 api1ErrorCode = CAMERA_ERROR_DISABLED;
4656 }
4657 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004658 } else {
4659 ALOGE("mRemoteCallback is NULL!!");
4660 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004661}
4662
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004663// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004664binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004665 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004666 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004667}
4668
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004669bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4670 return level == API_1;
4671}
4672
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004673CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4674 mClient(client) {
4675}
4676
4677void CameraService::Client::OpsCallback::opChanged(int32_t op,
4678 const String16& packageName) {
4679 sp<BasicClient> client = mClient.promote();
4680 if (client != NULL) {
4681 client->opChanged(op, packageName);
4682 }
4683}
4684
Mathias Agopian65ab4712010-07-14 17:59:35 -07004685// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004686// UidPolicy
4687// ----------------------------------------------------------------------------
4688
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004689void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004690 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004691 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004692
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004693 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004694 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004695 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004696 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004697 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4698 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004699 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004700 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004701 if (res == OK) {
4702 mRegistered = true;
4703 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004704 } else {
4705 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004706 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004707}
4708
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004709void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004710 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004711 return;
4712 }
4713
4714 registerWithActivityManager();
4715}
4716
4717void CameraService::UidPolicy::registerSelf() {
4718 // Use check service to see if the activity service is available
4719 // If not available then register for notifications, instead of blocking
4720 // till the service is ready
4721 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004722 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004723 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004724 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004725 } else {
4726 registerWithActivityManager();
4727 }
4728}
4729
Svet Ganova453d0d2018-01-11 15:37:58 -08004730void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004731 Mutex::Autolock _l(mUidLock);
4732
Steven Moreland2f348142019-07-02 15:59:07 -07004733 mAm.unregisterUidObserver(this);
4734 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004735 mRegistered = false;
4736 mActiveUids.clear();
4737 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004738}
4739
4740void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4741 onUidIdle(uid, disabled);
4742}
4743
4744void CameraService::UidPolicy::onUidActive(uid_t uid) {
4745 Mutex::Autolock _l(mUidLock);
4746 mActiveUids.insert(uid);
4747}
4748
4749void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4750 bool deleted = false;
4751 {
4752 Mutex::Autolock _l(mUidLock);
4753 if (mActiveUids.erase(uid) > 0) {
4754 deleted = true;
4755 }
4756 }
4757 if (deleted) {
4758 sp<CameraService> service = mService.promote();
4759 if (service != nullptr) {
4760 service->blockClientsForUid(uid);
4761 }
4762 }
4763}
4764
Emilian Peev53722fa2019-02-22 17:47:20 -08004765void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004766 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004767 bool procStateChange = false;
4768 {
4769 Mutex::Autolock _l(mUidLock);
4770 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4771 mMonitoredUids[uid].procState != procState) {
4772 mMonitoredUids[uid].procState = procState;
4773 procStateChange = true;
4774 }
4775 }
4776
4777 if (procStateChange) {
4778 sp<CameraService> service = mService.promote();
4779 if (service != nullptr) {
4780 service->notifyMonitoredUids();
4781 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004782 }
4783}
4784
Austin Borgerdddb7552023-03-30 17:53:01 -07004785/**
4786 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4787 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4788 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4789 * monitoredUids. If it is revised above some other monitoredUid, signal
4790 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4791 * foreground apps in split screen - state changes will capture all other cases.
4792 */
4793void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4794 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004795 {
4796 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004797 auto it = mMonitoredUids.find(uid);
4798
4799 if (it != mMonitoredUids.end()) {
4800 if (it->second.hasCamera) {
4801 for (auto &monitoredUid : mMonitoredUids) {
4802 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004803 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004804 notifyUidSet.emplace(monitoredUid.first);
4805 }
4806 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004807 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004808 notifyUidSet.emplace(uid);
4809 } else {
4810 for (auto &monitoredUid : mMonitoredUids) {
4811 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004812 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004813 notifyUidSet.emplace(uid);
4814 }
4815 }
4816 }
4817 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004818 }
4819 }
4820
Austin Borgerdddb7552023-03-30 17:53:01 -07004821 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004822 sp<CameraService> service = mService.promote();
4823 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004824 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004825 }
4826 }
4827}
4828
Austin Borgerdddb7552023-03-30 17:53:01 -07004829/**
4830 * Register a uid for monitoring, and note whether it owns a camera.
4831 */
4832void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004833 Mutex::Autolock _l(mUidLock);
4834 auto it = mMonitoredUids.find(uid);
4835 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004836 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004837 } else {
Austin Borger65577682022-02-17 00:25:43 +00004838 MonitoredUid monitoredUid;
4839 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004840 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004841 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004842 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004843 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004844 if (res != OK) {
4845 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4846 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004847 }
4848
4849 if (openCamera) {
4850 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004851 }
4852}
4853
Austin Borgerdddb7552023-03-30 17:53:01 -07004854/**
4855 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4856 */
4857void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004858 Mutex::Autolock _l(mUidLock);
4859 auto it = mMonitoredUids.find(uid);
4860 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004861 it->second.refCount--;
4862 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004863 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004864 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004865 if (res != OK) {
4866 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4867 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004868 } else if (closeCamera) {
4869 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004870 }
4871 } else {
4872 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4873 }
4874}
4875
Austin Borgered99f642023-06-01 16:51:35 -07004876bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004877 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004878 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004879}
4880
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004881static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4882static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004883
Austin Borgered99f642023-06-01 16:51:35 -07004884bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004885 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004886 // If activity manager is unreachable, assume everything is active
4887 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004888 return true;
4889 }
4890 auto it = mOverrideUids.find(uid);
4891 if (it != mOverrideUids.end()) {
4892 return it->second;
4893 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004894 bool active = mActiveUids.find(uid) != mActiveUids.end();
4895 if (!active) {
4896 // We want active UIDs to always access camera with their first attempt since
4897 // there is no guarantee the app is robustly written and would retry getting
4898 // the camera on failure. The inverse case is not a problem as we would take
4899 // camera away soon once we get the callback that the uid is no longer active.
4900 ActivityManager am;
4901 // Okay to access with a lock held as UID changes are dispatched without
4902 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004903 int64_t startTimeMillis = 0;
4904 do {
4905 // TODO: Fix this b/109950150!
4906 // Okay this is a hack. There is a race between the UID turning active and
4907 // activity being resumed. The proper fix is very risky, so we temporary add
4908 // some polling which should happen pretty rarely anyway as the race is hard
4909 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004910 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004911 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004912 if (active) {
4913 break;
4914 }
4915 if (startTimeMillis <= 0) {
4916 startTimeMillis = uptimeMillis();
4917 }
4918 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004919 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004920 if (remainingTimeMillis <= 0) {
4921 break;
4922 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004923 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4924
4925 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004926 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004927 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004928 } while (true);
4929
Svet Ganov7b4ab782018-03-25 12:48:10 -07004930 if (active) {
4931 // Now that we found out the UID is actually active, cache that
4932 mActiveUids.insert(uid);
4933 }
4934 }
4935 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004936}
4937
Varun Shahb42f1eb2019-04-16 14:45:13 -07004938int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4939 Mutex::Autolock _l(mUidLock);
4940 return getProcStateLocked(uid);
4941}
4942
4943int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4944 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4945 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004946 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004947 }
4948 return procState;
4949}
4950
Austin Borgered99f642023-06-01 16:51:35 -07004951void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4952 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004953 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004954}
4955
Austin Borgered99f642023-06-01 16:51:35 -07004956void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004957 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004958}
4959
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004960void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4961 Mutex::Autolock _l(mUidLock);
4962 ALOGV("UidPolicy: ActivityManager has died");
4963 mRegistered = false;
4964 mActiveUids.clear();
4965}
4966
Austin Borgered99f642023-06-01 16:51:35 -07004967void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004968 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004969 bool wasActive = false;
4970 bool isActive = false;
4971 {
4972 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004973 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004974 mOverrideUids.erase(uid);
4975 if (insert) {
4976 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4977 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004978 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004979 }
4980 if (wasActive != isActive && !isActive) {
4981 sp<CameraService> service = mService.promote();
4982 if (service != nullptr) {
4983 service->blockClientsForUid(uid);
4984 }
4985 }
4986}
4987
4988// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004989// SensorPrivacyPolicy
4990// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004991
4992void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4993{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004994 Mutex::Autolock _l(mSensorPrivacyLock);
4995 if (mRegistered) {
4996 return;
4997 }
Evan Severson09ab4002021-02-10 14:15:19 -08004998 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004999 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00005000 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005001 mSpm.addToggleSensorPrivacyListener(this);
5002 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005003 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005004 if (flags::camera_privacy_allowlist()) {
5005 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
5006 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
5007 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5008 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005009 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005010 if (res == OK) {
5011 mRegistered = true;
5012 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
5013 }
5014}
5015
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005016void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
5017 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07005018 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005019 return;
5020 }
5021
5022 registerWithSensorPrivacyManager();
5023}
5024
5025void CameraService::SensorPrivacyPolicy::registerSelf() {
5026 // Use checkservice to see if the sensor_privacy service is available
5027 // If service is not available then register for notification
5028 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07005029 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005030 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07005031 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005032 } else {
5033 registerWithSensorPrivacyManager();
5034 }
5035}
5036
Michael Grooverd1d435a2018-12-18 17:39:42 -08005037void CameraService::SensorPrivacyPolicy::unregisterSelf() {
5038 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08005039 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00005040 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005041 mSpm.removeToggleSensorPrivacyListener(this);
5042 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005043 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005044 mRegistered = false;
5045 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
5046}
5047
5048bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005049 if (!mRegistered) {
5050 registerWithSensorPrivacyManager();
5051 }
5052
Michael Grooverd1d435a2018-12-18 17:39:42 -08005053 Mutex::Autolock _l(mSensorPrivacyLock);
5054 return mSensorPrivacyEnabled;
5055}
5056
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005057int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
5058 if (!mRegistered) {
5059 registerWithSensorPrivacyManager();
5060 }
5061
5062 Mutex::Autolock _l(mSensorPrivacyLock);
5063 return mCameraPrivacyState;
5064}
5065
Evan Seversond0b69922022-01-27 10:47:34 -08005066bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08005067 if (!hasCameraPrivacyFeature()) {
5068 return false;
5069 }
Evan Seversond0b69922022-01-27 10:47:34 -08005070 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08005071}
5072
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005073bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
5074 if (!hasCameraPrivacyFeature()) {
5075 return SensorPrivacyManager::DISABLED;
5076 }
5077 return mSpm.isCameraPrivacyEnabled(packageName);
5078}
5079
Evan Seversond0b69922022-01-27 10:47:34 -08005080binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005081 int toggleType, int sensor, bool enabled) {
5082 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
5083 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
5084 {
5085 Mutex::Autolock _l(mSensorPrivacyLock);
5086 mSensorPrivacyEnabled = enabled;
5087 }
5088 // if sensor privacy is enabled then block all clients from accessing the camera
5089 if (enabled) {
5090 sp<CameraService> service = mService.promote();
5091 if (service != nullptr) {
5092 service->blockAllClients();
5093 }
5094 }
5095 }
5096 return binder::Status::ok();
5097}
5098
5099binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
5100 int, int sensor, int state) {
5101 if (!flags::camera_privacy_allowlist()
5102 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
5103 return binder::Status::ok();
5104 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08005105 {
5106 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005107 mCameraPrivacyState = state;
5108 }
5109 sp<CameraService> service = mService.promote();
5110 if (!service) {
5111 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005112 }
5113 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005114 if (state == SensorPrivacyManager::ENABLED) {
5115 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08005116 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005117 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005118 }
5119 return binder::Status::ok();
5120}
5121
5122void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
5123 Mutex::Autolock _l(mSensorPrivacyLock);
5124 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
5125 mRegistered = false;
5126}
5127
Evan Severson09ab4002021-02-10 14:15:19 -08005128bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08005129 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
5130 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5131 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
5132 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5133 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08005134}
5135
Michael Grooverd1d435a2018-12-18 17:39:42 -08005136// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005137// CameraState
5138// ----------------------------------------------------------------------------
5139
Austin Borgered99f642023-06-01 16:51:35 -07005140CameraService::CameraState::CameraState(const std::string& id, int cost,
5141 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005142 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005143 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005144 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005145
5146CameraService::CameraState::~CameraState() {}
5147
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005148CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005149 Mutex::Autolock lock(mStatusLock);
5150 return mStatus;
5151}
5152
Austin Borgered99f642023-06-01 16:51:35 -07005153std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005154 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005155 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005156 return res;
5157}
5158
Ruben Brunkcc776712015-02-17 20:18:47 -08005159CameraParameters CameraService::CameraState::getShimParams() const {
5160 return mShimParams;
5161}
5162
5163void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5164 mShimParams = params;
5165}
5166
5167int CameraService::CameraState::getCost() const {
5168 return mCost;
5169}
5170
Austin Borgered99f642023-06-01 16:51:35 -07005171std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005172 return mConflicting;
5173}
5174
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005175SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5176 return mSystemCameraKind;
5177}
5178
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005179bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5180 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5181 != mPhysicalCameras.end();
5182}
5183
Austin Borgered99f642023-06-01 16:51:35 -07005184bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005185 Mutex::Autolock lock(mStatusLock);
5186 auto result = mUnavailablePhysicalIds.insert(physicalId);
5187 return result.second;
5188}
5189
Austin Borgered99f642023-06-01 16:51:35 -07005190bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005191 Mutex::Autolock lock(mStatusLock);
5192 auto count = mUnavailablePhysicalIds.erase(physicalId);
5193 return count > 0;
5194}
5195
Austin Borgered99f642023-06-01 16:51:35 -07005196void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005197 Mutex::Autolock lock(mStatusLock);
5198 mClientPackage = clientPackage;
5199}
5200
Austin Borgered99f642023-06-01 16:51:35 -07005201std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005202 Mutex::Autolock lock(mStatusLock);
5203 return mClientPackage;
5204}
5205
Ruben Brunkcc776712015-02-17 20:18:47 -08005206// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005207// ClientEventListener
5208// ----------------------------------------------------------------------------
5209
5210void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005211 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005212 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005213 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005214 if (basicClient.get() != nullptr) {
5215 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005216 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005217 static_cast<int>(basicClient->getClientUid()));
5218 }
5219}
5220
5221void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005222 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005223 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005224 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005225 if (basicClient.get() != nullptr) {
5226 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005227 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005228 static_cast<int>(basicClient->getClientUid()));
5229 }
5230}
5231
Ruben Brunk99e69712015-05-26 17:25:07 -07005232// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005233// CameraClientManager
5234// ----------------------------------------------------------------------------
5235
Ruben Brunk99e69712015-05-26 17:25:07 -07005236CameraService::CameraClientManager::CameraClientManager() {
5237 setListener(std::make_shared<ClientEventListener>());
5238}
5239
Ruben Brunkcc776712015-02-17 20:18:47 -08005240CameraService::CameraClientManager::~CameraClientManager() {}
5241
5242sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005243 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005244 auto descriptor = get(id);
5245 if (descriptor == nullptr) {
5246 return sp<BasicClient>{nullptr};
5247 }
5248 return descriptor->getValue();
5249}
5250
Austin Borgered99f642023-06-01 16:51:35 -07005251std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005252 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005253 std::ostringstream ret;
5254 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005255 bool hasAny = false;
5256 for (auto& i : all) {
5257 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005258 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005259 int32_t cost = i->getCost();
5260 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005261 int32_t score = i->getPriority().getScore();
5262 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005263 auto conflicting = i->getConflicting();
5264 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005265 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005266 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005267 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005268 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005269 uid_t clientUid = clientSp->getClientUid();
5270 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005271 }
Austin Borgered99f642023-06-01 16:51:35 -07005272 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5273 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005274
Ruben Brunk6267b532015-04-30 17:44:07 -07005275 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005276 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005277 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005278 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005279 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005280 }
5281
Austin Borgered99f642023-06-01 16:51:35 -07005282 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005283 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005284 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005285 }
Austin Borgered99f642023-06-01 16:51:35 -07005286 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005287 }
Austin Borgered99f642023-06-01 16:51:35 -07005288 if (hasAny) ret << "\n";
5289 ret << "]\n";
5290 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005291}
5292
5293CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005294 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5295 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005296 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005297
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005298 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005299 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005300
Austin Borgered99f642023-06-01 16:51:35 -07005301 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005302 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5303 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005304}
5305
5306CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005307 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005308 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005309 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005310 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005311 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5312 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005313}
5314
5315// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005316// InjectionStatusListener
5317// ----------------------------------------------------------------------------
5318
5319void CameraService::InjectionStatusListener::addListener(
5320 const sp<ICameraInjectionCallback>& callback) {
5321 Mutex::Autolock lock(mListenerLock);
5322 if (mCameraInjectionCallback) return;
5323 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5324 if (res == OK) {
5325 mCameraInjectionCallback = callback;
5326 }
5327}
5328
5329void CameraService::InjectionStatusListener::removeListener() {
5330 Mutex::Autolock lock(mListenerLock);
5331 if (mCameraInjectionCallback == nullptr) {
5332 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5333 return;
5334 }
5335 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5336 mCameraInjectionCallback = nullptr;
5337}
5338
5339void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005340 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005341 if (mCameraInjectionCallback == nullptr) {
5342 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5343 return;
5344 }
Cliff Wud3a05312021-04-26 23:07:31 +08005345
5346 switch (err) {
5347 case -ENODEV:
5348 mCameraInjectionCallback->onInjectionError(
5349 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5350 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005351 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005352 break;
5353 case -EBUSY:
5354 mCameraInjectionCallback->onInjectionError(
5355 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5356 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005357 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005358 break;
5359 case DEAD_OBJECT:
5360 mCameraInjectionCallback->onInjectionError(
5361 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5362 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005363 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005364 break;
5365 case INVALID_OPERATION:
5366 mCameraInjectionCallback->onInjectionError(
5367 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5368 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005369 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005370 break;
5371 case UNKNOWN_TRANSACTION:
5372 mCameraInjectionCallback->onInjectionError(
5373 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5374 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005375 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005376 break;
5377 default:
5378 mCameraInjectionCallback->onInjectionError(
5379 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5380 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005381 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005382 }
Cliff Wud8cae102021-03-11 01:37:42 +08005383}
5384
5385void CameraService::InjectionStatusListener::binderDied(
5386 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005387 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5388 auto parent = mParent.promote();
5389 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005390 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5391 if (clientDescriptor != nullptr) {
5392 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5393 baseClientPtr->stopInjection();
5394 }
Cliff Wu3b268182021-07-06 15:44:43 +08005395 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005396 }
5397}
5398
5399// ----------------------------------------------------------------------------
5400// CameraInjectionSession
5401// ----------------------------------------------------------------------------
5402
5403binder::Status CameraService::CameraInjectionSession::stopInjection() {
5404 Mutex::Autolock lock(mInjectionSessionLock);
5405 auto parent = mParent.promote();
5406 if (parent == nullptr) {
5407 ALOGE("CameraInjectionSession: Parent is gone");
5408 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5409 "Camera service encountered error");
5410 }
Cliff Wud3a05312021-04-26 23:07:31 +08005411
5412 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005413 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5414 if (clientDescriptor != nullptr) {
5415 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5416 res = baseClientPtr->stopInjection();
5417 if (res != OK) {
5418 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5419 " ret != NO_ERROR: %d", res);
5420 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5421 "Camera session encountered error");
5422 }
5423 }
Cliff Wu3b268182021-07-06 15:44:43 +08005424 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005425 return binder::Status::ok();
5426}
5427
5428// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005429
5430static const int kDumpLockRetries = 50;
5431static const int kDumpLockSleep = 60000;
5432
5433static bool tryLock(Mutex& mutex)
5434{
5435 bool locked = false;
5436 for (int i = 0; i < kDumpLockRetries; ++i) {
5437 if (mutex.tryLock() == NO_ERROR) {
5438 locked = true;
5439 break;
5440 }
5441 usleep(kDumpLockSleep);
5442 }
5443 return locked;
5444}
5445
Rucha Katakwardf223072021-06-15 10:21:00 -07005446void CameraService::cacheDump() {
5447 if (mMemFd != -1) {
5448 const Vector<String16> args;
5449 ATRACE_CALL();
5450 // Acquiring service lock here will avoid the deadlock since
5451 // cacheDump will not be called during the second disconnect.
5452 Mutex::Autolock lock(mServiceLock);
5453
5454 Mutex::Autolock l(mCameraStatesLock);
5455 // Start collecting the info for open sessions and store it in temp file.
5456 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005457 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005458 auto clientDescriptor = mActiveClientManager.get(cameraId);
5459 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005460 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005461 // Log the current open session info before device is disconnected.
5462 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5463 }
5464 }
5465 }
5466}
5467
Mathias Agopian65ab4712010-07-14 17:59:35 -07005468status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005469 ATRACE_CALL();
5470
Austin Borgered99f642023-06-01 16:51:35 -07005471 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005472 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005473 getCallingPid(),
5474 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005475 return NO_ERROR;
5476 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005477 bool locked = tryLock(mServiceLock);
5478 // failed to lock - CameraService is probably deadlocked
5479 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005480 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005481 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005482
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005483 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005484 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005485
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005486 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005487 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005488
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005489 if (locked) mServiceLock.unlock();
5490 return NO_ERROR;
5491 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005492 dprintf(fd, "\n== Service global info: ==\n\n");
5493 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005494 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005495 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5496 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005497 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5498 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5499 }
Austin Borgered99f642023-06-01 16:51:35 -07005500 std::string activeClientString = mActiveClientManager.toString();
5501 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5502 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005503 if (mStreamUseCaseOverrides.size() > 0) {
5504 dprintf(fd, "Active stream use case overrides:");
5505 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5506 dprintf(fd, " %" PRId64, useCaseOverride);
5507 }
5508 dprintf(fd, "\n");
5509 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005510
5511 dumpEventLog(fd);
5512
5513 bool stateLocked = tryLock(mCameraStatesLock);
5514 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005515 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005516 }
5517
Emilian Peevbd8c5032018-02-14 23:05:40 +00005518 int argSize = args.size();
5519 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005520 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005521 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005522 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005523 }
5524 break;
5525 }
5526 }
5527
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005528 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005529 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005530
Austin Borgered99f642023-06-01 16:51:35 -07005531 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005532
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005533 CameraParameters p = state.second->getShimParams();
5534 if (!p.isEmpty()) {
5535 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5536 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005537 }
5538
5539 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005540 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005541 // log the current open session info
5542 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005543 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005544 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005545 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005546
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005547 }
5548
5549 if (stateLocked) mCameraStatesLock.unlock();
5550
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005551 if (locked) mServiceLock.unlock();
5552
Emilian Peevf53f66e2017-04-11 14:29:43 +01005553 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005554
5555 dprintf(fd, "\n== Vendor tags: ==\n\n");
5556
5557 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5558 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005559 sp<VendorTagDescriptorCache> cache =
5560 VendorTagDescriptorCache::getGlobalVendorTagCache();
5561 if (cache == NULL) {
5562 dprintf(fd, "No vendor tags.\n");
5563 } else {
5564 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5565 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005566 } else {
5567 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5568 }
5569
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005570 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005571 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005572 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005573
5574 // Process dump arguments, if any
5575 int n = args.size();
5576 String16 verboseOption("-v");
5577 String16 unreachableOption("--unreachable");
5578 for (int i = 0; i < n; i++) {
5579 if (args[i] == verboseOption) {
5580 // change logging level
5581 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005582 std::string levelStr = toStdString(args[i+1]);
5583 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005584 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005585 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005586 } else if (args[i] == unreachableOption) {
5587 // Dump memory analysis
5588 // TODO - should limit be an argument parameter?
5589 UnreachableMemoryInfo info;
5590 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5591 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005592 dprintf(fd, "\n== Unable to dump unreachable memory. "
5593 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005594 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005595 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005596 std::string s = info.ToString(/*log_contents*/ true);
5597 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005598 }
5599 }
5600 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005601
5602 bool serviceLocked = tryLock(mServiceLock);
5603
5604 // Dump info from previous open sessions.
5605 // Reposition the offset to beginning of the file before reading
5606
5607 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5608 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5609 ssize_t size_read;
5610 char buf[4096];
5611 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5612 // Read data from file to a small buffer and write it to fd.
5613 write(fd, buf, size_read);
5614 if (size_read == -1) {
5615 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5616 break;
5617 }
5618 }
5619 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5620 } else {
5621 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5622 }
5623
5624 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005625 return NO_ERROR;
5626}
5627
Rucha Katakwardf223072021-06-15 10:21:00 -07005628void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005629 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005630 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005631 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005632 getFormattedCurrentTime().c_str(),
5633 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005634 dprintf(fd, " Client priority score: %d state: %d\n",
5635 clientDescriptor->getPriority().getScore(),
5636 clientDescriptor->getPriority().getState());
5637 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5638
5639 auto client = clientDescriptor->getValue();
5640 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005641 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005642
5643 client->dumpClient(fd, args);
5644}
5645
Austin Borgered99f642023-06-01 16:51:35 -07005646void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005647 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005648 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005649}
5650
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005651void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005652 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005653
5654 Mutex::Autolock l(mLogLock);
5655 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005656 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005657 }
5658
5659 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005660 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005661 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005662 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005663 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005664 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005665}
5666
Austin Borgered99f642023-06-01 16:51:35 -07005667void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005668 Mutex::Autolock lock(mLogLock);
5669 if (!isClientWatchedLocked(client)) { return; }
5670
5671 std::vector<std::string> dumpVector;
5672 client->dumpWatchedEventsToVector(dumpVector);
5673
5674 if (dumpVector.empty()) { return; }
5675
Austin Borgered99f642023-06-01 16:51:35 -07005676 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005677
Austin Borgered99f642023-06-01 16:51:35 -07005678 std::string currentTime = getFormattedCurrentTime();
5679 dumpString << "Cached @ ";
5680 dumpString << currentTime;
5681 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005682
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005683 size_t i = dumpVector.size();
5684
5685 // Store the string in reverse order (latest last)
5686 while (i > 0) {
5687 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005688 dumpString << cameraId;
5689 dumpString << ":";
5690 dumpString << client->getPackageName();
5691 dumpString << " ";
5692 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005693 }
5694
Austin Borgered99f642023-06-01 16:51:35 -07005695 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005696}
5697
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005698void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005699 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005700 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5701 if (mTorchClientMap[i] == who) {
5702 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005703 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005704 status_t res = mFlashlight->setTorchMode(cameraId, false);
5705 if (res) {
5706 ALOGE("%s: torch client died but couldn't turn off torch: "
5707 "%s (%d)", __FUNCTION__, strerror(-res), res);
5708 return;
5709 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005710 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005711 break;
5712 }
5713 }
5714}
5715
Ruben Brunkcc776712015-02-17 20:18:47 -08005716/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005717
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005718 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005719 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5720 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005721 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005722 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005723 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005724
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005725 // check torch client
5726 handleTorchClientBinderDied(who);
5727
5728 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005729 if(!evictClientIdByRemote(who)) {
5730 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005731 return;
5732 }
5733
Ruben Brunkcc776712015-02-17 20:18:47 -08005734 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5735 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005736}
5737
Austin Borgered99f642023-06-01 16:51:35 -07005738void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005739 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005740}
5741
Austin Borgered99f642023-06-01 16:51:35 -07005742void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005743 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005744 // Do not lock mServiceLock here or can get into a deadlock from
5745 // connect() -> disconnect -> updateStatus
5746
5747 auto state = getCameraState(cameraId);
5748
5749 if (state == nullptr) {
5750 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005751 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005752 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005753 }
5754
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005755 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5756 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5757 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005758 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005759 return;
5760 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005761
Biswarup Pal37a75182024-01-16 15:53:35 +00005762 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5763 CameraMetadata cameraInfo;
5764 status_t res = mCameraProviderManager->getCameraCharacteristics(
5765 cameraId, false, &cameraInfo, false);
5766 if (res != OK) {
5767 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5768 __FUNCTION__, cameraId.c_str());
5769 } else {
5770 int32_t deviceId = getDeviceId(cameraInfo);
5771 if (deviceId != kDefaultDeviceId) {
5772 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5773 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5774 static_cast<camera_metadata_enum_android_lens_facing_t>(
5775 lensFacingEntry.data.u8[0]);
5776 std::string mappedCameraId;
5777 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5778 mappedCameraId = kVirtualDeviceBackCameraId;
5779 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5780 mappedCameraId = kVirtualDeviceFrontCameraId;
5781 } else {
5782 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5783 __func__);
5784 }
5785 if (!mappedCameraId.empty()) {
5786 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5787 }
5788 }
5789 }
5790 }
5791
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005792 // Collect the logical cameras without holding mStatusLock in updateStatus
5793 // as that can lead to a deadlock(b/162192331).
5794 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005795 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005796 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005797 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005798 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005799 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005800 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5801 auto [deviceId, mappedCameraId] =
5802 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005803
Biswarup Pal37a75182024-01-16 15:53:35 +00005804 if (status != StatusInternal::ENUMERATING) {
5805 // Update torch status if it has a flash unit.
5806 Mutex::Autolock al(mTorchStatusMutex);
5807 TorchModeStatus torchStatus;
5808 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5809 NAME_NOT_FOUND) {
5810 TorchModeStatus newTorchStatus =
5811 status == StatusInternal::PRESENT ?
5812 TorchModeStatus::AVAILABLE_OFF :
5813 TorchModeStatus::NOT_AVAILABLE;
5814 if (torchStatus != newTorchStatus) {
5815 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5816 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005817 }
5818 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005819
Biswarup Pal37a75182024-01-16 15:53:35 +00005820 Mutex::Autolock lock(mStatusListenerLock);
5821 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5822 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005823
Biswarup Pal37a75182024-01-16 15:53:35 +00005824 for (auto& listener : mListenerList) {
5825 bool isVendorListener = listener->isVendorListener();
5826 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5827 listener->getListenerPid(), listener->getListenerUid())) {
5828 ALOGV("Skipping discovery callback for system-only camera device %s",
5829 cameraId.c_str());
5830 continue;
5831 }
5832
5833 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5834 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005835 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005836 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005837 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5838 ret.exceptionCode());
Biswarup Pal37a75182024-01-16 15:53:35 +00005839
5840 // Only cameras of the default device can be remapped to a different camera
5841 // (using remapCameraIds method), so do the following only if the camera is
5842 // associated with the default device.
5843 if (deviceId == kDefaultDeviceId) {
5844 // For the default device, also trigger the callbacks for cameras that were
5845 // remapped to the current cameraId for the specific package that this
5846 // listener belongs to.
5847 std::vector<std::string> remappedCameraIds =
5848 findOriginalIdsForRemappedCameraId(cameraId,
5849 listener->getListenerUid());
5850 for (auto &remappedCameraId: remappedCameraIds) {
5851 ret = listener->getListener()->onStatusChanged(
5852 mapToInterface(status), remappedCameraId, kDefaultDeviceId);
5853 listener->handleBinderStatus(ret,
5854 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
5855 __FUNCTION__, listener->getListenerUid(),
5856 listener->getListenerPid(), ret.exceptionCode());
5857 }
5858 }
malikakash82ed4352023-07-21 22:44:34 +00005859 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005860 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005861}
5862
Austin Borgered99f642023-06-01 16:51:35 -07005863void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5864 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005865 auto state = getCameraState(cameraId);
5866 if (state == nullptr) {
5867 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005868 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005869 return;
5870 }
5871 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005872 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005873 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005874 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005875 }
5876
Biswarup Pal37a75182024-01-16 15:53:35 +00005877 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5878 auto [deviceId, mappedCameraId] =
5879 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5880
Shuzhen Wang695044d2020-03-06 09:02:23 -08005881 Mutex::Autolock lock(mStatusListenerLock);
5882
5883 for (const auto& it : mListenerList) {
5884 if (!it->isOpenCloseCallbackAllowed()) {
5885 continue;
5886 }
5887
5888 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005889 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005890 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5891 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005892 } else {
Biswarup Pal37a75182024-01-16 15:53:35 +00005893 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005894 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005895
5896 it->handleBinderStatus(ret,
5897 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5898 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005899 }
5900}
5901
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005902template<class Func>
5903void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005904 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005905 std::initializer_list<StatusInternal> rejectSourceStates,
5906 Func onStatusUpdatedLocked) {
5907 Mutex::Autolock lock(mStatusLock);
5908 StatusInternal oldStatus = mStatus;
5909 mStatus = status;
5910
5911 if (oldStatus == status) {
5912 return;
5913 }
5914
5915 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005916 cameraId.c_str(), oldStatus, status);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005917
5918 if (oldStatus == StatusInternal::NOT_PRESENT &&
5919 (status != StatusInternal::PRESENT &&
5920 status != StatusInternal::ENUMERATING)) {
5921
5922 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5923 __FUNCTION__);
5924 mStatus = oldStatus;
5925 return;
5926 }
5927
5928 /**
5929 * Sometimes we want to conditionally do a transition.
5930 * For example if a client disconnects, we want to go to PRESENT
5931 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5932 */
5933 for (auto& rejectStatus : rejectSourceStates) {
5934 if (oldStatus == rejectStatus) {
5935 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005936 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005937 mStatus = oldStatus;
5938 return;
5939 }
5940 }
5941
5942 onStatusUpdatedLocked(cameraId, status);
5943}
5944
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005945status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005946 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005947 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005948 if (!status) {
5949 return BAD_VALUE;
5950 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005951 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5952 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005953 // invalid camera ID or the camera doesn't have a flash unit
5954 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005955 }
5956
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005957 *status = mTorchStatusMap.valueAt(index);
5958 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005959}
5960
Austin Borgered99f642023-06-01 16:51:35 -07005961status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005962 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005963 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5964 if (index == NAME_NOT_FOUND) {
5965 return BAD_VALUE;
5966 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005967 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005968
5969 return OK;
5970}
5971
Austin Borgered99f642023-06-01 16:51:35 -07005972std::list<std::string> CameraService::getLogicalCameras(
5973 const std::string& physicalCameraId) {
5974 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005975 Mutex::Autolock lock(mCameraStatesLock);
5976 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005977 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5978 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005979 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005980 }
5981 return retList;
5982}
5983
5984void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005985 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00005986 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005987 // mStatusListenerLock is expected to be locked
5988 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005989 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005990 // Note: we check only the deviceKind of the physical camera id
5991 // since, logical camera ids and their physical camera ids are
5992 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005993 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5994 listener->getListenerPid(), listener->getListenerUid())) {
5995 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005996 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005997 continue;
5998 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005999 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00006000 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07006001 listener->handleBinderStatus(ret,
6002 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
6003 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
6004 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08006005 }
6006 }
6007}
6008
Svet Ganova453d0d2018-01-11 15:37:58 -08006009void CameraService::blockClientsForUid(uid_t uid) {
6010 const auto clients = mActiveClientManager.getAll();
6011 for (auto& current : clients) {
6012 if (current != nullptr) {
6013 const auto basicClient = current->getValue();
6014 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
6015 basicClient->block();
6016 }
6017 }
6018 }
6019}
6020
Michael Grooverd1d435a2018-12-18 17:39:42 -08006021void CameraService::blockAllClients() {
6022 const auto clients = mActiveClientManager.getAll();
6023 for (auto& current : clients) {
6024 if (current != nullptr) {
6025 const auto basicClient = current->getValue();
6026 if (basicClient.get() != nullptr) {
6027 basicClient->block();
6028 }
6029 }
6030 }
6031}
6032
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00006033void CameraService::blockPrivacyEnabledClients() {
6034 const auto clients = mActiveClientManager.getAll();
6035 for (auto& current : clients) {
6036 if (current != nullptr) {
6037 const auto basicClient = current->getValue();
6038 if (basicClient.get() != nullptr) {
6039 std::string pkgName = basicClient->getPackageName();
6040 bool cameraPrivacyEnabled =
6041 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
6042 if (cameraPrivacyEnabled) {
6043 basicClient->block();
6044 }
6045 }
6046 }
6047 }
6048}
6049
Svet Ganova453d0d2018-01-11 15:37:58 -08006050// NOTE: This is a remote API - make sure all args are validated
6051status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006052 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006053 return PERMISSION_DENIED;
6054 }
6055 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
6056 return BAD_VALUE;
6057 }
Austin Borgered99f642023-06-01 16:51:35 -07006058 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006059 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006060 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006061 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006062 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006063 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07006064 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006065 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07006066 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006067 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07006068 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006069 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07006070 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006071 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07006072 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006073 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07006074 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006075 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07006076 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006077 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07006078 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006079 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07006080 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006081 handleClearStreamUseCaseOverrides();
6082 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07006083 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006084 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07006085 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006086 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07006087 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00006088 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07006089 } else if (args.size() >= 4 && args[0] == toString16("remap-camera-id")) {
malikakash82ed4352023-07-21 22:44:34 +00006090 return handleCameraIdRemapping(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006091 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006092 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006093 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08006094 }
6095 printHelp(err);
6096 return BAD_VALUE;
6097}
6098
malikakash82ed4352023-07-21 22:44:34 +00006099status_t CameraService::handleCameraIdRemapping(const Vector<String16>& args, int err) {
6100 uid_t uid = IPCThreadState::self()->getCallingUid();
6101 if (uid != AID_ROOT) {
6102 dprintf(err, "Must be adb root\n");
6103 return PERMISSION_DENIED;
6104 }
6105 if (args.size() != 4) {
6106 dprintf(err, "Expected format: remap-camera-id <PACKAGE> <Id0> <Id1>\n");
6107 return BAD_VALUE;
6108 }
Austin Borgered99f642023-06-01 16:51:35 -07006109 std::string packageName = toStdString(args[1]);
6110 std::string cameraIdToReplace = toStdString(args[2]);
6111 std::string cameraIdNew = toStdString(args[3]);
malikakash82ed4352023-07-21 22:44:34 +00006112 remapCameraIds({{packageName, {{cameraIdToReplace, cameraIdNew}}}});
6113 return OK;
6114}
6115
Svet Ganova453d0d2018-01-11 15:37:58 -08006116status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006117 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006118
Svet Ganova453d0d2018-01-11 15:37:58 -08006119 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07006120 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006121 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07006122 } else if ((args[2] != toString16("idle"))) {
6123 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08006124 return BAD_VALUE;
6125 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006126
6127 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006128 if (args.size() >= 5 && args[3] == toString16("--user")) {
6129 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006130 }
6131
6132 uid_t uid;
6133 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
6134 return BAD_VALUE;
6135 }
6136
6137 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08006138 return NO_ERROR;
6139}
6140
6141status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006142 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006143
6144 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006145 if (args.size() >= 4 && args[2] == toString16("--user")) {
6146 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006147 }
6148
6149 uid_t uid;
6150 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006151 return BAD_VALUE;
6152 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006153
6154 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08006155 return NO_ERROR;
6156}
6157
6158status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006159 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006160
6161 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006162 if (args.size() >= 4 && args[2] == toString16("--user")) {
6163 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006164 }
6165
6166 uid_t uid;
6167 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006168 return BAD_VALUE;
6169 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006170
6171 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006172 return dprintf(out, "active\n");
6173 } else {
6174 return dprintf(out, "idle\n");
6175 }
6176}
6177
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006178status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006179 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006180 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
6181 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
6182 Mutex::Autolock lock(mServiceLock);
6183
6184 mOverrideRotateAndCropMode = rotateValue;
6185
6186 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6187
6188 const auto clients = mActiveClientManager.getAll();
6189 for (auto& current : clients) {
6190 if (current != nullptr) {
6191 const auto basicClient = current->getValue();
6192 if (basicClient.get() != nullptr) {
6193 basicClient->setRotateAndCropOverride(rotateValue);
6194 }
6195 }
6196 }
6197
6198 return OK;
6199}
6200
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006201status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6202 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006203 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006204 if ((*end != '\0') ||
6205 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6206 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6207 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6208 return BAD_VALUE;
6209 }
6210
6211 Mutex::Autolock lock(mServiceLock);
6212 mOverrideAutoframingMode = autoframingValue;
6213
6214 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6215
6216 const auto clients = mActiveClientManager.getAll();
6217 for (auto& current : clients) {
6218 if (current != nullptr) {
6219 const auto basicClient = current->getValue();
6220 if (basicClient.get() != nullptr) {
6221 basicClient->setAutoframingOverride(autoframingValue);
6222 }
6223 }
6224 }
6225
6226 return OK;
6227}
6228
Ravneetaeb20dc2022-03-30 05:33:03 +00006229status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006230 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006231
6232 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6233
6234 Mutex::Autolock lock(mServiceLock);
6235
6236 mCameraServiceWatchdogEnabled = enableWatchdog;
6237
6238 const auto clients = mActiveClientManager.getAll();
6239 for (auto& current : clients) {
6240 if (current != nullptr) {
6241 const auto basicClient = current->getValue();
6242 if (basicClient.get() != nullptr) {
6243 basicClient->setCameraServiceWatchdog(enableWatchdog);
6244 }
6245 }
6246 }
6247
6248 return OK;
6249}
6250
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006251status_t CameraService::handleGetRotateAndCrop(int out) {
6252 Mutex::Autolock lock(mServiceLock);
6253
6254 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6255}
6256
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006257status_t CameraService::handleGetAutoframing(int out) {
6258 Mutex::Autolock lock(mServiceLock);
6259
6260 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6261}
6262
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006263status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6264 char *endPtr;
6265 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006266 std::string maskString = toStdString(args[1]);
6267 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006268
6269 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006270 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006271 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6272
6273 Mutex::Autolock lock(mServiceLock);
6274
6275 mImageDumpMask = maskValue;
6276
6277 return OK;
6278}
6279
6280status_t CameraService::handleGetImageDumpMask(int out) {
6281 Mutex::Autolock lock(mServiceLock);
6282
6283 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6284}
6285
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006286status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006287 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006288 if (errno != 0) return BAD_VALUE;
6289
6290 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6291 Mutex::Autolock lock(mServiceLock);
6292
6293 mOverrideCameraMuteMode = (muteValue == 1);
6294
6295 const auto clients = mActiveClientManager.getAll();
6296 for (auto& current : clients) {
6297 if (current != nullptr) {
6298 const auto basicClient = current->getValue();
6299 if (basicClient.get() != nullptr) {
6300 if (basicClient->supportsCameraMute()) {
6301 basicClient->setCameraMute(mOverrideCameraMuteMode);
6302 }
6303 }
6304 }
6305 }
6306
6307 return OK;
6308}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006309
Shuzhen Wang16610a62022-12-15 22:38:07 -08006310status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6311 std::vector<int64_t> useCasesOverride;
6312 for (size_t i = 1; i < args.size(); i++) {
6313 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006314 std::string arg = toStdString(args[i]);
6315 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006316 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006317 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006318 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006319 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006320 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006321 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006322 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006323 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006324 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006325 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006326 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006327 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006328 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6329 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006330 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006331 return BAD_VALUE;
6332 }
6333 useCasesOverride.push_back(useCase);
6334 }
6335
6336 Mutex::Autolock lock(mServiceLock);
6337 mStreamUseCaseOverrides = std::move(useCasesOverride);
6338
6339 return OK;
6340}
6341
6342void CameraService::handleClearStreamUseCaseOverrides() {
6343 Mutex::Autolock lock(mServiceLock);
6344 mStreamUseCaseOverrides.clear();
6345}
6346
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006347status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6348 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006349 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006350 if ((*end != '\0') ||
6351 (zoomOverrideValue != -1 &&
6352 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6353 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6354 return BAD_VALUE;
6355 }
6356
6357 Mutex::Autolock lock(mServiceLock);
6358 mZoomOverrideValue = zoomOverrideValue;
6359
6360 const auto clients = mActiveClientManager.getAll();
6361 for (auto& current : clients) {
6362 if (current != nullptr) {
6363 const auto basicClient = current->getValue();
6364 if (basicClient.get() != nullptr) {
6365 if (basicClient->supportsZoomOverride()) {
6366 basicClient->setZoomOverride(mZoomOverrideValue);
6367 }
6368 }
6369 }
6370 }
6371
6372 return OK;
6373}
6374
Avichal Rakesh84147132021-11-11 17:47:11 -08006375status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006376 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006377 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006378 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006379 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006380 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006381 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006382 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006383 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006384 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006385 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006386 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006387 dprintf(outFd, "Camera service watch commands:\n"
6388 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6389 " starts watching the provided tags for clients with provided package\n"
6390 " recognizes tag shorthands like '3a'\n"
6391 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006392 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006393 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006394 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006395 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006396 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006397 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006398 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006399}
6400
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006401status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6402 Mutex::Autolock lock(mLogLock);
6403 size_t tagsIdx; // index of '-m'
6404 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006405 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006406 if (tagsIdx < args.size() - 1) {
6407 tags = args[tagsIdx + 1];
6408 } else {
6409 dprintf(outFd, "No tags provided.\n");
6410 return BAD_VALUE;
6411 }
6412
6413 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006414 // watch all clients if no clients are provided
6415 String16 clients = toString16(kWatchAllClientsFlag);
6416 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006417 clientsIdx++);
6418 if (clientsIdx < args.size() - 1) {
6419 clients = args[clientsIdx + 1];
6420 }
Austin Borgered99f642023-06-01 16:51:35 -07006421 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006422
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006423 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006424 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006425
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006426 bool serviceLock = tryLock(mServiceLock);
6427 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006428 auto cameraClients = mActiveClientManager.getAll();
6429 for (const auto &clientDescriptor: cameraClients) {
6430 if (clientDescriptor == nullptr) { continue; }
6431 sp<BasicClient> client = clientDescriptor->getValue();
6432 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006433
6434 if (isClientWatchedLocked(client.get())) {
6435 client->startWatchingTags(mMonitorTags, outFd);
6436 numWatchedClients++;
6437 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006438 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006439 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6440
6441 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006442 return OK;
6443}
6444
6445status_t CameraService::stopWatchingTags(int outFd) {
6446 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006447 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006448 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006449
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006450 mWatchedClientPackages.clear();
6451 mWatchedClientsDumpCache.clear();
6452
6453 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006454 auto cameraClients = mActiveClientManager.getAll();
6455 for (const auto &clientDescriptor : cameraClients) {
6456 if (clientDescriptor == nullptr) { continue; }
6457 sp<BasicClient> client = clientDescriptor->getValue();
6458 if (client.get() == nullptr) { continue; }
6459 client->stopWatchingTags(outFd);
6460 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006461 dprintf(outFd, "Stopped watching all clients.\n");
6462 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006463 return OK;
6464}
6465
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006466status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6467 Mutex::Autolock lock(mLogLock);
6468 size_t clearedSize = mWatchedClientsDumpCache.size();
6469 mWatchedClientsDumpCache.clear();
6470 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6471 return OK;
6472}
6473
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006474status_t CameraService::printWatchedTags(int outFd) {
6475 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006476 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006477
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006478 bool printedSomething = false; // tracks if any monitoring information was printed
6479 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006480
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006481 bool serviceLock = tryLock(mServiceLock);
6482 // get all watched clients that are currently connected
6483 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6484 if (clientDescriptor == nullptr) { continue; }
6485
6486 sp<BasicClient> client = clientDescriptor->getValue();
6487 if (client.get() == nullptr) { continue; }
6488 if (!isClientWatchedLocked(client.get())) { continue; }
6489
6490 std::vector<std::string> dumpVector;
6491 client->dumpWatchedEventsToVector(dumpVector);
6492
6493 size_t printIdx = dumpVector.size();
6494 if (printIdx == 0) {
6495 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006496 }
6497
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006498 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006499 const std::string &cameraId = clientDescriptor->getKey();
6500 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006501 while(printIdx > 0) {
6502 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006503 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006504 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006505 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006506 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006507 printedSomething = true;
6508
6509 connectedMonitoredClients.emplace(client->getPackageName());
6510 }
6511 if (serviceLock) { mServiceLock.unlock(); }
6512
6513 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6514 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006515 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006516 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6517 continue;
6518 }
6519
Austin Borgered99f642023-06-01 16:51:35 -07006520 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006521 dprintf(outFd, "%s\n", kv.second.c_str());
6522 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006523 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006524
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006525 if (!printedSomething) {
6526 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006527 }
6528
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006529 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006530}
6531
Avichal Rakesh84147132021-11-11 17:47:11 -08006532// Print all events in vector `events' that came after lastPrintedEvent
6533void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006534 const std::string &cameraId,
6535 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006536 const std::vector<std::string> &events,
6537 const std::string &lastPrintedEvent) {
6538 if (events.empty()) { return; }
6539
6540 // index of lastPrintedEvent in events.
6541 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6542 size_t lastPrintedIdx;
6543 for (lastPrintedIdx = 0;
6544 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6545 lastPrintedIdx++);
6546
6547 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6548
Avichal Rakesh84147132021-11-11 17:47:11 -08006549 // print events in chronological order (latest event last)
6550 size_t idxToPrint = lastPrintedIdx;
6551 do {
6552 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006553 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6554 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006555 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006556}
6557
6558// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6559// command should be interrupted if the user presses the return key, or if user loses any way to
6560// signal interrupt.
6561// If timeoutMs == 0, this function will always return false
6562bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6563 struct timeval startTime;
6564 int startTimeError = gettimeofday(&startTime, nullptr);
6565 if (startTimeError) {
6566 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6567 return true;
6568 }
6569
6570 const nfds_t numFds = 1;
6571 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6572
6573 struct timeval currTime;
6574 char buffer[2];
6575 while(true) {
6576 int currTimeError = gettimeofday(&currTime, nullptr);
6577 if (currTimeError) {
6578 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6579 return true;
6580 }
6581
6582 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6583 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6584 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6585
6586 if (remainingTimeMs <= 0) {
6587 // No user interrupt within timeoutMs, don't interrupt watch command
6588 return false;
6589 }
6590
6591 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6592 if (numFdsUpdated < 0) {
6593 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6594 return true;
6595 }
6596
6597 if (numFdsUpdated == 0) {
6598 // No user input within timeoutMs, don't interrupt watch command
6599 return false;
6600 }
6601
6602 if (!(pollFd.revents & POLLIN)) {
6603 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6604 return true;
6605 }
6606
6607 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6608 if (sizeRead < 0) {
6609 dprintf(outFd, "Error reading user input. Exiting.\n");
6610 return true;
6611 }
6612
6613 if (sizeRead == 0) {
6614 // Reached end of input fd (can happen if input is piped)
6615 // User has no way to signal an interrupt, so interrupt here
6616 return true;
6617 }
6618
6619 if (buffer[0] == '\n') {
6620 // User pressed return, interrupt watch command.
6621 return true;
6622 }
6623 }
6624}
6625
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006626status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6627 int inFd, int outFd) {
6628 // Figure out refresh interval, if present in args
6629 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006630 if (args.size() > 2) {
6631 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006632 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006633 intervalIdx++);
6634
6635 size_t intervalValIdx = intervalIdx + 1;
6636 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006637 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006638 if (errno) { return BAD_VALUE; }
6639 }
6640 }
6641
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006642 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6643 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006644
Avichal Rakesh84147132021-11-11 17:47:11 -08006645 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006646 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006647
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006648 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006649 bool serviceLock = tryLock(mServiceLock);
6650 auto cameraClients = mActiveClientManager.getAll();
6651 if (serviceLock) { mServiceLock.unlock(); }
6652
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006653 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006654 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006655 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006656
6657 sp<BasicClient> client = clientDescriptor->getValue();
6658 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006659 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006660
Austin Borgered99f642023-06-01 16:51:35 -07006661 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006662 // This also initializes the map entries with an empty string
6663 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6664
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006665 std::vector<std::string> latestEvents;
6666 client->dumpWatchedEventsToVector(latestEvents);
6667
6668 if (!latestEvents.empty()) {
6669 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006670 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006671 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006672 latestEvents,
6673 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006674 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006675 }
6676 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006677 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006678 break;
6679 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006680 }
6681 return OK;
6682}
6683
Austin Borgered99f642023-06-01 16:51:35 -07006684void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006685 mWatchedClientPackages.clear();
6686
Austin Borgered99f642023-06-01 16:51:35 -07006687 std::istringstream iss(clients);
6688 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006689
Austin Borgered99f642023-06-01 16:51:35 -07006690 while (std::getline(iss, nextClient, ',')) {
6691 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006692 // Don't need to track any other package if 'all' is present
6693 mWatchedClientPackages.clear();
6694 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6695 break;
6696 }
6697
6698 // track package names
6699 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006700 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006701}
6702
Svet Ganova453d0d2018-01-11 15:37:58 -08006703status_t CameraService::printHelp(int out) {
6704 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006705 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6706 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6707 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006708 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6709 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6710 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006711 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6712 " Valid values 0=false, 1=true, 2=auto\n"
6713 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006714 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6715 " Valid values 0=OFF, 1=ON for JPEG\n"
6716 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006717 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006718 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6719 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6720 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6721 " on. In case the number of usecases is smaller than the number of streams, the\n"
6722 " last use case is assigned to all the remaining streams. In case of multiple\n"
6723 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6724 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6725 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6726 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006727 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6728 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006729 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6730 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006731 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
malikakash73125c62023-07-21 22:44:34 +00006732 " remap-camera-id <PACKAGE> <Id0> <Id1> remaps camera ids. Must use adb root\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006733 " help print this message\n");
6734}
6735
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006736bool CameraService::isClientWatched(const BasicClient *client) {
6737 Mutex::Autolock lock(mLogLock);
6738 return isClientWatchedLocked(client);
6739}
6740
6741bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6742 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6743 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6744}
6745
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006746int32_t CameraService::updateAudioRestriction() {
6747 Mutex::Autolock lock(mServiceLock);
6748 return updateAudioRestrictionLocked();
6749}
6750
6751int32_t CameraService::updateAudioRestrictionLocked() {
6752 int32_t mode = 0;
6753 // iterate through all active client
6754 for (const auto& i : mActiveClientManager.getAll()) {
6755 const auto clientSp = i->getValue();
6756 mode |= clientSp->getAudioRestriction();
6757 }
6758
6759 bool modeChanged = (mAudioRestriction != mode);
6760 mAudioRestriction = mode;
6761 if (modeChanged) {
6762 mAppOps.setCameraAudioRestriction(mode);
6763 }
6764 return mode;
6765}
6766
Austin Borgered99f642023-06-01 16:51:35 -07006767status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006768 sp<BasicClient> clientSp) {
6769 std::unique_ptr<AutoConditionLock> lock =
6770 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6771 status_t res = NO_ERROR;
6772 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006773 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006774 mInjectionStatusListener->notifyInjectionError(
6775 externalCamId, UNKNOWN_TRANSACTION);
6776 clientSp->notifyError(
6777 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6778 CaptureResultExtras());
6779
6780 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6781 // other clients from connecting in mServiceLockWrapper if held
6782 mServiceLock.unlock();
6783
6784 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006785 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006786 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006787 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006788
6789 // Reacquire mServiceLock
6790 mServiceLock.lock();
6791 }
6792
6793 return res;
6794}
6795
Cliff Wud3a05312021-04-26 23:07:31 +08006796void CameraService::clearInjectionParameters() {
6797 {
6798 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006799 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006800 mInjectionInternalCamId = "";
6801 }
6802 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006803 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006804}
6805
Biswarup Pal37a75182024-01-16 15:53:35 +00006806} // namespace android