blob: 4730393edb4888a7f83410aa79fab2d3a4ba08d9 [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(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000382 cameraId, false, &cameraInfo,
383 hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +0000384 int32_t deviceId = kDefaultDeviceId;
385 if (res != OK) {
386 ALOGW("%s: Not able to get camera characteristics for camera id %s",
387 __FUNCTION__, cameraId.c_str());
388 } else {
389 deviceId = getDeviceId(cameraInfo);
390 }
391 // Cameras associated with non-default device id's (i.e., virtual cameras) can never be
392 // system cameras, so skip for non-default device id's.
393 if (deviceId != kDefaultDeviceId) {
394 continue;
395 }
396 }
397
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700398 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Biswarup Pal37a75182024-01-16 15:53:35 +0000399 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
400 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700401 continue;
402 }
403 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700404 // All system camera ids will necessarily come after public camera
405 // device ids as per the HAL interface contract.
406 break;
407 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000408 mNormalDeviceIdsWithoutSystemCamera.push_back(cameraId);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700409 }
410 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
411 mNormalDeviceIdsWithoutSystemCamera.size());
412}
413
Austin Borgered99f642023-06-01 16:51:35 -0700414status_t CameraService::getSystemCameraKind(const std::string& cameraId,
415 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700416 auto state = getCameraState(cameraId);
417 if (state != nullptr) {
418 *kind = state->getSystemCameraKind();
419 return OK;
420 }
421 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700422 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700423}
424
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800425void CameraService::updateCameraNumAndIds() {
426 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700427 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
428 // Excludes hidden secure cameras
429 mNumberOfCameras =
430 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
431 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800432 mNormalDeviceIds =
433 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700434 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800435}
436
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700437void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700438 // To claim to be S Performance primary cameras, the cameras must be
439 // backward compatible. So performance class primary camera Ids must be API1
440 // compatible.
441 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
442 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
443 int facing = -1;
444 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800445 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000446 getDeviceVersion(cameraId,
447 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
448 /*out*/&portraitRotation, /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700449 if (facing == -1) {
450 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
451 return;
452 }
453
454 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
455 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700456 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
457 if (res == OK) {
458 mPerfClassPrimaryCameraIds.insert(cameraId);
459 } else {
460 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
461 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
462 break;
463 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700464
465 if (facing == hardware::CAMERA_FACING_BACK) {
466 firstRearCameraSeen = true;
467 }
468 if (facing == hardware::CAMERA_FACING_FRONT) {
469 firstFrontCameraSeen = true;
470 }
471 }
472
473 if (firstRearCameraSeen && firstFrontCameraSeen) {
474 break;
475 }
476 }
477}
478
Austin Borgered99f642023-06-01 16:51:35 -0700479void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700480 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100481 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
482 if (res != OK) {
483 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
484 return;
485 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000486 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700487 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
488 if (res != OK) {
489 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
490 return;
491 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000492 std::vector<std::string> physicalCameraIds;
493 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700494 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100495 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700496 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100497 }
498
499 {
500 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700501 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000502 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100503 }
504
Austin Borgered99f642023-06-01 16:51:35 -0700505 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100506 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700507 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800508
Austin Borgered99f642023-06-01 16:51:35 -0700509 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100510 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800511
512 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700513 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100514}
515
Austin Borgered99f642023-06-01 16:51:35 -0700516void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800517 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700518 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100519 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700520 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100521 }
522
523 {
524 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700525 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100526 }
527}
528
Austin Borgered99f642023-06-01 16:51:35 -0700529void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800530 CameraDeviceStatus newHalStatus) {
531 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700532 cameraId.c_str(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700533
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800534 StatusInternal newStatus = mapToInternal(newHalStatus);
535
Austin Borgered99f642023-06-01 16:51:35 -0700536 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800537
538 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700539 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100540 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700541 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100542
543 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700544 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100545
Austin Borgered99f642023-06-01 16:51:35 -0700546 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700547 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700548 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700549 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700550 return;
551 }
552
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800553 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800554
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800555 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800556 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700557 return;
558 }
559
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800560 if (newStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000561 logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
562 oldStatus, newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800563 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
564 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700565 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000566 mVirtualDeviceCameraIdMapper.removeCamera(cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800567
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800568 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700569 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800570 // Don't do this in updateStatus to avoid deadlock over mServiceLock
571 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700572
Ruben Brunkcc776712015-02-17 20:18:47 -0800573 // Remove cached shim parameters
574 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700575
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800576 // Remove online as well as offline client from the list of active clients,
577 // if they are present
Austin Borgered99f642023-06-01 16:51:35 -0700578 clientToDisconnectOnline = removeClientLocked(cameraId);
579 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700580 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800581
Austin Borgered99f642023-06-01 16:51:35 -0700582 disconnectClient(cameraId, clientToDisconnectOnline);
583 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700584
Austin Borgered99f642023-06-01 16:51:35 -0700585 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800586 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800587 if (oldStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000588 logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
589 oldStatus, newStatus));
Ruben Brunka8ca9152015-04-07 14:23:40 -0700590 }
Austin Borgered99f642023-06-01 16:51:35 -0700591 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700592 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800593}
Igor Murashkincba2c162013-03-20 15:56:31 -0700594
Austin Borgered99f642023-06-01 16:51:35 -0700595void CameraService::onDeviceStatusChanged(const std::string& id,
596 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800597 CameraDeviceStatus newHalStatus) {
598 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700599 __FUNCTION__, id.c_str(), physicalId.c_str(), newHalStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800600
601 StatusInternal newStatus = mapToInternal(newHalStatus);
602
603 std::shared_ptr<CameraState> state = getCameraState(id);
604
605 if (state == nullptr) {
606 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700607 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800608 return;
609 }
610
611 StatusInternal logicalCameraStatus = state->getStatus();
612 if (logicalCameraStatus != StatusInternal::PRESENT &&
613 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
614 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Austin Borgered99f642023-06-01 16:51:35 -0700615 __FUNCTION__, physicalId.c_str(), newHalStatus, logicalCameraStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800616 return;
617 }
618
619 bool updated = false;
620 if (newStatus == StatusInternal::PRESENT) {
621 updated = state->removeUnavailablePhysicalId(physicalId);
622 } else {
623 updated = state->addUnavailablePhysicalId(physicalId);
624 }
625
626 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700627 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800628 if (newStatus == StatusInternal::PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000629 logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800630 } else {
Henri Chataingbcb99452023-11-01 17:40:30 +0000631 logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800632 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700633 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
634 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
635 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700636 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700637 return;
638 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800639 Mutex::Autolock lock(mStatusListenerLock);
640 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700641 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
642 listener->getListenerPid(), listener->getListenerUid())) {
643 ALOGV("Skipping discovery callback for system-only camera device %s",
644 id.c_str());
645 continue;
646 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700647 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Biswarup Pal37a75182024-01-16 15:53:35 +0000648 mapToInterface(newStatus), id, physicalId, kDefaultDeviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700649 listener->handleBinderStatus(ret,
650 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
651 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
652 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800653 }
654 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700655}
656
Austin Borgered99f642023-06-01 16:51:35 -0700657void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800658 if (clientToDisconnect.get() != nullptr) {
659 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700660 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800661 // Notify the client of disconnection
662 clientToDisconnect->notifyError(
663 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
664 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800665 clientToDisconnect->disconnect();
666 }
667}
668
Austin Borgered99f642023-06-01 16:51:35 -0700669void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800670 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700671 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
672 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
673 if (res != OK) {
674 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700675 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700676 return;
677 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800678 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700679 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800680}
681
Austin Borgered99f642023-06-01 16:51:35 -0700682void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700683 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
684 Mutex::Autolock al(mTorchStatusMutex);
685 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
686}
687
Austin Borgered99f642023-06-01 16:51:35 -0700688void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800689 int32_t newStrengthLevel) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000690 // Get the device id and app-visible camera id for the given HAL-visible camera id.
691 auto [deviceId, mappedCameraId] =
692 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
693
Rucha Katakwar38284522021-11-10 11:25:21 -0800694 Mutex::Autolock lock(mStatusListenerLock);
695 for (auto& i : mListenerList) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000696 auto ret = i->getListener()->onTorchStrengthLevelChanged(mappedCameraId,
697 newStrengthLevel, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700698 i->handleBinderStatus(ret,
699 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
700 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800701 }
702}
703
Austin Borgered99f642023-06-01 16:51:35 -0700704void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700705 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800706 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700707 __FUNCTION__, cameraId.c_str(), newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800708
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800709 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800710 status_t res = getTorchStatusLocked(cameraId, &status);
711 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700712 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700713 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800714 return;
715 }
716 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800717 return;
718 }
719
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800720 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800721 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800722 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
723 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800724 return;
725 }
726
Ruben Brunkcc776712015-02-17 20:18:47 -0800727 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700728 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700729 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700730 auto iter = mTorchUidMap.find(cameraId);
731 if (iter != mTorchUidMap.end()) {
732 int oldUid = iter->second.second;
733 int newUid = iter->second.first;
734 BatteryNotifier& notifier(BatteryNotifier::getInstance());
735 if (oldUid != newUid) {
736 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800737 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700738 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700739 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800740 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700741 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700742 }
743 iter->second.second = newUid;
744 } else {
745 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800746 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700747 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700748 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700749 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700750 }
751 }
752 }
753 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700754 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800755}
756
Austin Borger249e6592024-03-10 22:28:11 -0700757bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700758 // Returns false if this is not an automotive device type.
759 if (!isAutomotiveDevice())
760 return false;
761
762 // Returns false if no camera id is provided.
Austin Borger1c1bee02023-06-01 16:51:35 -0700763 if (cam_id.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700764 return false;
765
766 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
767 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
768 // This isn't a known camera ID, so it's not a system camera.
769 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
770 return false;
771 }
772
773 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
774 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
775 return false;
776 }
777
778 CameraMetadata cameraInfo;
779 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000780 cam_id, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700781 if (res != OK){
782 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
783 cam_id.c_str());
784 return false;
785 }
786
787 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
788 if (auto_location.count != 1)
789 return false;
790
791 uint8_t location = auto_location.data.u8[0];
792 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
793 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
794 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
795 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
796 return false;
797 }
798
799 return true;
800}
801
Biswarup Pal37a75182024-01-16 15:53:35 +0000802Status CameraService::getNumberOfCameras(int32_t type, int32_t deviceId, int32_t devicePolicy,
803 int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700804 ATRACE_CALL();
Biswarup Pal37a75182024-01-16 15:53:35 +0000805 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
806 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
807 *numCameras = mVirtualDeviceCameraIdMapper.getNumberOfCameras(deviceId);
808 return Status::ok();
809 }
810
Emilian Peevaee727d2017-05-04 16:35:48 +0100811 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700812 bool hasSystemCameraPermissions =
Austin Borger22c5c852024-03-08 13:31:36 -0800813 hasPermissionsForSystemCamera(std::string(), getCallingPid(),
814 getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700815 switch (type) {
816 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700817 if (hasSystemCameraPermissions) {
818 *numCameras = static_cast<int>(mNormalDeviceIds.size());
819 } else {
820 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
821 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800822 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700823 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700824 if (hasSystemCameraPermissions) {
825 *numCameras = mNumberOfCameras;
826 } else {
827 *numCameras = mNumberOfCamerasWithoutSystemCamera;
828 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800829 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700830 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800831 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700832 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800833 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
834 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700835 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800836 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700837}
838
malikakash73125c62023-07-21 22:44:34 +0000839Status CameraService::remapCameraIds(const hardware::CameraIdRemapping& cameraIdRemapping) {
Austin Borgered99f642023-06-01 16:51:35 -0700840 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -0800841 const int pid = getCallingPid();
842 const int uid = getCallingUid();
malikakash82ed4352023-07-21 22:44:34 +0000843 ALOGE("%s: Permission Denial: can't configure camera ID mapping pid=%d, uid=%d",
844 __FUNCTION__, pid, uid);
845 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
846 "Permission Denial: no permission to configure camera id mapping");
847 }
848 TCameraIdRemapping cameraIdRemappingMap{};
malikakash214f6e62023-08-10 23:50:56 +0000849 binder::Status parseStatus = parseCameraIdRemapping(cameraIdRemapping, &cameraIdRemappingMap);
malikakash82ed4352023-07-21 22:44:34 +0000850 if (!parseStatus.isOk()) {
851 return parseStatus;
852 }
853 remapCameraIds(cameraIdRemappingMap);
854 return Status::ok();
855}
856
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700857Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
Biswarup Pal37a75182024-01-16 15:53:35 +0000858 int32_t deviceId, int32_t devicePolicy,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700859 /* out */
860 hardware::camera2::impl::CameraMetadataNative* request) {
861 ATRACE_CALL();
862
863 if (!flags::feature_combination_query()) {
864 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
865 "Camera subsystem doesn't support this method!");
866 }
867 if (!mInitialized) {
868 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
869 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
870 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
871 }
872
Biswarup Pal37a75182024-01-16 15:53:35 +0000873 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
874 devicePolicy, getCallingUid());
875 if (!cameraIdOptional.has_value()) {
876 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
877 unresolvedCameraId.c_str(), deviceId);
878 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
879 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
880 }
881 std::string cameraId = cameraIdOptional.value();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700882
883 binder::Status res;
884 if (request == nullptr) {
885 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
886 "Camera %s: Error creating default request", cameraId.c_str());
887 return res;
888 }
889 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
890 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
891 cameraId, templateId, &tempId);
892 if (!res.isOk()) {
893 ALOGE("%s: Camera %s: failed to map request Template %d",
894 __FUNCTION__, cameraId.c_str(), templateId);
895 return res;
896 }
897
898 if (shouldRejectSystemCameraConnection(cameraId)) {
899 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
900 "request for system only device %s: ", cameraId.c_str());
901 }
902
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700903 CameraMetadata metadata;
904 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
905 if (err == OK) {
906 request->swap(metadata);
907 } else if (err == BAD_VALUE) {
908 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
909 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
910 cameraId.c_str(), templateId, strerror(-err), err);
911 } else {
912 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
913 "Camera %s: Error creating default request for template %d: %s (%d)",
914 cameraId.c_str(), templateId, strerror(-err), err);
915 }
916 return res;
917}
918
919Status CameraService::isSessionConfigurationWithParametersSupported(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700920 const std::string& unresolvedCameraId, int targetSdkVersion,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700921 const SessionConfiguration& sessionConfiguration,
Biswarup Pal37a75182024-01-16 15:53:35 +0000922 int32_t deviceId, int32_t devicePolicy,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700923 /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700924 ATRACE_CALL();
925
926 if (!flags::feature_combination_query()) {
927 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
928 "Camera subsystem doesn't support this method!");
929 }
930 if (!mInitialized) {
931 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
932 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
933 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
934 }
935
Biswarup Pal37a75182024-01-16 15:53:35 +0000936 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
937 devicePolicy, getCallingUid());
938 if (!cameraIdOptional.has_value()) {
939 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
940 unresolvedCameraId.c_str(), deviceId);
941 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
942 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
943 }
944 std::string cameraId = cameraIdOptional.value();
945
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700946 if (supported == nullptr) {
947 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
948 unresolvedCameraId.c_str());
949 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
950 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
951 }
952
953 if (shouldRejectSystemCameraConnection(cameraId)) {
954 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
955 "session configuration with parameters support for system only device %s: ",
956 cameraId.c_str());
957 }
958
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700959 bool overrideForPerfClass = flags::calculate_perf_override_during_session_support() &&
960 SessionConfigurationUtils::targetPerfClassPrimaryCamera(
961 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
962
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700963 return isSessionConfigurationWithParametersSupportedUnsafe(cameraId, sessionConfiguration,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700964 overrideForPerfClass, supported);
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700965}
966
967Status CameraService::isSessionConfigurationWithParametersSupportedUnsafe(
968 const std::string& cameraId, const SessionConfiguration& sessionConfiguration,
969 bool overrideForPerfClass, /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700970 *supported = false;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700971 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(
972 cameraId, sessionConfiguration, overrideForPerfClass,
973 /*checkSessionParams=*/true, supported);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700974 binder::Status res;
975 switch (ret) {
976 case OK:
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700977 // Expected. Do Nothing.
978 return Status::ok();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700979 case INVALID_OPERATION: {
980 std::string msg = fmt::sprintf(
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700981 "Camera %s: Session configuration with parameters supported query not "
982 "supported!",
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700983 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700984 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
985 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
986 *supported = false;
987 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700988 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700989 break;
990 case NAME_NOT_FOUND: {
991 std::string msg = fmt::sprintf("Camera %s: Unknown camera ID.", cameraId.c_str());
992 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
993 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
994 *supported = false;
995 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
996 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700997 break;
998 default: {
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700999 std::string msg = fmt::sprintf(
1000 "Unable to retrieve session configuration support for camera "
1001 "device %s: Error: %s (%d)",
1002 cameraId.c_str(), strerror(-ret), ret);
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001003 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001004 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1005 *supported = false;
1006 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001007 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001008 break;
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001009 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001010}
1011
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001012Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001013 int targetSdkVersion, int rotationOverride,
Biswarup Pal37a75182024-01-16 15:53:35 +00001014 const SessionConfiguration& sessionConfiguration, int32_t deviceId, int32_t devicePolicy,
1015 /*out*/ CameraMetadata* outMetadata) {
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001016 ATRACE_CALL();
1017
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001018 if (outMetadata == nullptr) {
1019 std::string msg =
1020 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
1021 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1022 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1023 }
1024
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001025 if (!mInitialized) {
1026 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1027 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
1028 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
1029 }
1030
Biswarup Pal37a75182024-01-16 15:53:35 +00001031 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001032 devicePolicy, getCallingUid());
Biswarup Pal37a75182024-01-16 15:53:35 +00001033 if (!cameraIdOptional.has_value()) {
1034 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001035 unresolvedCameraId.c_str(), deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001036 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1037 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1038 }
1039 std::string cameraId = cameraIdOptional.value();
1040
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001041 if (shouldRejectSystemCameraConnection(cameraId)) {
1042 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1043 "Unable to retrieve camera"
1044 "characteristics for system only device %s: ",
1045 cameraId.c_str());
1046 }
1047
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001048 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1049 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001050 if (flags::check_session_support_before_session_char()) {
1051 bool sessionConfigSupported;
1052 Status res = isSessionConfigurationWithParametersSupportedUnsafe(
1053 cameraId, sessionConfiguration, overrideForPerfClass, &sessionConfigSupported);
1054 if (!res.isOk()) {
1055 // isSessionConfigurationWithParametersSupportedUnsafe should log what went wrong and
1056 // report the correct Status to send to the client. Simply forward the error to
1057 // the client.
1058 outMetadata->clear();
1059 return res;
1060 }
1061 if (!sessionConfigSupported) {
1062 std::string msg = fmt::sprintf(
1063 "Session configuration not supported for camera device %s.", cameraId.c_str());
1064 outMetadata->clear();
1065 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1066 }
1067 }
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001068
1069 status_t ret = mCameraProviderManager->getSessionCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001070 cameraId, sessionConfiguration, overrideForPerfClass, rotationOverride, outMetadata);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001071
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001072 switch (ret) {
1073 case OK:
1074 // Expected, no handling needed.
1075 break;
1076 case INVALID_OPERATION: {
1077 std::string msg = fmt::sprintf(
1078 "Camera %s: Session characteristics query not supported!",
1079 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001080 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001081 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1082 outMetadata->clear();
1083 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1084 }
1085 break;
1086 case NAME_NOT_FOUND: {
1087 std::string msg = fmt::sprintf(
1088 "Camera %s: Unknown camera ID.",
1089 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001090 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001091 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1092 outMetadata->clear();
1093 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001094 }
1095 break;
1096 default: {
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001097 std::string msg = fmt::sprintf(
1098 "Unable to retrieve session characteristics for camera device %s: "
1099 "Error: %s (%d)",
1100 cameraId.c_str(), strerror(-ret), ret);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001101 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001102 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1103 outMetadata->clear();
1104 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001105 }
1106 }
1107
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001108 return filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
1109}
1110
1111Status CameraService::filterSensitiveMetadataIfNeeded(
1112 const std::string& cameraId, CameraMetadata* metadata) {
1113 int callingPid = getCallingPid();
1114 int callingUid = getCallingUid();
1115
1116 if (callingPid == getpid()) {
1117 // Caller is cameraserver; no need to remove keys
1118 return Status::ok();
1119 }
1120
1121 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1122 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1123 ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
1124 metadata->clear();
1125 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1126 "Unable to retrieve camera kind for device %s", cameraId.c_str());
1127 }
1128 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
1129 // Attempting to query system only camera without system camera permission would have
1130 // failed the shouldRejectSystemCameraConnection in the caller. So if we get here
1131 // for a system only camera, then the caller has the required permission.
1132 // No need to remove keys
1133 return Status::ok();
1134 }
1135
1136 std::vector<int32_t> tagsRemoved;
Biswarup Pale506e732024-03-27 13:46:20 +00001137 // Get the device id that owns this camera.
1138 auto [cameraOwnerDeviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1139 cameraId);
1140 bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid,
1141 cameraOwnerDeviceId);
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001142 if (hasCameraPermission) {
1143 // Caller has camera permission; no need to remove keys
1144 return Status::ok();
1145 }
1146
1147 status_t ret = metadata->removePermissionEntries(
1148 mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1149 if (ret != OK) {
1150 metadata->clear();
1151 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1152 "Failed to remove camera characteristics needing camera permission "
1153 "for device %s:%s (%d)",
1154 cameraId.c_str(), strerror(-ret), ret);
1155 }
1156
1157 if (!tagsRemoved.empty()) {
1158 ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1159 tagsRemoved.data(), tagsRemoved.size());
1160 if (ret != OK) {
1161 metadata->clear();
1162 return STATUS_ERROR_FMT(
1163 ERROR_INVALID_OPERATION,
1164 "Failed to insert camera keys needing permission for device %s: %s (%d)",
1165 cameraId.c_str(), strerror(-ret), ret);
1166 }
1167 }
1168 return Status::ok();
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001169}
1170
malikakash82ed4352023-07-21 22:44:34 +00001171Status CameraService::parseCameraIdRemapping(
1172 const hardware::CameraIdRemapping& cameraIdRemapping,
malikakash214f6e62023-08-10 23:50:56 +00001173 /* out */ TCameraIdRemapping* cameraIdRemappingMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001174 std::string packageName;
1175 std::string cameraIdToReplace, updatedCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001176 for (const auto& packageIdRemapping: cameraIdRemapping.packageIdRemappings) {
malikakash82ed4352023-07-21 22:44:34 +00001177 packageName = packageIdRemapping.packageName;
malikakash0894f5b2023-08-10 22:46:47 +00001178 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001179 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1180 "CameraIdRemapping: Package name cannot be empty");
1181 }
malikakash214f6e62023-08-10 23:50:56 +00001182 if (packageIdRemapping.cameraIdsToReplace.size()
1183 != packageIdRemapping.updatedCameraIds.size()) {
malikakash82ed4352023-07-21 22:44:34 +00001184 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1185 "CameraIdRemapping: Mismatch in CameraId Remapping lists sizes for package %s",
malikakash73125c62023-07-21 22:44:34 +00001186 packageName.c_str());
malikakash82ed4352023-07-21 22:44:34 +00001187 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001188 for (size_t i = 0; i < packageIdRemapping.cameraIdsToReplace.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -07001189 cameraIdToReplace = packageIdRemapping.cameraIdsToReplace[i];
1190 updatedCameraId = packageIdRemapping.updatedCameraIds[i];
malikakash0894f5b2023-08-10 22:46:47 +00001191 if (cameraIdToReplace.empty() || updatedCameraId.empty()) {
malikakash214f6e62023-08-10 23:50:56 +00001192 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1193 "CameraIdRemapping: Camera Id cannot be empty for package %s",
Austin Borgered99f642023-06-01 16:51:35 -07001194 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001195 }
1196 if (cameraIdToReplace == updatedCameraId) {
1197 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1198 "CameraIdRemapping: CameraIdToReplace cannot be the same"
1199 " as updatedCameraId for %s",
Austin Borgered99f642023-06-01 16:51:35 -07001200 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001201 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001202
1203 // Do not allow any camera remapping that involves a virtual camera.
1204 auto [deviceIdForCameraToReplace, _] =
1205 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1206 cameraIdToReplace);
1207 if (deviceIdForCameraToReplace != kDefaultDeviceId) {
1208 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1209 "CameraIdRemapping: CameraIdToReplace cannot be a virtual camera");
1210 }
1211 [[maybe_unused]] auto [deviceIdForUpdatedCamera, unusedMappedCameraId] =
1212 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(updatedCameraId);
1213 if (deviceIdForUpdatedCamera != kDefaultDeviceId) {
1214 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1215 "CameraIdRemapping: UpdatedCameraId cannot be a virtual camera");
1216 }
1217
malikakash214f6e62023-08-10 23:50:56 +00001218 (*cameraIdRemappingMap)[packageName][cameraIdToReplace] = updatedCameraId;
malikakash82ed4352023-07-21 22:44:34 +00001219 }
1220 }
1221 return Status::ok();
1222}
1223
1224void CameraService::remapCameraIds(const TCameraIdRemapping& cameraIdRemapping) {
1225 // Acquire mServiceLock and prevent other clients from connecting
1226 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1227 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1228
malikakashedb38962023-09-06 00:03:35 +00001229 // Collect all existing clients for camera Ids that are being
1230 // remapped in the new cameraIdRemapping, but only if they were being used by a
1231 // targeted packageName.
malikakash82ed4352023-07-21 22:44:34 +00001232 std::vector<sp<BasicClient>> clientsToDisconnect;
Austin Borgered99f642023-06-01 16:51:35 -07001233 std::vector<std::string> cameraIdsToUpdate;
malikakash82ed4352023-07-21 22:44:34 +00001234 for (const auto& [packageName, injectionMap] : cameraIdRemapping) {
1235 for (auto& [id0, id1] : injectionMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001236 ALOGI("%s: UPDATE:= %s: %s: %s", __FUNCTION__, packageName.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001237 id0.c_str(), id1.c_str());
1238 auto clientDescriptor = mActiveClientManager.get(id0);
1239 if (clientDescriptor != nullptr) {
1240 sp<BasicClient> clientSp = clientDescriptor->getValue();
1241 if (clientSp->getPackageName() == packageName) {
malikakashedb38962023-09-06 00:03:35 +00001242 // This camera is being used by a targeted packageName and
1243 // being remapped to a new camera Id. We should disconnect it.
malikakash82ed4352023-07-21 22:44:34 +00001244 clientsToDisconnect.push_back(clientSp);
1245 cameraIdsToUpdate.push_back(id0);
1246 }
1247 }
1248 }
1249 }
1250
malikakashedb38962023-09-06 00:03:35 +00001251 for (auto& clientSp : clientsToDisconnect) {
malikakashf4c80f22023-09-25 21:50:28 +00001252 // Notify the clients about the disconnection.
1253 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
malikakashedb38962023-09-06 00:03:35 +00001254 CaptureResultExtras{});
1255 }
malikakash82ed4352023-07-21 22:44:34 +00001256
1257 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1258 // blocking other clients from connecting in mServiceLockWrapper if held.
1259 mServiceLock.unlock();
1260
malikakashedb38962023-09-06 00:03:35 +00001261 // Clear calling identity for disconnect() PID checks.
Austin Borger22c5c852024-03-08 13:31:36 -08001262 int64_t token = clearCallingIdentity();
malikakashedb38962023-09-06 00:03:35 +00001263
malikakash82ed4352023-07-21 22:44:34 +00001264 // Disconnect clients.
1265 for (auto& clientSp : clientsToDisconnect) {
malikakashedb38962023-09-06 00:03:35 +00001266 // This also triggers a call to updateStatus() which also reads mCameraIdRemapping
1267 // and requires mCameraIdRemappingLock.
malikakash82ed4352023-07-21 22:44:34 +00001268 clientSp->disconnect();
1269 }
1270
malikakashedb38962023-09-06 00:03:35 +00001271 // Invoke destructors (which call disconnect()) now while we don't hold the mServiceLock.
1272 clientsToDisconnect.clear();
1273
Austin Borger22c5c852024-03-08 13:31:36 -08001274 restoreCallingIdentity(token);
malikakash82ed4352023-07-21 22:44:34 +00001275 mServiceLock.lock();
malikakashedb38962023-09-06 00:03:35 +00001276
1277 {
1278 Mutex::Autolock lock(mCameraIdRemappingLock);
1279 // Update mCameraIdRemapping.
1280 mCameraIdRemapping.clear();
1281 mCameraIdRemapping.insert(cameraIdRemapping.begin(), cameraIdRemapping.end());
1282 }
malikakash82ed4352023-07-21 22:44:34 +00001283}
1284
malikakash22af94c2023-12-04 18:13:14 +00001285Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001286 const std::string& cameraId,
1287 const CameraMetadata& sessionParams) {
1288 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001289 const int pid = getCallingPid();
1290 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001291 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1292 __FUNCTION__, pid, uid);
1293 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1294 "Permission Denial: no permission to inject session params");
1295 }
1296
Biswarup Pal37a75182024-01-16 15:53:35 +00001297 // Do not allow session params injection for a virtual camera.
1298 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1299 if (deviceId != kDefaultDeviceId) {
1300 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1301 "Cannot inject session params for a virtual camera");
1302 }
1303
malikakash22af94c2023-12-04 18:13:14 +00001304 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1305 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1306
1307 auto clientDescriptor = mActiveClientManager.get(cameraId);
1308 if (clientDescriptor == nullptr) {
1309 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1310 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1311 "No active client for camera id %s", cameraId.c_str());
1312 }
1313
1314 sp<BasicClient> clientSp = clientDescriptor->getValue();
1315 status_t res = clientSp->injectSessionParams(sessionParams);
1316
1317 if (res != OK) {
1318 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1319 "Error injecting session params into camera \"%s\": %s (%d)",
1320 cameraId.c_str(), strerror(-res), res);
1321 }
1322 return Status::ok();
1323}
1324
Austin Borgered99f642023-06-01 16:51:35 -07001325std::vector<std::string> CameraService::findOriginalIdsForRemappedCameraId(
1326 const std::string& inputCameraId, int clientUid) {
1327 std::string packageName = getPackageNameFromUid(clientUid);
1328 std::vector<std::string> cameraIds;
malikakash82ed4352023-07-21 22:44:34 +00001329 Mutex::Autolock lock(mCameraIdRemappingLock);
1330 if (auto packageMapIter = mCameraIdRemapping.find(packageName);
1331 packageMapIter != mCameraIdRemapping.end()) {
1332 for (auto& [id0, id1]: packageMapIter->second) {
1333 if (id1 == inputCameraId) {
1334 cameraIds.push_back(id0);
1335 }
1336 }
1337 }
1338 return cameraIds;
1339}
1340
Austin Borgered99f642023-06-01 16:51:35 -07001341std::string CameraService::resolveCameraId(
1342 const std::string& inputCameraId,
malikakashedb38962023-09-06 00:03:35 +00001343 int clientUid,
Austin Borgered99f642023-06-01 16:51:35 -07001344 const std::string& packageName) {
1345 std::string packageNameVal = packageName;
malikakashedb38962023-09-06 00:03:35 +00001346 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001347 packageNameVal = getPackageNameFromUid(clientUid);
1348 }
malikakash65d20692023-09-07 01:06:33 +00001349 if (clientUid < AID_APP_START || packageNameVal.empty()) {
malikakashedb38962023-09-06 00:03:35 +00001350 // We shouldn't remap cameras for processes with system/vendor UIDs.
1351 return inputCameraId;
1352 }
malikakash82ed4352023-07-21 22:44:34 +00001353 Mutex::Autolock lock(mCameraIdRemappingLock);
1354 if (auto packageMapIter = mCameraIdRemapping.find(packageNameVal);
1355 packageMapIter != mCameraIdRemapping.end()) {
malikakash82ed4352023-07-21 22:44:34 +00001356 auto packageMap = packageMapIter->second;
1357 if (auto replacementIdIter = packageMap.find(inputCameraId);
1358 replacementIdIter != packageMap.end()) {
malikakashedb38962023-09-06 00:03:35 +00001359 ALOGI("%s: resolveCameraId: remapping cameraId %s for %s to %s",
malikakash82ed4352023-07-21 22:44:34 +00001360 __FUNCTION__, inputCameraId.c_str(),
malikakashedb38962023-09-06 00:03:35 +00001361 packageNameVal.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001362 replacementIdIter->second.c_str());
1363 return replacementIdIter->second;
1364 }
1365 }
1366 return inputCameraId;
1367}
1368
Biswarup Pal37a75182024-01-16 15:53:35 +00001369std::optional<std::string> CameraService::resolveCameraId(
1370 const std::string& inputCameraId,
1371 int32_t deviceId,
1372 int32_t devicePolicy,
1373 int clientUid,
1374 const std::string& packageName) {
1375 if ((deviceId == kDefaultDeviceId)
1376 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1377 auto [storedDeviceId, _] =
1378 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1379 if (storedDeviceId != kDefaultDeviceId) {
1380 // Trying to access a virtual camera from default-policy device context, we should fail.
1381 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1382 inputCameraId.c_str(), deviceId);
1383 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1384 return std::nullopt;
1385 }
1386 return resolveCameraId(inputCameraId, clientUid, packageName);
1387 }
1388
1389 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1390}
1391
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001392Status CameraService::getCameraInfo(int cameraId, int rotationOverride, int32_t deviceId,
Biswarup Pal37a75182024-01-16 15:53:35 +00001393 int32_t devicePolicy, CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001394 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001395 Mutex::Autolock l(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001396 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId, deviceId, devicePolicy);
1397 if (cameraIdStr.empty()) {
1398 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
1399 cameraId, deviceId);
1400 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1401 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1402 }
malikakashedb38962023-09-06 00:03:35 +00001403
Austin Borgered99f642023-06-01 16:51:35 -07001404 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001405 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1406 "characteristics for system only device %s: ", cameraIdStr.c_str());
1407 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001408
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001409 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001410 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001411 return STATUS_ERROR(ERROR_DISCONNECTED,
1412 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001413 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001414 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001415 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001416 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1417 if (hasSystemCameraPermissions) {
1418 cameraIdBound = mNumberOfCameras;
1419 }
1420 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001421 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1422 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001423 }
1424
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001425 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001426 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001427 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001428 cameraIdStr, rotationOverride, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001429 if (err != OK) {
1430 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1431 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1432 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001433 logServiceError(std::string("Error retrieving camera info from device ")
1434 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001435 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001436
Ruben Brunkcc776712015-02-17 20:18:47 -08001437 return ret;
1438}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001439
Biswarup Pal37a75182024-01-16 15:53:35 +00001440std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1441 int32_t deviceId, int32_t devicePolicy) {
1442 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1443 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1444 std::optional<std::string> cameraIdOptional =
1445 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1446 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1447 }
1448
1449 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001450 auto callingPid = getCallingPid();
1451 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001452 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1453 callingPid, callingUid, /* checkCameraPermissions= */ false);
1454 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001455 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001456 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001457 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1458 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1459 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001460 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001461 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001462
Biswarup Pal37a75182024-01-16 15:53:35 +00001463 std::string unresolvedCameraId = (*cameraIds)[cameraIdInt];
1464 return resolveCameraId(unresolvedCameraId, getCallingUid());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001465}
1466
Biswarup Pal37a75182024-01-16 15:53:35 +00001467std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1468 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001469 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001470 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001471}
1472
Austin Borgered99f642023-06-01 16:51:35 -07001473Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001474 int targetSdkVersion, int rotationOverride, int32_t deviceId, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +00001475 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001476 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001477
Zhijun He2b59be82013-09-25 10:14:30 -07001478 if (!cameraInfo) {
1479 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001480 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001481 }
1482
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001483 if (!mInitialized) {
1484 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001485 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001486 return STATUS_ERROR(ERROR_DISCONNECTED,
1487 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001488 }
1489
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
Austin Borgered99f642023-06-01 16:51:35 -07001500 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001501 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001502 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001503 }
1504
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001505 bool overrideForPerfClass =
1506 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001507 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001508 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001509 cameraId, overrideForPerfClass, cameraInfo, rotationOverride);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001510 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001511 if (res == NAME_NOT_FOUND) {
1512 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001513 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001514 strerror(-res), res);
1515 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001516 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1517 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001518 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001519 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001520 strerror(-res), res);
1521 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001522 }
Emilian Peeve20c6372018-08-14 18:45:53 +01001523
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001524 return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -07001525}
1526
Biswarup Pal37a75182024-01-16 15:53:35 +00001527Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId, int32_t deviceId,
1528 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001529 ATRACE_CALL();
1530 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001531
Biswarup Pal37a75182024-01-16 15:53:35 +00001532 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
1533 devicePolicy, getCallingUid());
1534 if (!cameraIdOptional.has_value()) {
1535 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1536 unresolvedCameraId.c_str(), deviceId);
1537 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1538 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1539 }
1540 std::string cameraId = cameraIdOptional.value();
1541
Rucha Katakwar38284522021-11-10 11:25:21 -08001542 if (!mInitialized) {
1543 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1544 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1545 }
1546
Biswarup Pal37a75182024-01-16 15:53:35 +00001547 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001548 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1549 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1550 }
1551
Austin Borgered99f642023-06-01 16:51:35 -07001552 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001553 if (res != OK) {
1554 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001555 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001556 strerror(-res), res);
1557 }
1558 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1559 return Status::ok();
1560}
1561
Austin Borgered99f642023-06-01 16:51:35 -07001562std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001563 time_t now = time(nullptr);
1564 char formattedTime[64];
1565 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001566 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001567}
1568
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001569Status CameraService::getCameraVendorTagDescriptor(
1570 /*out*/
1571 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001572 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001573 if (!mInitialized) {
1574 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001575 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001576 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001577 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1578 if (globalDescriptor != nullptr) {
1579 *desc = *(globalDescriptor.get());
1580 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001581 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001582}
1583
Emilian Peev71c73a22017-03-21 16:35:51 +00001584Status CameraService::getCameraVendorTagCache(
1585 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1586 ATRACE_CALL();
1587 if (!mInitialized) {
1588 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1589 return STATUS_ERROR(ERROR_DISCONNECTED,
1590 "Camera subsystem not available");
1591 }
1592 sp<VendorTagDescriptorCache> globalCache =
1593 VendorTagDescriptorCache::getGlobalVendorTagCache();
1594 if (globalCache != nullptr) {
1595 *cache = *(globalCache.get());
1596 }
1597 return Status::ok();
1598}
1599
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001600void CameraService::clearCachedVariables() {
1601 BasicClient::BasicClient::sCameraService = nullptr;
1602}
1603
Austin Borgered99f642023-06-01 16:51:35 -07001604std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001605 int rotationOverride, int* portraitRotation, int* facing,
1606 int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001607 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001608
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001609 int deviceVersion = 0;
1610
Emilian Peevf53f66e2017-04-11 14:29:43 +01001611 status_t res;
1612 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001613 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001614 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001615 if (res != OK || transport == IPCTransport::INVALID) {
1616 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001617 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001618 return std::make_pair(-1, IPCTransport::INVALID) ;
1619 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001620 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001621
Emilian Peevf53f66e2017-04-11 14:29:43 +01001622 hardware::CameraInfo info;
1623 if (facing) {
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001624 res = mCameraProviderManager->getCameraInfo(cameraId, rotationOverride,
Austin Borger18b30a72022-10-27 12:20:29 -07001625 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001626 if (res != OK) {
1627 return std::make_pair(-1, IPCTransport::INVALID);
1628 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001629 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001630 if (orientation) {
1631 *orientation = info.orientation;
1632 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001633 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001634
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001635 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001636}
1637
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001638Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001639 switch(err) {
1640 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001641 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001642 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001643 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1644 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001645 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001646 return STATUS_ERROR(ERROR_DISCONNECTED,
1647 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001648 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001649 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1650 "Camera HAL encountered error %d: %s",
1651 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001652 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001653}
1654
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001655Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001656 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1657 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001658 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001659 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001660 apiLevel effectiveApiLevel, bool overrideForPerfClass, int rotationOverride,
malikakash73125c62023-07-21 22:44:34 +00001661 bool forceSlowJpegMode, const std::string& originalCameraId,
1662 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001663 // For HIDL devices
1664 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1665 // Create CameraClient based on device version reported by the HAL.
1666 int deviceVersion = deviceVersionAndTransport.first;
1667 switch(deviceVersion) {
1668 case CAMERA_DEVICE_API_VERSION_1_0:
1669 ALOGE("Camera using old HAL version: %d", deviceVersion);
1670 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1671 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001672 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001673 break;
1674 case CAMERA_DEVICE_API_VERSION_3_0:
1675 case CAMERA_DEVICE_API_VERSION_3_1:
1676 case CAMERA_DEVICE_API_VERSION_3_2:
1677 case CAMERA_DEVICE_API_VERSION_3_3:
1678 case CAMERA_DEVICE_API_VERSION_3_4:
1679 case CAMERA_DEVICE_API_VERSION_3_5:
1680 case CAMERA_DEVICE_API_VERSION_3_6:
1681 case CAMERA_DEVICE_API_VERSION_3_7:
1682 break;
1683 default:
1684 // Should not be reachable
1685 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1686 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1687 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001688 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001689 }
1690 }
1691 if (effectiveApiLevel == API_1) { // Camera1 API route
1692 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001693 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001694 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001695 api1CameraId, facing, sensorOrientation,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001696 clientPid, clientUid, servicePid, overrideForPerfClass, rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00001697 forceSlowJpegMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001698 ALOGI("%s: Camera1 API (legacy), rotationOverride %d, forceSlowJpegMode %d",
1699 __FUNCTION__, rotationOverride, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001700 } else { // Camera2 API route
1701 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1702 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001703 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001704 cameraService->mCameraServiceProxyWrapper,
1705 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001706 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001707 overrideForPerfClass, rotationOverride, originalCameraId);
1708 ALOGI("%s: Camera2 API, rotationOverride %d", __FUNCTION__, rotationOverride);
Ruben Brunkcc776712015-02-17 20:18:47 -08001709 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001710 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001711}
1712
Austin Borgered99f642023-06-01 16:51:35 -07001713std::string CameraService::toString(std::set<userid_t> intSet) {
1714 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001715 bool first = true;
1716 for (userid_t i : intSet) {
1717 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001718 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001719 first = false;
1720 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001721 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001722 }
1723 }
Austin Borgered99f642023-06-01 16:51:35 -07001724 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001725}
1726
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001727int32_t CameraService::mapToInterface(TorchModeStatus status) {
1728 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1729 switch (status) {
1730 case TorchModeStatus::NOT_AVAILABLE:
1731 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1732 break;
1733 case TorchModeStatus::AVAILABLE_OFF:
1734 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1735 break;
1736 case TorchModeStatus::AVAILABLE_ON:
1737 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1738 break;
1739 default:
1740 ALOGW("Unknown new flash status: %d", status);
1741 }
1742 return serviceStatus;
1743}
1744
1745CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1746 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1747 switch (status) {
1748 case CameraDeviceStatus::NOT_PRESENT:
1749 serviceStatus = StatusInternal::NOT_PRESENT;
1750 break;
1751 case CameraDeviceStatus::PRESENT:
1752 serviceStatus = StatusInternal::PRESENT;
1753 break;
1754 case CameraDeviceStatus::ENUMERATING:
1755 serviceStatus = StatusInternal::ENUMERATING;
1756 break;
1757 default:
1758 ALOGW("Unknown new HAL device status: %d", status);
1759 }
1760 return serviceStatus;
1761}
1762
1763int32_t CameraService::mapToInterface(StatusInternal status) {
1764 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1765 switch (status) {
1766 case StatusInternal::NOT_PRESENT:
1767 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1768 break;
1769 case StatusInternal::PRESENT:
1770 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1771 break;
1772 case StatusInternal::ENUMERATING:
1773 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1774 break;
1775 case StatusInternal::NOT_AVAILABLE:
1776 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1777 break;
1778 case StatusInternal::UNKNOWN:
1779 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1780 break;
1781 default:
1782 ALOGW("Unknown new internal device status: %d", status);
1783 }
1784 return serviceStatus;
1785}
1786
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001787Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001788 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001789
Austin Borgered99f642023-06-01 16:51:35 -07001790 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001791 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001792 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001793 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001794 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1795 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001796 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001797 /*targetSdkVersion*/ __ANDROID_API_FUTURE__,
1798 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_OVERRIDE_TO_PORTRAIT,
Austin Borgered99f642023-06-01 16:51:35 -07001799 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001800 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001801 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001802 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001803 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001804}
1805
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001806Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001807 /*out*/
1808 CameraParameters* parameters) {
1809
1810 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1811
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001812 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001813
1814 if (parameters == NULL) {
1815 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001816 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001817 }
1818
malikakashedb38962023-09-06 00:03:35 +00001819 std::string unresolvedCameraId = std::to_string(cameraId);
1820 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08001821 getCallingUid());
Ruben Brunkcc776712015-02-17 20:18:47 -08001822
1823 // Check if we already have parameters
1824 {
1825 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001826 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001827 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001828 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001829 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001830 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001831 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001832 }
1833 CameraParameters p = cameraState->getShimParams();
1834 if (!p.isEmpty()) {
1835 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001836 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001837 }
1838 }
1839
Austin Borger22c5c852024-03-08 13:31:36 -08001840 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001841 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001842 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001843 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001844 // Error already logged by callee
1845 return ret;
1846 }
1847
1848 // Check for parameters again
1849 {
1850 // Scope for service lock
1851 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001852 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001853 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001854 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001855 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001856 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001857 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001858 CameraParameters p = cameraState->getShimParams();
1859 if (!p.isEmpty()) {
1860 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001861 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001862 }
1863 }
1864
Ruben Brunkcc776712015-02-17 20:18:47 -08001865 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1866 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001867 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001868}
1869
Austin Borgered99f642023-06-01 16:51:35 -07001870Status CameraService::validateConnectLocked(const std::string& cameraId,
1871 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001872 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001873
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001874#ifdef __BRILLO__
1875 UNUSED(clientName8);
1876 UNUSED(clientUid);
1877 UNUSED(clientPid);
1878 UNUSED(originalClientPid);
1879#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001880 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1881 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001882 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001883 return allowed;
1884 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001885#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001886
Austin Borger22c5c852024-03-08 13:31:36 -08001887 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001888
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001889 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001890 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1891 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001892 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001893 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001894 }
1895
Ruben Brunkcc776712015-02-17 20:18:47 -08001896 if (getCameraState(cameraId) == nullptr) {
1897 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001898 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001899 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001900 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001901 }
1902
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001903 status_t err = checkIfDeviceIsUsable(cameraId);
1904 if (err != NO_ERROR) {
1905 switch(err) {
1906 case -ENODEV:
1907 case -EBUSY:
1908 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001909 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001910 default:
1911 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001912 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001913 }
1914 }
1915 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001916}
1917
Austin Borgered99f642023-06-01 16:51:35 -07001918Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1919 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001920 /*out*/int& originalClientPid) const {
Austin Borger22c5c852024-03-08 13:31:36 -08001921 int callingPid = getCallingPid();
1922 int callingUid = getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001923
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001924 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001925 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001926 clientUid = callingUid;
1927 } else if (!isTrustedCallingUid(callingUid)) {
1928 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1929 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001930 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1931 "Untrusted caller (calling PID %d, UID %d) trying to "
1932 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001933 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001934 clientName.c_str(), clientPid, clientUid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001935 }
1936
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001937 // Check if we can trust clientPid
1938 if (clientPid == USE_CALLING_PID) {
1939 clientPid = callingPid;
1940 } else if (!isTrustedCallingUid(callingUid)) {
1941 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1942 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001943 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1944 "Untrusted caller (calling PID %d, UID %d) trying to "
1945 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001946 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001947 clientName.c_str(), clientPid, clientUid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001948 }
1949
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001950 if (shouldRejectSystemCameraConnection(cameraId)) {
1951 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1952 cameraId.c_str());
1953 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001954 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001955 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001956 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1957 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001958 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001959 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001960 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001961 }
1962
Biswarup Pale506e732024-03-27 13:46:20 +00001963 // Get the device id that owns this camera.
1964 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1965
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001966 // If it's not calling from cameraserver, check the permission if the
1967 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1968 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001969 bool checkPermissionForCamera =
Biswarup Pale506e732024-03-27 13:46:20 +00001970 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName, deviceId);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001971 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001972 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001973 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001974 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1975 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001976 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001977 }
1978
Svet Ganova453d0d2018-01-11 15:37:58 -08001979 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001980 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001981 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001982 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1983 clientPid, clientUid);
1984 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001985 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1986 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001987 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001988 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001989 }
1990
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001991 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1992 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1993 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1994 if ((!isAutomotivePrivilegedClient(callingUid) ||
1995 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1996 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001997 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1998 return STATUS_ERROR_FMT(ERROR_DISABLED,
1999 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07002000 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08002001 }
2002
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07002003 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
2004 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07002005 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07002006 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002007
Ruben Brunk6267b532015-04-30 17:44:07 -07002008 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08002009
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002010 // For non-system clients : Only allow clients who are being used by the current foreground
2011 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08002012 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08002013 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002014 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
2015 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07002016 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002017 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2018 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002019 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07002020 }
2021
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07002022 if (flags::camera_hsum_permission()) {
2023 // If the System User tries to access the camera when the device is running in
2024 // headless system user mode, ensure that client has the required permission
2025 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07002026 if (isHeadlessSystemUserMode()
2027 && (clientUserId == USER_SYSTEM)
2028 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07002029 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
2030 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2031 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
2032 User without camera headless system user permission",
Austin Borger249e6592024-03-10 22:28:11 -07002033 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07002034 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07002035 }
2036
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002037 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002038}
2039
Austin Borgered99f642023-06-01 16:51:35 -07002040status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08002041 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08002042 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08002043 if (cameraState == nullptr) {
2044 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07002045 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002046 return -ENODEV;
2047 }
2048
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002049 StatusInternal currentStatus = cameraState->getStatus();
2050 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002051 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07002052 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002053 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002054 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002055 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07002056 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002057 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07002058 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002059
Ruben Brunkcc776712015-02-17 20:18:47 -08002060 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08002061}
2062
Ruben Brunkcc776712015-02-17 20:18:47 -08002063void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002064 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08002065
Ruben Brunkcc776712015-02-17 20:18:47 -08002066 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002067 auto clientDescriptor =
2068 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002069 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08002070 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
2071
2072 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002073 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08002074
2075 if (evicted.size() > 0) {
2076 // This should never happen - clients should already have been removed in disconnect
2077 for (auto& i : evicted) {
2078 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07002079 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002080 }
2081
2082 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
2083 __FUNCTION__);
2084 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002085
2086 // And register a death notification for the client callback. Do
2087 // this last to avoid Binder policy where a nested Binder
2088 // transaction might be pre-empted to service the client death
2089 // notification if the client process dies before linkToDeath is
2090 // invoked.
2091 sp<IBinder> remoteCallback = client->getRemote();
2092 if (remoteCallback != nullptr) {
2093 remoteCallback->linkToDeath(this);
2094 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002095}
2096
Austin Borgered99f642023-06-01 16:51:35 -07002097status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
2098 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
2099 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08002100 /*out*/
2101 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07002102 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002103 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08002104 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002105 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08002106 DescriptorPtr clientDescriptor;
2107 {
2108 if (effectiveApiLevel == API_1) {
2109 // If we are using API1, any existing client for this camera ID with the same remote
2110 // should be returned rather than evicted to allow MediaRecorder to work properly.
2111
2112 auto current = mActiveClientManager.get(cameraId);
2113 if (current != nullptr) {
2114 auto clientSp = current->getValue();
2115 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002116 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07002117 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002118 " API level, evicting prior client...");
2119 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002120 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002121 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002122 *client = clientSp;
2123 return NO_ERROR;
2124 }
2125 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002126 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002127 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08002128
Ruben Brunkcc776712015-02-17 20:18:47 -08002129 // Get state for the given cameraId
2130 auto state = getCameraState(cameraId);
2131 if (state == nullptr) {
2132 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07002133 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002134 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07002135 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002136 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002137
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002138 sp<IServiceManager> sm = defaultServiceManager();
2139 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08002140 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002141 // If processinfo service is not available and the client is automotive privileged
2142 // client used for safety critical uses cases such as rear-view and surround-view which
2143 // needs to be available before android boot completes, then use the hardcoded values
2144 // for the process state and priority score. As this scenario is before android system
2145 // services are up and client is native client, hence using NATIVE_ADJ as the priority
2146 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
2147 // visible on the top.
2148 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2149 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2150 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
2151 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
2152 } else {
2153 // Get current active client PIDs
2154 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
2155 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002156
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002157 std::vector<int> priorityScores(ownerPids.size());
2158 std::vector<int> states(ownerPids.size());
2159
2160 // Get priority scores of all active PIDs
2161 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
2162 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
2163 if (err != OK) {
2164 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
2165 return err;
2166 }
2167
2168 // Update all active clients' priorities
2169 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
2170 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
2171 pidToPriorityMap.emplace(ownerPids[i],
2172 resource_policy::ClientPriority(priorityScores[i], states[i],
2173 /* isVendorClient won't get copied over*/ false,
2174 /* oomScoreOffset won't get copied over*/ 0));
2175 }
2176 mActiveClientManager.updatePriorities(pidToPriorityMap);
2177
2178 int32_t actualScore = priorityScores[priorityScores.size() - 1];
2179 int32_t actualState = states[states.size() - 1];
2180
2181 // Make descriptor for incoming client. We store the oomScoreOffset
2182 // since we might need it later on new handleEvictionsLocked and
2183 // ProcessInfoService would not take that into account.
2184 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2185 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2186 state->getConflicting(), actualScore, clientPid, actualState,
2187 oomScoreOffset, systemNativeClient);
2188 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002189
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002190 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
2191
Ruben Brunkcc776712015-02-17 20:18:47 -08002192 // Find clients that would be evicted
2193 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
2194
2195 // If the incoming client was 'evicted,' higher priority clients have the camera in the
2196 // background, so we cannot do evictions
2197 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2198 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2199 " priority).", clientPid);
2200
2201 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002202 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002203 auto incompatibleClients =
2204 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2205
Austin Borgered99f642023-06-01 16:51:35 -07002206 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2207 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2208 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002209 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002210
2211 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002212 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002213 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002214 i->getKey().c_str(),
2215 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002216 i->getOwnerId(), i->getPriority().getScore(),
2217 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002218 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002219 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2220 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002221 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002222 }
2223
2224 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002225 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002226 mEventLog.add(msg);
2227
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002228 auto current = mActiveClientManager.get(cameraId);
2229 if (current != nullptr) {
2230 return -EBUSY; // CAMERA_IN_USE
2231 } else {
2232 return -EUSERS; // MAX_CAMERAS_IN_USE
2233 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002234 }
2235
2236 for (auto& i : evicted) {
2237 sp<BasicClient> clientSp = i->getValue();
2238 if (clientSp.get() == nullptr) {
2239 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2240
2241 // TODO: Remove this
2242 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2243 __FUNCTION__);
2244 mActiveClientManager.remove(i);
2245 continue;
2246 }
2247
2248 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002249 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002250 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002251
Ruben Brunkcc776712015-02-17 20:18:47 -08002252 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002253 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002254 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2255 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002256 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002257 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002258 i->getPriority().getState(), cameraId.c_str(),
2259 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002260 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002261
2262 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002263 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002264 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002265 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002266 }
2267
Ruben Brunkcc776712015-02-17 20:18:47 -08002268 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2269 // other clients from connecting in mServiceLockWrapper if held
2270 mServiceLock.unlock();
2271
2272 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002273 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002274
2275 // Destroy evicted clients
2276 for (auto& i : evictedClients) {
2277 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002278 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002279 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002280
Austin Borger22c5c852024-03-08 13:31:36 -08002281 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002282
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002283 for (const auto& i : evictedClients) {
2284 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002285 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002286 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2287 if (ret == TIMED_OUT) {
2288 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002289 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2290 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002291 return -EBUSY;
2292 }
2293 if (ret != NO_ERROR) {
2294 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002295 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2296 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002297 return ret;
2298 }
2299 }
2300
2301 evictedClients.clear();
2302
Ruben Brunkcc776712015-02-17 20:18:47 -08002303 // Once clients have been disconnected, relock
2304 mServiceLock.lock();
2305
2306 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2307 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2308 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002309 }
2310
Ruben Brunkcc776712015-02-17 20:18:47 -08002311 *partial = clientDescriptor;
2312 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002313}
2314
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002315Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002316 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002317 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07002318 const std::string& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002319 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08002320 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002321 int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002322 int rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00002323 bool forceSlowJpegMode,
Biswarup Pal37a75182024-01-16 15:53:35 +00002324 int32_t deviceId,
2325 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002326 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002327 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002328 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002329 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002330
Biswarup Pal37a75182024-01-16 15:53:35 +00002331 std::string cameraIdStr = cameraIdIntToStr(api1CameraId, deviceId, devicePolicy);
2332 if (cameraIdStr.empty()) {
2333 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
2334 api1CameraId, deviceId);
2335 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2336 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2337 }
malikakashedb38962023-09-06 00:03:35 +00002338
Ruben Brunkcc776712015-02-17 20:18:47 -08002339 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002340 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
2341 clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002342 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002343 rotationOverride, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002344
Biswarup Pal37a75182024-01-16 15:53:35 +00002345 if (!ret.isOk()) {
2346 logRejected(cameraIdStr, getCallingPid(), clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002347 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002348 }
2349
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002350 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002351
2352 const sp<IServiceManager> sm(defaultServiceManager());
2353 const auto& mActivityManager = getActivityManager();
2354 if (mActivityManager) {
2355 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002356 getCallingUid(),
2357 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002358 }
2359
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002360 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002361}
2362
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002363bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2364 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002365 // If the client is not a vendor client, don't add listener if
2366 // a) the camera is a publicly hidden secure camera OR
2367 // b) the camera is a system only camera and the client doesn't
2368 // have android.permission.SYSTEM_CAMERA permissions.
2369 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2370 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002371 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002372 return true;
2373 }
2374 return false;
2375}
2376
Austin Borgered99f642023-06-01 16:51:35 -07002377bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002378 // Rules for rejection:
2379 // 1) If cameraserver tries to access this camera device, accept the
2380 // connection.
2381 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002382 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002383 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2384 // and the serving thread is a non hwbinder thread, the client must have
2385 // android.permission.SYSTEM_CAMERA permissions to connect.
2386
Austin Borger22c5c852024-03-08 13:31:36 -08002387 int cPid = getCallingPid();
2388 int cUid = getCallingUid();
2389 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002390 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2391 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002392 // This isn't a known camera ID, so it's not a system camera
2393 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2394 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002395 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002396
2397 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002398 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002399 return false;
2400 }
2401 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002402 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002403 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2404 return true;
2405 }
2406 // (3) Here we only check for permissions if it is a system only camera device. This is since
2407 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2408 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2409 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002410 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002411 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002412 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2413 cameraId.c_str());
2414 return true;
2415 }
2416
2417 return false;
2418}
2419
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002420Status CameraService::connectDevice(
2421 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002422 const std::string& unresolvedCameraId,
2423 const std::string& clientPackageName,
2424 const std::optional<std::string>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002425 int clientUid, int oomScoreOffset, int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002426 int rotationOverride, int32_t deviceId, int32_t devicePolicy,
Ruben Brunkcc776712015-02-17 20:18:47 -08002427 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002428 sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002429 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002430 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002431 sp<CameraDeviceClient> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002432 std::string clientPackageNameAdj = clientPackageName;
Austin Borger22c5c852024-03-08 13:31:36 -08002433 int callingPid = getCallingPid();
2434 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002435 bool systemNativeClient = false;
Austin Borger22c5c852024-03-08 13:31:36 -08002436 if (callerHasSystemUid() && (clientPackageNameAdj.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002437 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borgered99f642023-06-01 16:51:35 -07002438 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002439 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002440 }
Austin Borger249e6592024-03-10 22:28:11 -07002441
Biswarup Pal37a75182024-01-16 15:53:35 +00002442 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
2443 devicePolicy, callingUid, clientPackageNameAdj);
2444 if (!cameraIdOptional.has_value()) {
2445 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
2446 unresolvedCameraId.c_str(), deviceId);
2447 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2448 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2449 }
2450 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002451
2452 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002453 std::string msg =
2454 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
2455 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
2456 cameraId.c_str());
2457 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2458 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002459 }
2460
Austin Borger9bfa0a72022-08-03 17:50:40 -07002461 userid_t clientUserId = multiuser_get_user_id(clientUid);
Austin Borger9bfa0a72022-08-03 17:50:40 -07002462 if (clientUid == USE_CALLING_UID) {
2463 clientUserId = multiuser_get_user_id(callingUid);
2464 }
2465
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002466 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2467 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002468 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2469 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002470 std::string msg = "Camera disabled by device policy";
2471 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2472 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002473 }
2474
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002475 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002476 if (oomScoreOffset > 0
2477 && !hasPermissionsForSystemCamera(cameraId, callingPid,
Austin Borger249e6592024-03-10 22:28:11 -07002478 callingUid)
2479 && !isTrustedCallingUid(callingUid)) {
Austin Borgered99f642023-06-01 16:51:35 -07002480 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002481 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07002482 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2483 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2484 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002485 }
2486
Austin Borgered99f642023-06-01 16:51:35 -07002487 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
2488 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002489 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002490 targetSdkVersion, rotationOverride, /*forceSlowJpegMode*/false, unresolvedCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002491 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002492
Biswarup Pal37a75182024-01-16 15:53:35 +00002493 if (!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002494 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002495 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002496 }
2497
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002498 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002499 Mutex::Autolock lock(mServiceLock);
2500
2501 // Clear the previous cached logs and reposition the
2502 // file offset to beginning of the file to log new data.
2503 // If either truncate or lseek fails, close the previous file and create a new one.
2504 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2505 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2506 // Close the previous memfd.
2507 close(mMemFd);
2508 // If failure to wipe the data, then create a new file and
2509 // assign the new value to mMemFd.
2510 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2511 if (mMemFd == -1) {
2512 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2513 }
2514 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002515 const sp<IServiceManager> sm(defaultServiceManager());
2516 const auto& mActivityManager = getActivityManager();
2517 if (mActivityManager) {
2518 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002519 callingUid,
2520 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002521 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002522 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002523}
2524
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002525bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2526 int callingPid, int callingUid) {
2527 if (!isAutomotiveDevice()) {
2528 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2529 }
2530
2531 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2532 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2533 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2534 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2535 "using camera %s", callingUid, cam_id.c_str());
2536 return false;
2537 }
2538
2539 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2540 return true;
2541 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2542 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002543 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2544 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002545 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2546 return false;
2547 } else {
2548 return true;
2549 }
2550 }
2551 return false;
2552}
2553
Austin Borgered99f642023-06-01 16:51:35 -07002554std::string CameraService::getPackageNameFromUid(int clientUid) {
2555 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002556
Avichal Rakesh5788fec2024-03-15 14:39:20 -07002557 sp<IPermissionController> permCtrl;
2558 if (flags::cache_permission_services()) {
2559 permCtrl = getPermissionController();
2560 } else {
2561 sp<IServiceManager> sm = defaultServiceManager();
2562#pragma clang diagnostic push
2563#pragma clang diagnostic ignored "-Wdeprecated-declarations"
2564 // Using deprecated function to preserve functionality until the
2565 // cache_permission_services flag is removed.
2566 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
2567#pragma clang diagnostic pop
2568 if (binder == 0) {
2569 ALOGE("Cannot get permission service");
2570 permCtrl = nullptr;
2571 } else {
2572 permCtrl = interface_cast<IPermissionController>(binder);
2573 }
2574 }
2575
2576 if (permCtrl == nullptr) {
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002577 // Return empty package name and the further interaction
2578 // with camera will likely fail
2579 return packageName;
2580 }
2581
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002582 Vector<String16> packages;
2583
2584 permCtrl->getPackagesForUid(clientUid, packages);
2585
2586 if (packages.isEmpty()) {
2587 ALOGE("No packages for calling UID %d", clientUid);
2588 // Return empty package name and the further interaction
2589 // with camera will likely fail
2590 return packageName;
2591 }
2592
2593 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002594 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002595
2596 return packageName;
2597}
2598
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002599template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002600Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2601 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2602 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002603 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002604 int rotationOverride, bool forceSlowJpegMode,
2605 const std::string& originalCameraId, /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002606 binder::Status ret = binder::Status::ok();
2607
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002608 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002609 std::string clientPackageName;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002610 int packageUid = (clientUid == USE_CALLING_UID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002611 getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002612 if (clientPackageNameMaybe.size() <= 0) {
2613 // NDK calls don't come with package names, but we need one for various cases.
2614 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2615 // do exist. For all authentication cases, all packages under the same UID get the
2616 // same permissions, so picking any associated package name is sufficient. For some
2617 // other cases, this may give inaccurate names for clients in logs.
2618 isNonSystemNdk = true;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002619 clientPackageName = getPackageNameFromUid(packageUid);
2620 } else {
2621 clientPackageName = clientPackageNameMaybe;
2622 }
2623
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002624 int originalClientPid = 0;
2625
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002626 int packagePid = (clientPid == USE_CALLING_PID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002627 getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002628 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002629 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002630 static_cast<int>(effectiveApiLevel));
2631
Shuzhen Wang316781a2020-08-18 18:11:01 -07002632 nsecs_t openTimeNs = systemTime();
2633
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002634 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002635 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002636 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002637
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002638 {
2639 // Acquire mServiceLock and prevent other clients from connecting
2640 std::unique_ptr<AutoConditionLock> lock =
2641 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2642
2643 if (lock == nullptr) {
2644 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2645 , clientPid);
2646 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2647 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002648 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002649 }
2650
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002651 // Enforce client permissions and do basic validity checks
Biswarup Pal37a75182024-01-16 15:53:35 +00002652 if (!(ret = validateConnectLocked(cameraId, clientPackageName,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002653 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2654 return ret;
2655 }
2656
2657 // Check the shim parameters after acquiring lock, if they have already been updated and
2658 // we were doing a shim update, return immediately
2659 if (shimUpdateOnly) {
2660 auto cameraState = getCameraState(cameraId);
2661 if (cameraState != nullptr) {
2662 if (!cameraState->getShimParams().isEmpty()) return ret;
2663 }
2664 }
2665
2666 status_t err;
2667
2668 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002669 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002670 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002671 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2672 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002673 switch (err) {
2674 case -ENODEV:
2675 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2676 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002677 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002678 case -EBUSY:
2679 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2680 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002681 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002682 case -EUSERS:
2683 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2684 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002685 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002686 default:
2687 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2688 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002689 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002690 }
2691 }
2692
2693 if (clientTmp.get() != nullptr) {
2694 // Handle special case for API1 MediaRecorder where the existing client is returned
2695 device = static_cast<CLIENT*>(clientTmp.get());
2696 return ret;
2697 }
2698
2699 // give flashlight a chance to close devices if necessary.
2700 mFlashlight->prepareDeviceOpen(cameraId);
2701
Austin Borger18b30a72022-10-27 12:20:29 -07002702 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002703 auto deviceVersionAndTransport =
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002704 getDeviceVersion(cameraId, rotationOverride, /*out*/&portraitRotation,
Austin Borger18b30a72022-10-27 12:20:29 -07002705 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002706 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002707 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002708 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002709 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002710 }
2711
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002712 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002713 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002714 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002715
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002716 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002717 clientFeatureId, cameraId, api1CameraId, facing,
2718 orientation, clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002719 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002720 rotationOverride, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002721 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002722 return ret;
2723 }
2724 client = static_cast<CLIENT*>(tmp.get());
2725
2726 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2727 __FUNCTION__);
2728
Austin Borgered99f642023-06-01 16:51:35 -07002729 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002730 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002731 if (err != OK) {
2732 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002733 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002734 mServiceLock.unlock();
2735 client->disconnect();
2736 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002737 switch(err) {
2738 case BAD_VALUE:
2739 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002740 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002741 case -EBUSY:
2742 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002743 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002744 case -EUSERS:
2745 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2746 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002747 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002748 case PERMISSION_DENIED:
2749 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002750 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002751 case -EACCES:
2752 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002753 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002754 case -ENODEV:
2755 default:
2756 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002757 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002758 strerror(-err), err);
2759 }
2760 }
2761
2762 // Update shim paremeters for legacy clients
2763 if (effectiveApiLevel == API_1) {
2764 // Assume we have always received a Client subclass for API1
2765 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2766 String8 rawParams = shimClient->getParameters();
2767 CameraParameters params(rawParams);
2768
2769 auto cameraState = getCameraState(cameraId);
2770 if (cameraState != nullptr) {
2771 cameraState->setShimParams(params);
2772 } else {
2773 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002774 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002775 }
2776 }
2777
Ravneetaeb20dc2022-03-30 05:33:03 +00002778 // Enable/disable camera service watchdog
2779 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2780
Emilian Peev6d45db82024-01-18 20:11:54 +00002781 CameraMetadata chars;
2782 bool rotateAndCropSupported = true;
2783 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002784 &chars, rotationOverride);
Emilian Peev6d45db82024-01-18 20:11:54 +00002785 if (err == OK) {
2786 auto availableRotateCropEntry = chars.find(
2787 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2788 if (availableRotateCropEntry.count <= 1) {
2789 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002790 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002791 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002792 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2793 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002794 }
2795
Emilian Peev6d45db82024-01-18 20:11:54 +00002796 if (rotateAndCropSupported) {
2797 // Set rotate-and-crop override behavior
2798 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2799 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002800 } else if (rotationOverride != hardware::ICameraService::ROTATION_OVERRIDE_NONE &&
2801 portraitRotation != 0) {
Emilian Peev6d45db82024-01-18 20:11:54 +00002802 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2803 switch (portraitRotation) {
2804 case 90:
2805 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2806 break;
2807 case 180:
2808 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2809 break;
2810 case 270:
2811 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2812 break;
2813 default:
2814 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2815 break;
2816 }
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002817 // Here we're communicating to the client the chosen rotate
2818 // and crop mode to send to the HAL
Emilian Peev6d45db82024-01-18 20:11:54 +00002819 client->setRotateAndCropOverride(rotateAndCropMode);
2820 } else {
2821 client->setRotateAndCropOverride(
2822 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2823 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2824 }
2825 }
2826
2827 bool autoframingSupported = true;
2828 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2829 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2830 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2831 autoframingSupported = false;
2832 }
2833
2834 if (autoframingSupported) {
2835 // Set autoframing override behaviour
2836 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2837 client->setAutoframingOverride(mOverrideAutoframingMode);
2838 } else {
2839 client->setAutoframingOverride(
2840 mCameraServiceProxyWrapper->getAutoframingOverride(
2841 clientPackageName));
2842 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002843 }
2844
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002845 bool isCameraPrivacyEnabled;
2846 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002847 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002848 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2849 toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2850 } else {
2851 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002852 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002853 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002854
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002855 if (client->supportsCameraMute()) {
2856 client->setCameraMute(
2857 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2858 } else if (isCameraPrivacyEnabled) {
2859 // no camera mute supported, but privacy is on! => disconnect
2860 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2861 client->getPackageName().c_str(), cameraId.c_str());
2862 // Do not hold mServiceLock while disconnecting clients, but
2863 // retain the condition blocking other clients from connecting
2864 // in mServiceLockWrapper if held.
2865 mServiceLock.unlock();
2866 // Clear caller identity temporarily so client disconnect PID
2867 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002868 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002869 // Note AppOp to trigger the "Unblock" dialog
2870 client->noteAppOp();
2871 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002872 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002873 // Reacquire mServiceLock
2874 mServiceLock.lock();
2875
2876 return STATUS_ERROR_FMT(ERROR_DISABLED,
2877 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002878 }
2879
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002880 if (shimUpdateOnly) {
2881 // If only updating legacy shim parameters, immediately disconnect client
2882 mServiceLock.unlock();
2883 client->disconnect();
2884 mServiceLock.lock();
2885 } else {
2886 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002887 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002888 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002889
2890 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002891 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002892 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002893 } // lock is destroyed, allow further connect calls
2894
2895 // Important: release the mutex here so the client can call back into the service from its
2896 // destructor (can be at the end of the call)
2897 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002898
2899 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002900 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002901 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002902
Cliff Wud3a05312021-04-26 23:07:31 +08002903 {
2904 Mutex::Autolock lock(mInjectionParametersLock);
2905 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2906 mInjectionInitPending = false;
2907 status_t res = NO_ERROR;
2908 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2909 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002910 sp<BasicClient> clientSp = clientDescriptor->getValue();
2911 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2912 if(res != OK) {
2913 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2914 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002915 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002916 }
2917 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002918 if (res != OK) {
2919 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2920 }
2921 } else {
2922 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002923 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002924 res = NO_INIT;
2925 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2926 }
2927 }
2928 }
2929
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002930 return ret;
2931}
2932
Austin Borgered99f642023-06-01 16:51:35 -07002933status_t CameraService::addOfflineClient(const std::string &cameraId,
2934 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002935 if (offlineClient.get() == nullptr) {
2936 return BAD_VALUE;
2937 }
2938
2939 {
2940 // Acquire mServiceLock and prevent other clients from connecting
2941 std::unique_ptr<AutoConditionLock> lock =
2942 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2943
2944 if (lock == nullptr) {
2945 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2946 , __FUNCTION__, offlineClient->getClientPid());
2947 return TIMED_OUT;
2948 }
2949
2950 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2951 if (onlineClientDesc.get() == nullptr) {
2952 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2953 cameraId.c_str());
2954 return BAD_VALUE;
2955 }
2956
2957 // Offline clients do not evict or conflict with other online devices. Resource sharing
2958 // conflicts are handled by the camera provider which will either succeed or fail before
2959 // reaching this method.
2960 const auto& onlinePriority = onlineClientDesc->getPriority();
2961 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2962 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002963 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002964 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002965 // native clients don't have offline processing support.
2966 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002967 if (offlineClientDesc == nullptr) {
2968 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2969 return BAD_VALUE;
2970 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002971
2972 // Allow only one offline device per camera
2973 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2974 if (!incompatibleClients.empty()) {
2975 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2976 return BAD_VALUE;
2977 }
2978
Austin Borgered99f642023-06-01 16:51:35 -07002979 std::string monitorTags = isClientWatched(offlineClient.get())
2980 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002981 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002982 if (err != OK) {
2983 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2984 return err;
2985 }
2986
2987 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2988 if (evicted.size() > 0) {
2989 for (auto& i : evicted) {
2990 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002991 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002992 }
2993
2994 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2995 "properly", __FUNCTION__);
2996
2997 return BAD_VALUE;
2998 }
2999
3000 logConnectedOffline(offlineClientDesc->getKey(),
3001 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07003002 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003003
3004 sp<IBinder> remoteCallback = offlineClient->getRemote();
3005 if (remoteCallback != nullptr) {
3006 remoteCallback->linkToDeath(this);
3007 }
3008 } // lock is destroyed, allow further connect calls
3009
3010 return OK;
3011}
3012
Austin Borgered99f642023-06-01 16:51:35 -07003013Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +00003014 int32_t torchStrength, const sp<IBinder>& clientBinder, int32_t deviceId,
3015 int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08003016 Mutex::Autolock lock(mServiceLock);
3017
3018 ATRACE_CALL();
3019 if (clientBinder == nullptr) {
3020 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
3021 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
3022 "Torch client binder in null.");
3023 }
3024
Austin Borger22c5c852024-03-08 13:31:36 -08003025 int uid = getCallingUid();
Biswarup Pal37a75182024-01-16 15:53:35 +00003026 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
3027 devicePolicy, uid);
3028 if (!cameraIdOptional.has_value()) {
3029 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
3030 unresolvedCameraId.c_str(), deviceId);
3031 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3032 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3033 }
3034 std::string cameraId = cameraIdOptional.value();
3035
Austin Borgered99f642023-06-01 16:51:35 -07003036 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08003037 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07003038 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003039 }
3040
3041 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07003042 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08003043 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07003044 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003045 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003046 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003047 }
3048
3049 StatusInternal cameraStatus = state->getStatus();
3050 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
3051 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07003052 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08003053 (int)cameraStatus);
3054 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003055 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003056 }
3057
3058 {
3059 Mutex::Autolock al(mTorchStatusMutex);
3060 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003061 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08003062 if (err != OK) {
3063 if (err == NAME_NOT_FOUND) {
3064 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003065 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003066 }
3067 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003068 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003069 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
3070 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003071 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08003072 }
3073
3074 if (status == TorchModeStatus::NOT_AVAILABLE) {
3075 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
3076 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003077 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003078 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3079 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003080 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003081 } else {
3082 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003083 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003084 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3085 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003086 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003087 }
3088 }
3089 }
3090
3091 {
3092 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003093 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08003094 }
3095 // Check if the current torch strength level is same as the new one.
3096 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07003097 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003098
Austin Borgered99f642023-06-01 16:51:35 -07003099 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003100
3101 if (err != OK) {
3102 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003103 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08003104 switch (err) {
3105 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003106 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
3107 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003108 errorCode = ERROR_ILLEGAL_ARGUMENT;
3109 break;
3110 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003111 msg = fmt::sprintf("Camera \"%s\" is in use",
3112 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003113 errorCode = ERROR_CAMERA_IN_USE;
3114 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08003115 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07003116 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08003117 "valid range.", torchStrength);
3118 errorCode = ERROR_ILLEGAL_ARGUMENT;
3119 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08003120 default:
Austin Borgered99f642023-06-01 16:51:35 -07003121 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08003122 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08003123 }
Austin Borgered99f642023-06-01 16:51:35 -07003124 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3125 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003126 }
3127
3128 {
3129 // update the link to client's death
3130 // Store the last client that turns on each camera's torch mode.
3131 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003132 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08003133 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003134 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08003135 } else {
3136 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
3137 mTorchClientMap.replaceValueAt(index, clientBinder);
3138 }
3139 clientBinder->linkToDeath(this);
3140 }
3141
Austin Borger22c5c852024-03-08 13:31:36 -08003142 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08003143 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07003144 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08003145 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07003146 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003147 }
3148 return Status::ok();
3149}
3150
malikakash73125c62023-07-21 22:44:34 +00003151Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Biswarup Pal37a75182024-01-16 15:53:35 +00003152 const sp<IBinder>& clientBinder, int32_t deviceId, int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003153 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003154
3155 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07003156 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003157 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003158 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
3159 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003160 }
3161
Austin Borger22c5c852024-03-08 13:31:36 -08003162 int uid = getCallingUid();
Biswarup Pal37a75182024-01-16 15:53:35 +00003163 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
3164 devicePolicy, uid);
3165 if (!cameraIdOptional.has_value()) {
3166 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
3167 unresolvedCameraId.c_str(), deviceId);
3168 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3169 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3170 }
3171 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003172
Austin Borgered99f642023-06-01 16:51:35 -07003173 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003174 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07003175 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003176 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003177 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07003178 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003179 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07003180 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003181 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003182 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003183 }
3184
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003185 StatusInternal cameraStatus = state->getStatus();
3186 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003187 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07003188 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
3189 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003190 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003191 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003192 }
3193
3194 {
3195 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003196 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003197 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003198 if (err != OK) {
3199 if (err == NAME_NOT_FOUND) {
3200 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003201 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003202 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003203 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003204 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003205 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07003206 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003207 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003208 }
3209
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003210 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003211 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003212 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003213 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003214 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3215 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003216 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003217 } else {
3218 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003219 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003220 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3221 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003222 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003223 }
3224 }
3225 }
3226
Ruben Brunk99e69712015-05-26 17:25:07 -07003227 {
3228 // Update UID map - this is used in the torch status changed callbacks, so must be done
3229 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003230 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003231 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003232 }
3233
Austin Borgered99f642023-06-01 16:51:35 -07003234 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003235
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003236 if (err != OK) {
3237 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003238 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003239 switch (err) {
3240 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003241 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3242 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003243 errorCode = ERROR_ILLEGAL_ARGUMENT;
3244 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003245 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003246 msg = fmt::sprintf("Camera \"%s\" is in use",
3247 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003248 errorCode = ERROR_CAMERA_IN_USE;
3249 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003250 default:
Austin Borgered99f642023-06-01 16:51:35 -07003251 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003252 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003253 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003254 errorCode = ERROR_INVALID_OPERATION;
3255 }
Austin Borgered99f642023-06-01 16:51:35 -07003256 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3257 logServiceError(msg, errorCode);
3258 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003259 }
3260
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003261 {
3262 // update the link to client's death
3263 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003264 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003265 if (enabled) {
3266 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003267 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003268 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003269 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003270 mTorchClientMap.replaceValueAt(index, clientBinder);
3271 }
3272 clientBinder->linkToDeath(this);
3273 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003274 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003275 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003276 }
3277
Austin Borger22c5c852024-03-08 13:31:36 -08003278 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003279 std::string torchState = enabled ? "on" : "off";
3280 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3281 torchState.c_str(), clientPid);
3282 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003283 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003284}
3285
Austin Borgered99f642023-06-01 16:51:35 -07003286void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3287 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3288 mTorchUidMap[cameraId].first = uid;
3289 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003290 } else {
3291 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003292 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003293 }
3294}
3295
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003296Status CameraService::notifySystemEvent(int32_t eventId,
3297 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003298 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003299 const int selfPid = getpid();
3300
3301 // Permission checks
3302 if (pid != selfPid) {
3303 // Ensure we're being called by system_server, or similar process with
3304 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003305 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003306 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003307 ALOGE("Permission Denial: cannot send updates to camera service about system"
3308 " events from pid=%d, uid=%d", pid, uid);
3309 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003310 "No permission to send updates to camera service about system events"
3311 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003312 }
3313 }
3314
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003315 ATRACE_CALL();
3316
Ruben Brunk36597b22015-03-20 22:15:57 -07003317 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003318 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003319 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003320 // from a system server crash
3321 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003322 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003323 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003324 break;
3325 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003326 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3327 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003328 if (args.size() != 1) {
3329 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3330 "USB Device Event requires 1 argument");
3331 }
3332
Valentin Iftime29e2e152021-08-13 15:17:33 +02003333 // Notify CameraProviderManager for lazy HALs
3334 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3335 std::to_string(args[0]));
3336 break;
3337 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003338 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003339 default: {
3340 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3341 eventId);
3342 break;
3343 }
3344 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003345 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003346}
3347
Emilian Peev53722fa2019-02-22 17:47:20 -08003348void CameraService::notifyMonitoredUids() {
3349 Mutex::Autolock lock(mStatusListenerLock);
3350
3351 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003352 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003353 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3354 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003355 }
3356}
3357
Austin Borgerdddb7552023-03-30 17:53:01 -07003358void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3359 Mutex::Autolock lock(mStatusListenerLock);
3360
3361 for (const auto& it : mListenerList) {
3362 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3363 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3364 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3365 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3366 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3367 }
3368 }
3369}
3370
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003371Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003372 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003373 const int selfPid = getpid();
3374
3375 // Permission checks
3376 if (pid != selfPid) {
3377 // Ensure we're being called by system_server, or similar process with
3378 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003379 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003380 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003381 ALOGE("Permission Denial: cannot send updates to camera service about device"
3382 " state changes from pid=%d, uid=%d", pid, uid);
3383 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3384 "No permission to send updates to camera service about device state"
3385 " changes from pid=%d, uid=%d", pid, uid);
3386 }
3387 }
3388
3389 ATRACE_CALL();
3390
Austin Borger18b30a72022-10-27 12:20:29 -07003391 {
3392 Mutex::Autolock lock(mServiceLock);
3393 mDeviceState = newState;
3394 }
3395
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003396 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003397
3398 return Status::ok();
3399}
3400
Emilian Peev8b64f282021-03-25 16:49:57 -07003401Status CameraService::notifyDisplayConfigurationChange() {
3402 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003403 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003404 const int selfPid = getpid();
3405
3406 // Permission checks
3407 if (callingPid != selfPid) {
3408 // Ensure we're being called by system_server, or similar process with
3409 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003410 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003411 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003412 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3413 " changes from pid=%d, uid=%d", callingPid, uid);
3414 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3415 "No permission to send updates to camera service about orientation"
3416 " changes from pid=%d, uid=%d", callingPid, uid);
3417 }
3418 }
3419
3420 Mutex::Autolock lock(mServiceLock);
3421
3422 // Don't do anything if rotate-and-crop override via cmd is active
3423 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3424
3425 const auto clients = mActiveClientManager.getAll();
3426 for (auto& current : clients) {
3427 if (current != nullptr) {
3428 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003429 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3430 basicClient->setRotateAndCropOverride(
3431 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3432 basicClient->getPackageName(),
3433 basicClient->getCameraFacing(),
3434 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003435 }
3436 }
3437 }
3438
3439 return Status::ok();
3440}
3441
Biswarup Pal37a75182024-01-16 15:53:35 +00003442// TODO(b/291736219): This to be made device-aware.
Emilian Peev8b64f282021-03-25 16:49:57 -07003443Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003444 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3445 ATRACE_CALL();
3446 if (!concurrentCameraIds) {
3447 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3448 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3449 }
3450
3451 if (!mInitialized) {
3452 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003453 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003454 return STATUS_ERROR(ERROR_DISCONNECTED,
3455 "Camera subsystem is not available");
3456 }
3457 // First call into the provider and get the set of concurrent camera
3458 // combinations
3459 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003460 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003461 for (auto &combination : concurrentCameraCombinations) {
3462 std::vector<std::string> validCombination;
3463 for (auto &cameraId : combination) {
3464 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003465 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003466 if (state == nullptr) {
3467 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3468 continue;
3469 }
3470 StatusInternal status = state->getStatus();
3471 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3472 continue;
3473 }
Austin Borgered99f642023-06-01 16:51:35 -07003474 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003475 continue;
3476 }
3477 validCombination.push_back(cameraId);
3478 }
3479 if (validCombination.size() != 0) {
3480 concurrentCameraIds->push_back(std::move(validCombination));
3481 }
3482 }
3483 return Status::ok();
3484}
3485
3486Status CameraService::isConcurrentSessionConfigurationSupported(
3487 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003488 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003489 if (!isSupported) {
3490 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3491 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3492 }
3493
3494 if (!mInitialized) {
3495 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3496 return STATUS_ERROR(ERROR_DISCONNECTED,
3497 "Camera subsystem is not available");
3498 }
3499
3500 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003501 int callingPid = getCallingPid();
3502 int callingUid = getCallingUid();
Biswarup Pale506e732024-03-27 13:46:20 +00003503 // TODO(b/291736219): Pass deviceId owning the camera if we make this method device-aware.
Austin Borger249e6592024-03-10 22:28:11 -07003504 bool hasCameraPermission = ((callingPid == getpid()) ||
Biswarup Pale506e732024-03-27 13:46:20 +00003505 hasPermissionsForCamera(callingPid, callingUid, kDefaultDeviceId));
Austin Borger249e6592024-03-10 22:28:11 -07003506 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003507 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3508 "android.permission.CAMERA needed to call"
3509 "isConcurrentSessionConfigurationSupported");
3510 }
3511
3512 status_t res =
3513 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003514 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3515 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003516 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003517 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003518 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003519 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3520 "support %s (%d)", strerror(-res), res);
3521 }
3522 return Status::ok();
3523}
3524
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003525Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3526 /*out*/
3527 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003528 return addListenerHelper(listener, cameraStatuses);
3529}
3530
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003531binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3532 std::vector<hardware::CameraStatus>* cameraStatuses) {
3533 return addListenerHelper(listener, cameraStatuses, false, true);
3534}
3535
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003536Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3537 /*out*/
3538 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003539 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003540 ATRACE_CALL();
3541
Igor Murashkinbfc99152013-02-27 12:55:20 -08003542 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003543
Ruben Brunk3450ba72015-06-16 11:00:37 -07003544 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003545 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003546 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003547 }
3548
Austin Borger22c5c852024-03-08 13:31:36 -08003549 auto clientPid = getCallingPid();
3550 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003551 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003552
Igor Murashkinbfc99152013-02-27 12:55:20 -08003553 Mutex::Autolock lock(mServiceLock);
3554
Ruben Brunkcc776712015-02-17 20:18:47 -08003555 {
3556 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003557 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003558 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003559 ALOGW("%s: Tried to add listener %p which was already subscribed",
3560 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003561 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003562 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003563 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003564
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003565 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003566 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3567 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003568 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003569 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003570 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003571 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003572 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3573 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3574 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003575 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003576 // The listener still needs to be added to the list of listeners, regardless of what
3577 // permissions the listener process has / whether it is a vendor listener. Since it might be
3578 // eligible to listen to other camera ids.
3579 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003580 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003581 }
3582
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003583 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003584 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003585 Mutex::Autolock lock(mCameraStatesLock);
3586 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003587 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3588 auto [deviceId, mappedCameraId] =
3589 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3590
3591 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003592 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003593 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3594 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003595 }
3596 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003597 // Remove the camera statuses that should be hidden from the client, we do
3598 // this after collecting the states in order to avoid holding
3599 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3600 // the same time.
3601 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3602 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003603 std::string cameraId = s.cameraId;
3604 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
3605 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM,
3606 clientUid);
3607 if (!cameraIdOptional.has_value()) {
3608 std::string msg =
3609 fmt::sprintf(
3610 "Camera %s: Invalid camera id for device id %d",
3611 s.cameraId.c_str(), s.deviceId);
3612 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3613 return true;
3614 }
3615 cameraId = cameraIdOptional.value();
3616 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3617 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3618 ALOGE("%s: Invalid camera id %s, skipping status update",
3619 __FUNCTION__, s.cameraId.c_str());
3620 return true;
3621 }
3622 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3623 clientUid);
3624 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003625
Biswarup Pal37a75182024-01-16 15:53:35 +00003626 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003627 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003628 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003629 // Add only default device cameras here, as virtual cameras currently don't support torch
3630 // anyway. Note that this is a simplification of the implementation here, and we should
3631 // change this when virtual cameras support torch.
3632 if (s.deviceId == kDefaultDeviceId) {
3633 idsChosenForCallback.insert(s.cameraId);
3634 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003635 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003636
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003637 /*
3638 * Immediately signal current torch status to this listener only
3639 * This may be a subset of all the devices, so don't include it in the response directly
3640 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003641 {
3642 Mutex::Autolock al(mTorchStatusMutex);
3643 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003644 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003645 // The camera id is visible to the client. Fine to send torch
3646 // callback.
3647 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003648 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3649 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003650 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003651 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003652 }
3653
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003654 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003655}
Ruben Brunkcc776712015-02-17 20:18:47 -08003656
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003657Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003658 ATRACE_CALL();
3659
Igor Murashkinbfc99152013-02-27 12:55:20 -08003660 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3661
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003662 if (listener == 0) {
3663 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003664 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003665 }
3666
Igor Murashkinbfc99152013-02-27 12:55:20 -08003667 Mutex::Autolock lock(mServiceLock);
3668
Ruben Brunkcc776712015-02-17 20:18:47 -08003669 {
3670 Mutex::Autolock lock(mStatusListenerLock);
3671 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003672 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003673 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003674 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003675 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003676 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003677 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003678 }
3679 }
3680
3681 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3682 __FUNCTION__, listener.get());
3683
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003684 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003685}
3686
Austin Borgered99f642023-06-01 16:51:35 -07003687Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003688
3689 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003690 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3691
3692 if (parameters == NULL) {
3693 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003694 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003695 }
3696
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003697 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003698
3699 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003700 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003701 // Error logged by caller
3702 return ret;
3703 }
3704
3705 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003706
Austin Borgered99f642023-06-01 16:51:35 -07003707 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003708
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003709 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003710}
3711
Austin Borgered99f642023-06-01 16:51:35 -07003712Status CameraService::supportsCameraApi(const std::string& unresolvedCameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003713 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003714 ATRACE_CALL();
3715
malikakashedb38962023-09-06 00:03:35 +00003716 const std::string cameraId = resolveCameraId(
Austin Borger22c5c852024-03-08 13:31:36 -08003717 unresolvedCameraId, getCallingUid());
malikakash82ed4352023-07-21 22:44:34 +00003718
Austin Borgered99f642023-06-01 16:51:35 -07003719 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003720
3721 switch (apiVersion) {
3722 case API_VERSION_1:
3723 case API_VERSION_2:
3724 break;
3725 default:
Austin Borgered99f642023-06-01 16:51:35 -07003726 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3727 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3728 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003729 }
3730
Austin Borger18b30a72022-10-27 12:20:29 -07003731 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00003732 auto deviceVersionAndTransport =
3733 getDeviceVersion(cameraId,
3734 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
3735 &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003736 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003737 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3738 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3739 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003740 }
3741 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3742 int deviceVersion = deviceVersionAndTransport.first;
3743 switch (deviceVersion) {
3744 case CAMERA_DEVICE_API_VERSION_1_0:
3745 case CAMERA_DEVICE_API_VERSION_3_0:
3746 case CAMERA_DEVICE_API_VERSION_3_1:
3747 if (apiVersion == API_VERSION_2) {
3748 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003749 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003750 *isSupported = false;
3751 } else { // if (apiVersion == API_VERSION_1) {
3752 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003753 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003754 *isSupported = true;
3755 }
3756 break;
3757 case CAMERA_DEVICE_API_VERSION_3_2:
3758 case CAMERA_DEVICE_API_VERSION_3_3:
3759 case CAMERA_DEVICE_API_VERSION_3_4:
3760 case CAMERA_DEVICE_API_VERSION_3_5:
3761 case CAMERA_DEVICE_API_VERSION_3_6:
3762 case CAMERA_DEVICE_API_VERSION_3_7:
3763 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003764 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003765 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003766 break;
3767 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003768 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3769 deviceVersion, cameraId.c_str());
3770 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3771 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003772 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003773 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003774 } else {
3775 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003776 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003777 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003778}
3779
Austin Borgered99f642023-06-01 16:51:35 -07003780Status CameraService::isHiddenPhysicalCamera(const std::string& unresolvedCameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003781 /*out*/ bool *isSupported) {
3782 ATRACE_CALL();
3783
malikakashedb38962023-09-06 00:03:35 +00003784 const std::string cameraId = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08003785 getCallingUid());
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003786
Austin Borgered99f642023-06-01 16:51:35 -07003787 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3788 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003789
3790 return Status::ok();
3791}
3792
Cliff Wud8cae102021-03-11 01:37:42 +08003793Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003794 const std::string& packageName, const std::string& internalCamId,
3795 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003796 const sp<ICameraInjectionCallback>& callback,
3797 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003798 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003799 ATRACE_CALL();
3800
Austin Borgered99f642023-06-01 16:51:35 -07003801 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003802 const int pid = getCallingPid();
3803 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003804 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3805 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003806 "Permission Denial: no permission to inject camera");
3807 }
3808
3809 // Do not allow any camera injection that injects or replaces a virtual camera.
3810 auto [deviceIdForInternalCamera, _] =
3811 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3812 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3813 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3814 "Cannot replace a virtual camera");
3815 }
3816 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3817 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3818 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3819 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3820 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003821 }
3822
3823 ALOGV(
3824 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3825 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003826 __FUNCTION__, packageName.c_str(),
3827 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003828
Cliff Wud3a05312021-04-26 23:07:31 +08003829 {
3830 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003831 mInjectionInternalCamId = internalCamId;
3832 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003833 mInjectionStatusListener->addListener(callback);
3834 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003835 status_t res = NO_ERROR;
3836 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3837 // If the client already exists, we can directly connect to the camera device through the
3838 // client's injectCamera(), otherwise we need to wait until the client is established
3839 // (execute connectHelper()) before injecting the camera to the camera device.
3840 if (clientDescriptor != nullptr) {
3841 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003842 sp<BasicClient> clientSp = clientDescriptor->getValue();
3843 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3844 if(res != OK) {
3845 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3846 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003847 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003848 }
3849 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003850 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003851 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3852 }
3853 } else {
3854 mInjectionInitPending = true;
3855 }
3856 }
Cliff Wud8cae102021-03-11 01:37:42 +08003857
Cliff Wud3a05312021-04-26 23:07:31 +08003858 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003859}
3860
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003861Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003862 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003863 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3864 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3865 return Status::ok();
3866}
3867
Ruben Brunkcc776712015-02-17 20:18:47 -08003868void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003869 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003870 for (auto& i : mActiveClientManager.getAll()) {
3871 auto clientSp = i->getValue();
3872 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003873 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003874 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003875 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003876 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003877 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003878}
3879
Ruben Brunkcc776712015-02-17 20:18:47 -08003880bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003881 bool ret = false;
3882 {
3883 // Acquire mServiceLock and prevent other clients from connecting
3884 std::unique_ptr<AutoConditionLock> lock =
3885 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003886
Ruben Brunkcc776712015-02-17 20:18:47 -08003887 std::vector<sp<BasicClient>> evicted;
3888 for (auto& i : mActiveClientManager.getAll()) {
3889 auto clientSp = i->getValue();
3890 if (clientSp.get() == nullptr) {
3891 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3892 mActiveClientManager.remove(i);
3893 continue;
3894 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003895 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003896 mActiveClientManager.remove(i);
3897 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003898
Ruben Brunkcc776712015-02-17 20:18:47 -08003899 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003900 clientSp->notifyError(
3901 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003902 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003903 }
3904 }
3905
Ruben Brunkcc776712015-02-17 20:18:47 -08003906 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3907 // other clients from connecting in mServiceLockWrapper if held
3908 mServiceLock.unlock();
3909
Ruben Brunk36597b22015-03-20 22:15:57 -07003910 // Do not clear caller identity, remote caller should be client proccess
3911
Ruben Brunkcc776712015-02-17 20:18:47 -08003912 for (auto& i : evicted) {
3913 if (i.get() != nullptr) {
3914 i->disconnect();
3915 ret = true;
3916 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003917 }
3918
Ruben Brunkcc776712015-02-17 20:18:47 -08003919 // Reacquire mServiceLock
3920 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003921
Ruben Brunkcc776712015-02-17 20:18:47 -08003922 } // lock is destroyed, allow further connect calls
3923
3924 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003925}
3926
Ruben Brunkcc776712015-02-17 20:18:47 -08003927std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003928 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003929 std::shared_ptr<CameraState> state;
3930 {
3931 Mutex::Autolock lock(mCameraStatesLock);
3932 auto iter = mCameraStates.find(cameraId);
3933 if (iter != mCameraStates.end()) {
3934 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003935 }
3936 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003937 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003938}
3939
Austin Borgered99f642023-06-01 16:51:35 -07003940sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003941 // Remove from active clients list
3942 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3943 if (clientDescriptorPtr == nullptr) {
3944 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003945 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003946 return sp<BasicClient>{nullptr};
3947 }
3948
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003949 sp<BasicClient> client = clientDescriptorPtr->getValue();
3950 if (client.get() != nullptr) {
3951 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3952 }
3953 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003954}
3955
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003956void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003957 // Acquire mServiceLock and prevent other clients from connecting
3958 std::unique_ptr<AutoConditionLock> lock =
3959 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3960
Ruben Brunk6267b532015-04-30 17:44:07 -07003961 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003962 for (size_t i = 0; i < newUserIds.size(); i++) {
3963 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003964 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003965 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003966 return;
3967 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003968 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003969 }
3970
Ruben Brunka8ca9152015-04-07 14:23:40 -07003971
Ruben Brunk6267b532015-04-30 17:44:07 -07003972 if (newAllowedUsers == mAllowedUsers) {
3973 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3974 return;
3975 }
3976
3977 logUserSwitch(mAllowedUsers, newAllowedUsers);
3978
3979 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003980
3981 // Current user has switched, evict all current clients.
3982 std::vector<sp<BasicClient>> evicted;
3983 for (auto& i : mActiveClientManager.getAll()) {
3984 auto clientSp = i->getValue();
3985
3986 if (clientSp.get() == nullptr) {
3987 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3988 continue;
3989 }
3990
Ruben Brunk6267b532015-04-30 17:44:07 -07003991 // Don't evict clients that are still allowed.
3992 uid_t clientUid = clientSp->getClientUid();
3993 userid_t clientUserId = multiuser_get_user_id(clientUid);
3994 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3995 continue;
3996 }
3997
Ruben Brunk36597b22015-03-20 22:15:57 -07003998 evicted.push_back(clientSp);
3999
Ruben Brunk36597b22015-03-20 22:15:57 -07004000 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07004001 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07004002
Ruben Brunk36597b22015-03-20 22:15:57 -07004003 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004004 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00004005 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07004006 " to user switch.", i->getKey().c_str(),
4007 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00004008 i->getOwnerId(), i->getPriority().getScore(),
4009 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07004010
4011 }
4012
4013 // Do not hold mServiceLock while disconnecting clients, but retain the condition
4014 // blocking other clients from connecting in mServiceLockWrapper if held.
4015 mServiceLock.unlock();
4016
4017 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08004018 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07004019
4020 for (auto& i : evicted) {
4021 i->disconnect();
4022 }
4023
Austin Borger22c5c852024-03-08 13:31:36 -08004024 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07004025
4026 // Reacquire mServiceLock
4027 mServiceLock.lock();
4028}
Ruben Brunkcc776712015-02-17 20:18:47 -08004029
Austin Borgered99f642023-06-01 16:51:35 -07004030void CameraService::logEvent(const std::string &event) {
4031 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07004032 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07004033 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07004034 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07004035 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07004036 mEventLog.add(msg);
4037 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
4038 // Error event not added to the dumpsys log before
4039 mEventLog.add(msg);
4040 sServiceErrorEventSet.insert(msg);
4041 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004042}
4043
Austin Borgered99f642023-06-01 16:51:35 -07004044void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
4045 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004046 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004047 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
4048 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004049}
4050
Austin Borgered99f642023-06-01 16:51:35 -07004051void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
4052 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004053 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004054 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
4055 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004056}
4057
Austin Borgered99f642023-06-01 16:51:35 -07004058void CameraService::logConnected(const std::string &cameraId, int clientPid,
4059 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004060 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004061 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
4062 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004063}
4064
Austin Borgered99f642023-06-01 16:51:35 -07004065void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
4066 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004067 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004068 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
4069 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004070}
4071
Austin Borgered99f642023-06-01 16:51:35 -07004072void CameraService::logRejected(const std::string &cameraId, int clientPid,
4073 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004074 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07004075 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
4076 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004077}
4078
Austin Borgered99f642023-06-01 16:51:35 -07004079void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
4080 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07004081 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07004082 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
4083 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07004084}
4085
Ruben Brunk6267b532015-04-30 17:44:07 -07004086void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
4087 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07004088 std::string newUsers = toString(newUserIds);
4089 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004090 if (oldUsers.size() == 0) {
4091 oldUsers = "<None>";
4092 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07004093 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07004094 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
4095 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004096}
4097
Austin Borgered99f642023-06-01 16:51:35 -07004098void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004099 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004100 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004101}
4102
Austin Borgered99f642023-06-01 16:51:35 -07004103void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004104 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004105 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004106}
4107
Austin Borgered99f642023-06-01 16:51:35 -07004108void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004109 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004110 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07004111}
4112
Austin Borgered99f642023-06-01 16:51:35 -07004113void CameraService::logServiceError(const std::string &msg, int errorCode) {
4114 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
4115 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004116}
4117
Ruben Brunk36597b22015-03-20 22:15:57 -07004118status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4119 uint32_t flags) {
4120
Mathias Agopian65ab4712010-07-14 17:59:35 -07004121 // Permission checks
4122 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004123 case SHELL_COMMAND_TRANSACTION: {
4124 int in = data.readFileDescriptor();
4125 int out = data.readFileDescriptor();
4126 int err = data.readFileDescriptor();
4127 int argc = data.readInt32();
4128 Vector<String16> args;
4129 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
4130 args.add(data.readString16());
4131 }
4132 sp<IBinder> unusedCallback;
4133 sp<IResultReceiver> resultReceiver;
4134 status_t status;
4135 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
4136 return status;
4137 }
4138 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
4139 return status;
4140 }
4141 status = shellCommand(in, out, err, args);
4142 if (resultReceiver != nullptr) {
4143 resultReceiver->send(status);
4144 }
4145 return NO_ERROR;
4146 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004147 }
4148
4149 return BnCameraService::onTransact(code, data, reply, flags);
4150}
4151
Mathias Agopian65ab4712010-07-14 17:59:35 -07004152// We share the media players for shutter and recording sound for all clients.
4153// A reference count is kept to determine when we will actually release the
4154// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09004155sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
4156 sp<MediaPlayer> mp = new MediaPlayer();
4157 status_t error;
4158 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08004159 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09004160 error = mp->prepare();
4161 }
4162 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004163 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09004164 mp->disconnect();
4165 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004166 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004167 }
4168 return mp;
4169}
4170
username5755fea2018-12-27 09:48:08 +08004171void CameraService::increaseSoundRef() {
4172 Mutex::Autolock lock(mSoundLock);
4173 mSoundRef++;
4174}
4175
4176void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004177 ATRACE_CALL();
4178
username5755fea2018-12-27 09:48:08 +08004179 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
4180 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
4181 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
4182 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
4183 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4184 }
4185 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
4186 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4187 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4188 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004189 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08004190 }
4191 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4192 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4193 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4194 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4195 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004196 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004197}
4198
username5755fea2018-12-27 09:48:08 +08004199void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004200 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004201 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004202 if (--mSoundRef) return;
4203
4204 for (int i = 0; i < NUM_SOUNDS; i++) {
4205 if (mSoundPlayer[i] != 0) {
4206 mSoundPlayer[i]->disconnect();
4207 mSoundPlayer[i].clear();
4208 }
4209 }
4210}
4211
4212void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004213 ATRACE_CALL();
4214
Mathias Agopian65ab4712010-07-14 17:59:35 -07004215 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004216 if (kind < 0 || kind >= NUM_SOUNDS) {
4217 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4218 return;
4219 }
4220
Mathias Agopian65ab4712010-07-14 17:59:35 -07004221 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004222 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004223 sp<MediaPlayer> player = mSoundPlayer[kind];
4224 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004225 player->seekTo(0);
4226 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004227 }
4228}
4229
4230// ----------------------------------------------------------------------------
4231
4232CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004233 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004234 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004235 const std::string& clientPackageName, bool systemNativeClient,
4236 const std::optional<std::string>& clientFeatureId,
4237 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004238 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004239 int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004240 int servicePid, int rotationOverride) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004241 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004242 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07004243 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004244 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004245 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004246 clientPid, clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004247 servicePid, rotationOverride),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004248 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004249{
Austin Borger22c5c852024-03-08 13:31:36 -08004250 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004251 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004252
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004253 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004254
username5755fea2018-12-27 09:48:08 +08004255 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004256
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004257 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004258}
4259
Mathias Agopian65ab4712010-07-14 17:59:35 -07004260// tear down the client
4261CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004262 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004263 mDestructionStarted = true;
4264
username5755fea2018-12-27 09:48:08 +08004265 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004266 // unconditionally disconnect. function is idempotent
4267 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004268}
4269
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004270sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4271
Igor Murashkin634a5152013-02-20 17:15:11 -08004272CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004273 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004274 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004275 const std::string& clientPackageName, bool nativeClient,
4276 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004277 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004278 int servicePid, int rotationOverride):
Austin Borger249e6592024-03-10 22:28:11 -07004279 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004280 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004281 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004282 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4283 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004284 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004285 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004286 mDisconnected(false), mUidIsTrusted(false),
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004287 mRotationOverride(rotationOverride),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004288 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004289 mRemoteBinder(remoteCallback),
4290 mOpsActive(false),
4291 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004292{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004293 if (sCameraService == nullptr) {
4294 sCameraService = cameraService;
4295 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004296
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004297 // There are 2 scenarios in which a client won't have AppOps operations
4298 // (both scenarios : native clients)
4299 // 1) It's an system native client*, the package name will be empty
4300 // and it will return from this function in the previous if condition
4301 // (This is the same as the previously existing behavior).
4302 // 2) It is a system native client, but its package name has been
4303 // modified for debugging, however it still must not use AppOps since
4304 // the package name is not a real one.
4305 //
4306 // * system native client - native client with UID < AID_APP_START. It
4307 // doesn't exclude clients not on the system partition.
4308 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004309 mAppOpsManager = std::make_unique<AppOpsManager>();
4310 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004311
Charles Chenf075f082024-03-04 23:32:55 +00004312 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004313}
4314
4315CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004316 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004317 mDestructionStarted = true;
4318}
4319
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004320binder::Status CameraService::BasicClient::disconnect() {
4321 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004322 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004323 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004324 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004325 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004326
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004327 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004328 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004329 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004330 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004331
4332 sp<IBinder> remote = getRemote();
4333 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004334 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004335 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004336
4337 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004338 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004339 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004340 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004341 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004342
Igor Murashkincba2c162013-03-20 15:56:31 -07004343 // client shouldn't be able to call into us anymore
4344 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004345
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004346 const auto& mActivityManager = getActivityManager();
4347 if (mActivityManager) {
4348 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004349 getCallingUid(),
4350 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004351 }
4352
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004353 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004354}
4355
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004356status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4357 // No dumping of clients directly over Binder,
4358 // must go through CameraService::dump
4359 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004360 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004361 return OK;
4362}
4363
Austin Borgered99f642023-06-01 16:51:35 -07004364status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004365 // Can't watch tags directly, must go through CameraService::startWatchingTags
4366 return OK;
4367}
4368
4369status_t CameraService::BasicClient::stopWatchingTags(int) {
4370 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4371 return OK;
4372}
4373
4374status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4375 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4376 return OK;
4377}
4378
Austin Borgered99f642023-06-01 16:51:35 -07004379std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004380 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004381}
4382
Emilian Peev8b64f282021-03-25 16:49:57 -07004383int CameraService::BasicClient::getCameraFacing() const {
4384 return mCameraFacing;
4385}
4386
4387int CameraService::BasicClient::getCameraOrientation() const {
4388 return mOrientation;
4389}
Ruben Brunkcc776712015-02-17 20:18:47 -08004390
4391int CameraService::BasicClient::getClientPid() const {
4392 return mClientPid;
4393}
4394
Ruben Brunk6267b532015-04-30 17:44:07 -07004395uid_t CameraService::BasicClient::getClientUid() const {
4396 return mClientUid;
4397}
4398
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004399bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4400 // Defaults to API2.
4401 return level == API_2;
4402}
4403
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004404status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004405 {
4406 Mutex::Autolock l(mAudioRestrictionLock);
4407 mAudioRestriction = mode;
4408 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004409 sCameraService->updateAudioRestriction();
4410 return OK;
4411}
4412
4413int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004414 return sCameraService->updateAudioRestriction();
4415}
4416
4417int32_t CameraService::BasicClient::getAudioRestriction() const {
4418 Mutex::Autolock l(mAudioRestrictionLock);
4419 return mAudioRestriction;
4420}
4421
4422bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4423 switch (mode) {
4424 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4425 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4426 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4427 return true;
4428 default:
4429 return false;
4430 }
4431}
4432
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004433status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4434 if (mode == AppOpsManager::MODE_ERRORED) {
4435 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004436 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004437 return PERMISSION_DENIED;
4438 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4439 // If the calling Uid is trusted (a native service), the AppOpsManager could
4440 // return MODE_IGNORED. Do not treat such case as error.
4441 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4442 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004443
4444 bool isCameraPrivacyEnabled;
4445 if (flags::camera_privacy_allowlist()) {
4446 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4447 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4448 } else {
4449 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004450 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004451 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004452 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4453 // We prefer to successfully open the camera and perform camera muting
4454 // or blocking in connectHelper as handleAppOpMode can be called before the
4455 // connection has been fully established and at that time camera muting
4456 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004457 if (!isUidActive || !isCameraPrivacyEnabled) {
Austin Borgerfd05d982024-04-22 15:54:50 -07004458 ALOGI("Camera %s: Access for \"%s\" has been restricted."
4459 "uid active: %s, privacy enabled: %s", mCameraIdStr.c_str(),
4460 mClientPackageName.c_str(), isUidActive ? "true" : "false",
4461 isCameraPrivacyEnabled ? "true" : "false");
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004462 // Return the same error as for device policy manager rejection
4463 return -EACCES;
4464 }
4465 }
4466 return OK;
4467}
4468
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004469status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004470 ATRACE_CALL();
4471
Igor Murashkine6800ce2013-03-04 17:25:57 -08004472 {
4473 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004474 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004475 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004476 if (mAppOpsManager != nullptr) {
4477 // Notify app ops that the camera is not available
4478 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004479
4480 if (flags::watch_foreground_changes()) {
4481 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4482 toString16(mClientPackageName),
4483 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4484 } else {
4485 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004486 toString16(mClientPackageName), mOpsCallback);
Austin Borgerca1e0062023-06-28 11:32:55 -07004487 }
Igor Murashkine6800ce2013-03-04 17:25:57 -08004488
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004489 // Just check for camera acccess here on open - delay startOp until
4490 // camera frames start streaming in startCameraStreamingOps
4491 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004492 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004493 status_t res = handleAppOpMode(mode);
4494 if (res != OK) {
4495 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004496 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004497 }
4498
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004499 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004500
4501 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004502 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004503
Austin Borgerdddb7552023-03-30 17:53:01 -07004504 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004505
Shuzhen Wang695044d2020-03-06 09:02:23 -08004506 // Notify listeners of camera open/close status
4507 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4508
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004509 return OK;
4510}
4511
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004512status_t CameraService::BasicClient::startCameraStreamingOps() {
4513 ATRACE_CALL();
4514
4515 if (!mOpsActive) {
4516 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4517 return INVALID_OPERATION;
4518 }
4519 if (mOpsStreaming) {
4520 ALOGV("%s: Streaming already active!", __FUNCTION__);
4521 return OK;
4522 }
4523
4524 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004525 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004526
4527 if (mAppOpsManager != nullptr) {
4528 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004529 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4530 toString16(mClientFeatureId),
4531 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004532 status_t res = handleAppOpMode(mode);
4533 if (res != OK) {
4534 return res;
4535 }
4536 }
4537
4538 mOpsStreaming = true;
4539
4540 return OK;
4541}
4542
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004543status_t CameraService::BasicClient::noteAppOp() {
4544 ATRACE_CALL();
4545
4546 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004547 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004548
4549 // noteAppOp is only used for when camera mute is not supported, in order
4550 // to trigger the sensor privacy "Unblock" dialog
4551 if (mAppOpsManager != nullptr) {
4552 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004553 toString16(mClientPackageName), toString16(mClientFeatureId),
4554 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004555 status_t res = handleAppOpMode(mode);
4556 if (res != OK) {
4557 return res;
4558 }
4559 }
4560
4561 return OK;
4562}
4563
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004564status_t CameraService::BasicClient::finishCameraStreamingOps() {
4565 ATRACE_CALL();
4566
4567 if (!mOpsActive) {
4568 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4569 return INVALID_OPERATION;
4570 }
4571 if (!mOpsStreaming) {
4572 ALOGV("%s: Streaming not active!", __FUNCTION__);
4573 return OK;
4574 }
4575
4576 if (mAppOpsManager != nullptr) {
4577 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004578 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004579 mOpsStreaming = false;
4580 }
4581
4582 return OK;
4583}
4584
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004585status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004586 ATRACE_CALL();
4587
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004588 if (mOpsStreaming) {
4589 // Make sure we've notified everyone about camera stopping
4590 finishCameraStreamingOps();
4591 }
4592
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004593 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004594 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004595 mOpsActive = false;
4596
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004597 // This function is called when a client disconnects. This should
4598 // release the camera, but actually only if it was in a proper
4599 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004600 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004601 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004602
Ruben Brunkcc776712015-02-17 20:18:47 -08004603 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004604 sCameraService->updateStatus(StatusInternal::PRESENT,
4605 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004606 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004607 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004608 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4609 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004610 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004611 mOpsCallback.clear();
4612
Austin Borgerdddb7552023-03-30 17:53:01 -07004613 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004614
Shuzhen Wang695044d2020-03-06 09:02:23 -08004615 // Notify listeners of camera open/close status
4616 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4617
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004618 return OK;
4619}
4620
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004621void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004622 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004623 if (mAppOpsManager == nullptr) {
4624 return;
4625 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004626 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004627 if (op != AppOpsManager::OP_CAMERA) {
4628 ALOGW("Unexpected app ops notification received: %d", op);
4629 return;
4630 }
4631
4632 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004633 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004634 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004635 ALOGV("checkOp returns: %d, %s ", res,
4636 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4637 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4638 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4639 "UNKNOWN");
4640
Shuzhen Wang64900852021-02-05 09:03:29 -08004641 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004642 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4643 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004644 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004645 } else if (res == AppOpsManager::MODE_IGNORED) {
4646 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004647
Austin Borgerca1e0062023-06-28 11:32:55 -07004648 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4649 // If not visible, but still active, then we want to block instead of muting the camera.
4650 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4651 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4652
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004653 bool isCameraPrivacyEnabled;
4654 if (flags::camera_privacy_allowlist()) {
4655 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4656 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4657 } else {
4658 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004659 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004660 }
4661
4662 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004663 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4664 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4665 isCameraPrivacyEnabled);
4666 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4667 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4668 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004669 if (!mUidIsTrusted) {
Austin Borgerca1e0062023-06-28 11:32:55 -07004670 if (flags::watch_foreground_changes()) {
4671 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4672 setCameraMute(true);
4673 } else {
4674 block();
4675 }
4676 } else {
4677 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4678 setCameraMute(true);
4679 } else if (!isUidActive
4680 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4681 block();
4682 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004683 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004684 }
Evan Severson09ab4002021-02-10 14:15:19 -08004685 } else if (res == AppOpsManager::MODE_ALLOWED) {
4686 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004687 }
4688}
4689
Svet Ganova453d0d2018-01-11 15:37:58 -08004690void CameraService::BasicClient::block() {
4691 ATRACE_CALL();
4692
4693 // Reset the client PID to allow server-initiated disconnect,
4694 // and to prevent further calls by client.
Austin Borger22c5c852024-03-08 13:31:36 -08004695 mClientPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004696 CaptureResultExtras resultExtras; // a dummy result (invalid)
4697 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4698 disconnect();
4699}
4700
Mathias Agopian65ab4712010-07-14 17:59:35 -07004701// ----------------------------------------------------------------------------
4702
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004703void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004704 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004705 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004706 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4707 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4708 api1ErrorCode = CAMERA_ERROR_DISABLED;
4709 }
4710 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004711 } else {
4712 ALOGE("mRemoteCallback is NULL!!");
4713 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004714}
4715
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004716// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004717binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004718 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004719 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004720}
4721
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004722bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4723 return level == API_1;
4724}
4725
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004726CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4727 mClient(client) {
4728}
4729
4730void CameraService::Client::OpsCallback::opChanged(int32_t op,
4731 const String16& packageName) {
4732 sp<BasicClient> client = mClient.promote();
4733 if (client != NULL) {
4734 client->opChanged(op, packageName);
4735 }
4736}
4737
Mathias Agopian65ab4712010-07-14 17:59:35 -07004738// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004739// UidPolicy
4740// ----------------------------------------------------------------------------
4741
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004742void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004743 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004744 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004745
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004746 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004747 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004748 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004749 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004750 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4751 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004752 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004753 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004754 if (res == OK) {
4755 mRegistered = true;
4756 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004757 } else {
4758 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004759 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004760}
4761
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004762void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004763 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004764 return;
4765 }
4766
4767 registerWithActivityManager();
4768}
4769
4770void CameraService::UidPolicy::registerSelf() {
4771 // Use check service to see if the activity service is available
4772 // If not available then register for notifications, instead of blocking
4773 // till the service is ready
4774 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004775 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004776 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004777 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004778 } else {
4779 registerWithActivityManager();
4780 }
4781}
4782
Svet Ganova453d0d2018-01-11 15:37:58 -08004783void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004784 Mutex::Autolock _l(mUidLock);
4785
Steven Moreland2f348142019-07-02 15:59:07 -07004786 mAm.unregisterUidObserver(this);
4787 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004788 mRegistered = false;
4789 mActiveUids.clear();
4790 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004791}
4792
4793void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4794 onUidIdle(uid, disabled);
4795}
4796
4797void CameraService::UidPolicy::onUidActive(uid_t uid) {
4798 Mutex::Autolock _l(mUidLock);
4799 mActiveUids.insert(uid);
4800}
4801
4802void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4803 bool deleted = false;
4804 {
4805 Mutex::Autolock _l(mUidLock);
4806 if (mActiveUids.erase(uid) > 0) {
4807 deleted = true;
4808 }
4809 }
4810 if (deleted) {
4811 sp<CameraService> service = mService.promote();
4812 if (service != nullptr) {
4813 service->blockClientsForUid(uid);
4814 }
4815 }
4816}
4817
Emilian Peev53722fa2019-02-22 17:47:20 -08004818void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004819 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004820 bool procStateChange = false;
4821 {
4822 Mutex::Autolock _l(mUidLock);
4823 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4824 mMonitoredUids[uid].procState != procState) {
4825 mMonitoredUids[uid].procState = procState;
4826 procStateChange = true;
4827 }
4828 }
4829
4830 if (procStateChange) {
4831 sp<CameraService> service = mService.promote();
4832 if (service != nullptr) {
4833 service->notifyMonitoredUids();
4834 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004835 }
4836}
4837
Austin Borgerdddb7552023-03-30 17:53:01 -07004838/**
4839 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4840 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4841 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4842 * monitoredUids. If it is revised above some other monitoredUid, signal
4843 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4844 * foreground apps in split screen - state changes will capture all other cases.
4845 */
4846void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4847 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004848 {
4849 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004850 auto it = mMonitoredUids.find(uid);
4851
4852 if (it != mMonitoredUids.end()) {
4853 if (it->second.hasCamera) {
4854 for (auto &monitoredUid : mMonitoredUids) {
4855 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004856 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004857 notifyUidSet.emplace(monitoredUid.first);
4858 }
4859 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004860 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004861 notifyUidSet.emplace(uid);
4862 } else {
4863 for (auto &monitoredUid : mMonitoredUids) {
4864 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004865 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004866 notifyUidSet.emplace(uid);
4867 }
4868 }
4869 }
4870 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004871 }
4872 }
4873
Austin Borgerdddb7552023-03-30 17:53:01 -07004874 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004875 sp<CameraService> service = mService.promote();
4876 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004877 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004878 }
4879 }
4880}
4881
Austin Borgerdddb7552023-03-30 17:53:01 -07004882/**
4883 * Register a uid for monitoring, and note whether it owns a camera.
4884 */
4885void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004886 Mutex::Autolock _l(mUidLock);
4887 auto it = mMonitoredUids.find(uid);
4888 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004889 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004890 } else {
Austin Borger65577682022-02-17 00:25:43 +00004891 MonitoredUid monitoredUid;
4892 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004893 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004894 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004895 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004896 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004897 if (res != OK) {
4898 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4899 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004900 }
4901
4902 if (openCamera) {
4903 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004904 }
4905}
4906
Austin Borgerdddb7552023-03-30 17:53:01 -07004907/**
4908 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4909 */
4910void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004911 Mutex::Autolock _l(mUidLock);
4912 auto it = mMonitoredUids.find(uid);
4913 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004914 it->second.refCount--;
4915 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004916 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004917 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004918 if (res != OK) {
4919 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4920 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004921 } else if (closeCamera) {
4922 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004923 }
4924 } else {
4925 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4926 }
4927}
4928
Austin Borgered99f642023-06-01 16:51:35 -07004929bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004930 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004931 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004932}
4933
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004934static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4935static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004936
Austin Borgered99f642023-06-01 16:51:35 -07004937bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004938 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004939 // If activity manager is unreachable, assume everything is active
4940 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004941 return true;
4942 }
4943 auto it = mOverrideUids.find(uid);
4944 if (it != mOverrideUids.end()) {
4945 return it->second;
4946 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004947 bool active = mActiveUids.find(uid) != mActiveUids.end();
4948 if (!active) {
4949 // We want active UIDs to always access camera with their first attempt since
4950 // there is no guarantee the app is robustly written and would retry getting
4951 // the camera on failure. The inverse case is not a problem as we would take
4952 // camera away soon once we get the callback that the uid is no longer active.
4953 ActivityManager am;
4954 // Okay to access with a lock held as UID changes are dispatched without
4955 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004956 int64_t startTimeMillis = 0;
4957 do {
4958 // TODO: Fix this b/109950150!
4959 // Okay this is a hack. There is a race between the UID turning active and
4960 // activity being resumed. The proper fix is very risky, so we temporary add
4961 // some polling which should happen pretty rarely anyway as the race is hard
4962 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004963 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004964 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004965 if (active) {
4966 break;
4967 }
4968 if (startTimeMillis <= 0) {
4969 startTimeMillis = uptimeMillis();
4970 }
4971 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004972 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004973 if (remainingTimeMillis <= 0) {
4974 break;
4975 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004976 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4977
4978 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004979 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004980 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004981 } while (true);
4982
Svet Ganov7b4ab782018-03-25 12:48:10 -07004983 if (active) {
4984 // Now that we found out the UID is actually active, cache that
4985 mActiveUids.insert(uid);
4986 }
4987 }
4988 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004989}
4990
Varun Shahb42f1eb2019-04-16 14:45:13 -07004991int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4992 Mutex::Autolock _l(mUidLock);
4993 return getProcStateLocked(uid);
4994}
4995
4996int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4997 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4998 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004999 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07005000 }
5001 return procState;
5002}
5003
Austin Borgered99f642023-06-01 16:51:35 -07005004void CameraService::UidPolicy::addOverrideUid(uid_t uid,
5005 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07005006 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08005007}
5008
Austin Borgered99f642023-06-01 16:51:35 -07005009void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07005010 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08005011}
5012
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07005013void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
5014 Mutex::Autolock _l(mUidLock);
5015 ALOGV("UidPolicy: ActivityManager has died");
5016 mRegistered = false;
5017 mActiveUids.clear();
5018}
5019
Austin Borgered99f642023-06-01 16:51:35 -07005020void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07005021 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005022 bool wasActive = false;
5023 bool isActive = false;
5024 {
5025 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07005026 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08005027 mOverrideUids.erase(uid);
5028 if (insert) {
5029 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
5030 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07005031 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08005032 }
5033 if (wasActive != isActive && !isActive) {
5034 sp<CameraService> service = mService.promote();
5035 if (service != nullptr) {
5036 service->blockClientsForUid(uid);
5037 }
5038 }
5039}
5040
5041// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08005042// SensorPrivacyPolicy
5043// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005044
5045void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
5046{
Michael Grooverd1d435a2018-12-18 17:39:42 -08005047 Mutex::Autolock _l(mSensorPrivacyLock);
5048 if (mRegistered) {
5049 return;
5050 }
Evan Severson09ab4002021-02-10 14:15:19 -08005051 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08005052 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00005053 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005054 mSpm.addToggleSensorPrivacyListener(this);
5055 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005056 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005057 if (flags::camera_privacy_allowlist()) {
5058 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
5059 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
5060 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5061 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005062 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005063 if (res == OK) {
5064 mRegistered = true;
5065 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
5066 }
5067}
5068
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005069void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
5070 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07005071 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005072 return;
5073 }
5074
5075 registerWithSensorPrivacyManager();
5076}
5077
5078void CameraService::SensorPrivacyPolicy::registerSelf() {
5079 // Use checkservice to see if the sensor_privacy service is available
5080 // If service is not available then register for notification
5081 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07005082 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005083 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07005084 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005085 } else {
5086 registerWithSensorPrivacyManager();
5087 }
5088}
5089
Michael Grooverd1d435a2018-12-18 17:39:42 -08005090void CameraService::SensorPrivacyPolicy::unregisterSelf() {
5091 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08005092 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00005093 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005094 mSpm.removeToggleSensorPrivacyListener(this);
5095 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005096 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005097 mRegistered = false;
5098 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
5099}
5100
5101bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005102 if (!mRegistered) {
5103 registerWithSensorPrivacyManager();
5104 }
5105
Michael Grooverd1d435a2018-12-18 17:39:42 -08005106 Mutex::Autolock _l(mSensorPrivacyLock);
5107 return mSensorPrivacyEnabled;
5108}
5109
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005110int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
5111 if (!mRegistered) {
5112 registerWithSensorPrivacyManager();
5113 }
5114
5115 Mutex::Autolock _l(mSensorPrivacyLock);
5116 return mCameraPrivacyState;
5117}
5118
Evan Seversond0b69922022-01-27 10:47:34 -08005119bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08005120 if (!hasCameraPrivacyFeature()) {
5121 return false;
5122 }
Evan Seversond0b69922022-01-27 10:47:34 -08005123 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08005124}
5125
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005126bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
5127 if (!hasCameraPrivacyFeature()) {
5128 return SensorPrivacyManager::DISABLED;
5129 }
5130 return mSpm.isCameraPrivacyEnabled(packageName);
5131}
5132
Evan Seversond0b69922022-01-27 10:47:34 -08005133binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005134 int toggleType, int sensor, bool enabled) {
5135 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
5136 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
5137 {
5138 Mutex::Autolock _l(mSensorPrivacyLock);
5139 mSensorPrivacyEnabled = enabled;
5140 }
5141 // if sensor privacy is enabled then block all clients from accessing the camera
5142 if (enabled) {
5143 sp<CameraService> service = mService.promote();
5144 if (service != nullptr) {
5145 service->blockAllClients();
5146 }
5147 }
5148 }
5149 return binder::Status::ok();
5150}
5151
5152binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
5153 int, int sensor, int state) {
5154 if (!flags::camera_privacy_allowlist()
5155 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
5156 return binder::Status::ok();
5157 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08005158 {
5159 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005160 mCameraPrivacyState = state;
5161 }
5162 sp<CameraService> service = mService.promote();
5163 if (!service) {
5164 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005165 }
5166 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005167 if (state == SensorPrivacyManager::ENABLED) {
5168 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08005169 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005170 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005171 }
5172 return binder::Status::ok();
5173}
5174
5175void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
5176 Mutex::Autolock _l(mSensorPrivacyLock);
5177 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
5178 mRegistered = false;
5179}
5180
Evan Severson09ab4002021-02-10 14:15:19 -08005181bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08005182 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
5183 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5184 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
5185 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5186 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08005187}
5188
Michael Grooverd1d435a2018-12-18 17:39:42 -08005189// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005190// CameraState
5191// ----------------------------------------------------------------------------
5192
Austin Borgered99f642023-06-01 16:51:35 -07005193CameraService::CameraState::CameraState(const std::string& id, int cost,
5194 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005195 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005196 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005197 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005198
5199CameraService::CameraState::~CameraState() {}
5200
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005201CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005202 Mutex::Autolock lock(mStatusLock);
5203 return mStatus;
5204}
5205
Austin Borgered99f642023-06-01 16:51:35 -07005206std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005207 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005208 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005209 return res;
5210}
5211
Ruben Brunkcc776712015-02-17 20:18:47 -08005212CameraParameters CameraService::CameraState::getShimParams() const {
5213 return mShimParams;
5214}
5215
5216void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5217 mShimParams = params;
5218}
5219
5220int CameraService::CameraState::getCost() const {
5221 return mCost;
5222}
5223
Austin Borgered99f642023-06-01 16:51:35 -07005224std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005225 return mConflicting;
5226}
5227
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005228SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5229 return mSystemCameraKind;
5230}
5231
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005232bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5233 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5234 != mPhysicalCameras.end();
5235}
5236
Austin Borgered99f642023-06-01 16:51:35 -07005237bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005238 Mutex::Autolock lock(mStatusLock);
5239 auto result = mUnavailablePhysicalIds.insert(physicalId);
5240 return result.second;
5241}
5242
Austin Borgered99f642023-06-01 16:51:35 -07005243bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005244 Mutex::Autolock lock(mStatusLock);
5245 auto count = mUnavailablePhysicalIds.erase(physicalId);
5246 return count > 0;
5247}
5248
Austin Borgered99f642023-06-01 16:51:35 -07005249void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005250 Mutex::Autolock lock(mStatusLock);
5251 mClientPackage = clientPackage;
5252}
5253
Austin Borgered99f642023-06-01 16:51:35 -07005254std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005255 Mutex::Autolock lock(mStatusLock);
5256 return mClientPackage;
5257}
5258
Ruben Brunkcc776712015-02-17 20:18:47 -08005259// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005260// ClientEventListener
5261// ----------------------------------------------------------------------------
5262
5263void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005264 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005265 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005266 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005267 if (basicClient.get() != nullptr) {
5268 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005269 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005270 static_cast<int>(basicClient->getClientUid()));
5271 }
5272}
5273
5274void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005275 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005276 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005277 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005278 if (basicClient.get() != nullptr) {
5279 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005280 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005281 static_cast<int>(basicClient->getClientUid()));
5282 }
5283}
5284
Ruben Brunk99e69712015-05-26 17:25:07 -07005285// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005286// CameraClientManager
5287// ----------------------------------------------------------------------------
5288
Ruben Brunk99e69712015-05-26 17:25:07 -07005289CameraService::CameraClientManager::CameraClientManager() {
5290 setListener(std::make_shared<ClientEventListener>());
5291}
5292
Ruben Brunkcc776712015-02-17 20:18:47 -08005293CameraService::CameraClientManager::~CameraClientManager() {}
5294
5295sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005296 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005297 auto descriptor = get(id);
5298 if (descriptor == nullptr) {
5299 return sp<BasicClient>{nullptr};
5300 }
5301 return descriptor->getValue();
5302}
5303
Austin Borgered99f642023-06-01 16:51:35 -07005304std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005305 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005306 std::ostringstream ret;
5307 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005308 bool hasAny = false;
5309 for (auto& i : all) {
5310 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005311 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005312 int32_t cost = i->getCost();
5313 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005314 int32_t score = i->getPriority().getScore();
5315 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005316 auto conflicting = i->getConflicting();
5317 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005318 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005319 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005320 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005321 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005322 uid_t clientUid = clientSp->getClientUid();
5323 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005324 }
Austin Borgered99f642023-06-01 16:51:35 -07005325 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5326 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005327
Ruben Brunk6267b532015-04-30 17:44:07 -07005328 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005329 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005330 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005331 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005332 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005333 }
5334
Austin Borgered99f642023-06-01 16:51:35 -07005335 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005336 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005337 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005338 }
Austin Borgered99f642023-06-01 16:51:35 -07005339 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005340 }
Austin Borgered99f642023-06-01 16:51:35 -07005341 if (hasAny) ret << "\n";
5342 ret << "]\n";
5343 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005344}
5345
5346CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005347 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5348 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005349 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005350
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005351 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005352 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005353
Austin Borgered99f642023-06-01 16:51:35 -07005354 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005355 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5356 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005357}
5358
5359CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005360 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005361 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005362 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005363 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005364 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5365 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005366}
5367
5368// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005369// InjectionStatusListener
5370// ----------------------------------------------------------------------------
5371
5372void CameraService::InjectionStatusListener::addListener(
5373 const sp<ICameraInjectionCallback>& callback) {
5374 Mutex::Autolock lock(mListenerLock);
5375 if (mCameraInjectionCallback) return;
5376 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5377 if (res == OK) {
5378 mCameraInjectionCallback = callback;
5379 }
5380}
5381
5382void CameraService::InjectionStatusListener::removeListener() {
5383 Mutex::Autolock lock(mListenerLock);
5384 if (mCameraInjectionCallback == nullptr) {
5385 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5386 return;
5387 }
5388 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5389 mCameraInjectionCallback = nullptr;
5390}
5391
5392void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005393 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005394 if (mCameraInjectionCallback == nullptr) {
5395 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5396 return;
5397 }
Cliff Wud3a05312021-04-26 23:07:31 +08005398
5399 switch (err) {
5400 case -ENODEV:
5401 mCameraInjectionCallback->onInjectionError(
5402 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5403 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005404 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005405 break;
5406 case -EBUSY:
5407 mCameraInjectionCallback->onInjectionError(
5408 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5409 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005410 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005411 break;
5412 case DEAD_OBJECT:
5413 mCameraInjectionCallback->onInjectionError(
5414 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5415 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005416 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005417 break;
5418 case INVALID_OPERATION:
5419 mCameraInjectionCallback->onInjectionError(
5420 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5421 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005422 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005423 break;
5424 case UNKNOWN_TRANSACTION:
5425 mCameraInjectionCallback->onInjectionError(
5426 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5427 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005428 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005429 break;
5430 default:
5431 mCameraInjectionCallback->onInjectionError(
5432 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5433 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005434 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005435 }
Cliff Wud8cae102021-03-11 01:37:42 +08005436}
5437
5438void CameraService::InjectionStatusListener::binderDied(
5439 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005440 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5441 auto parent = mParent.promote();
5442 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005443 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5444 if (clientDescriptor != nullptr) {
5445 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5446 baseClientPtr->stopInjection();
5447 }
Cliff Wu3b268182021-07-06 15:44:43 +08005448 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005449 }
5450}
5451
5452// ----------------------------------------------------------------------------
5453// CameraInjectionSession
5454// ----------------------------------------------------------------------------
5455
5456binder::Status CameraService::CameraInjectionSession::stopInjection() {
5457 Mutex::Autolock lock(mInjectionSessionLock);
5458 auto parent = mParent.promote();
5459 if (parent == nullptr) {
5460 ALOGE("CameraInjectionSession: Parent is gone");
5461 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5462 "Camera service encountered error");
5463 }
Cliff Wud3a05312021-04-26 23:07:31 +08005464
5465 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005466 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5467 if (clientDescriptor != nullptr) {
5468 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5469 res = baseClientPtr->stopInjection();
5470 if (res != OK) {
5471 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5472 " ret != NO_ERROR: %d", res);
5473 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5474 "Camera session encountered error");
5475 }
5476 }
Cliff Wu3b268182021-07-06 15:44:43 +08005477 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005478 return binder::Status::ok();
5479}
5480
5481// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005482
5483static const int kDumpLockRetries = 50;
5484static const int kDumpLockSleep = 60000;
5485
5486static bool tryLock(Mutex& mutex)
5487{
5488 bool locked = false;
5489 for (int i = 0; i < kDumpLockRetries; ++i) {
5490 if (mutex.tryLock() == NO_ERROR) {
5491 locked = true;
5492 break;
5493 }
5494 usleep(kDumpLockSleep);
5495 }
5496 return locked;
5497}
5498
Rucha Katakwardf223072021-06-15 10:21:00 -07005499void CameraService::cacheDump() {
5500 if (mMemFd != -1) {
5501 const Vector<String16> args;
5502 ATRACE_CALL();
5503 // Acquiring service lock here will avoid the deadlock since
5504 // cacheDump will not be called during the second disconnect.
5505 Mutex::Autolock lock(mServiceLock);
5506
5507 Mutex::Autolock l(mCameraStatesLock);
5508 // Start collecting the info for open sessions and store it in temp file.
5509 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005510 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005511 auto clientDescriptor = mActiveClientManager.get(cameraId);
5512 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005513 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005514 // Log the current open session info before device is disconnected.
5515 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5516 }
5517 }
5518 }
5519}
5520
Mathias Agopian65ab4712010-07-14 17:59:35 -07005521status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005522 ATRACE_CALL();
5523
Austin Borgered99f642023-06-01 16:51:35 -07005524 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005525 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005526 getCallingPid(),
5527 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005528 return NO_ERROR;
5529 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005530 bool locked = tryLock(mServiceLock);
5531 // failed to lock - CameraService is probably deadlocked
5532 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005533 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005534 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005535
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005536 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005537 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005538
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005539 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005540 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005541
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005542 if (locked) mServiceLock.unlock();
5543 return NO_ERROR;
5544 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005545 dprintf(fd, "\n== Service global info: ==\n\n");
5546 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005547 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005548 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5549 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005550 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5551 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5552 }
Austin Borgered99f642023-06-01 16:51:35 -07005553 std::string activeClientString = mActiveClientManager.toString();
5554 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5555 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005556 if (mStreamUseCaseOverrides.size() > 0) {
5557 dprintf(fd, "Active stream use case overrides:");
5558 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5559 dprintf(fd, " %" PRId64, useCaseOverride);
5560 }
5561 dprintf(fd, "\n");
5562 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005563
5564 dumpEventLog(fd);
5565
5566 bool stateLocked = tryLock(mCameraStatesLock);
5567 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005568 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005569 }
5570
Emilian Peevbd8c5032018-02-14 23:05:40 +00005571 int argSize = args.size();
5572 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005573 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005574 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005575 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005576 }
5577 break;
5578 }
5579 }
5580
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005581 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005582 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005583
Austin Borgered99f642023-06-01 16:51:35 -07005584 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005585
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005586 CameraParameters p = state.second->getShimParams();
5587 if (!p.isEmpty()) {
5588 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5589 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005590 }
5591
5592 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005593 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005594 // log the current open session info
5595 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005596 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005597 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005598 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005599
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005600 }
5601
5602 if (stateLocked) mCameraStatesLock.unlock();
5603
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005604 if (locked) mServiceLock.unlock();
5605
Emilian Peevf53f66e2017-04-11 14:29:43 +01005606 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005607
5608 dprintf(fd, "\n== Vendor tags: ==\n\n");
5609
5610 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5611 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005612 sp<VendorTagDescriptorCache> cache =
5613 VendorTagDescriptorCache::getGlobalVendorTagCache();
5614 if (cache == NULL) {
5615 dprintf(fd, "No vendor tags.\n");
5616 } else {
5617 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5618 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005619 } else {
5620 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5621 }
5622
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005623 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005624 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005625 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005626
5627 // Process dump arguments, if any
5628 int n = args.size();
5629 String16 verboseOption("-v");
5630 String16 unreachableOption("--unreachable");
5631 for (int i = 0; i < n; i++) {
5632 if (args[i] == verboseOption) {
5633 // change logging level
5634 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005635 std::string levelStr = toStdString(args[i+1]);
5636 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005637 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005638 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005639 } else if (args[i] == unreachableOption) {
5640 // Dump memory analysis
5641 // TODO - should limit be an argument parameter?
5642 UnreachableMemoryInfo info;
5643 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5644 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005645 dprintf(fd, "\n== Unable to dump unreachable memory. "
5646 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005647 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005648 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005649 std::string s = info.ToString(/*log_contents*/ true);
5650 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005651 }
5652 }
5653 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005654
5655 bool serviceLocked = tryLock(mServiceLock);
5656
5657 // Dump info from previous open sessions.
5658 // Reposition the offset to beginning of the file before reading
5659
5660 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5661 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5662 ssize_t size_read;
5663 char buf[4096];
5664 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5665 // Read data from file to a small buffer and write it to fd.
5666 write(fd, buf, size_read);
5667 if (size_read == -1) {
5668 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5669 break;
5670 }
5671 }
5672 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5673 } else {
5674 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5675 }
5676
5677 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005678 return NO_ERROR;
5679}
5680
Rucha Katakwardf223072021-06-15 10:21:00 -07005681void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005682 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005683 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005684 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005685 getFormattedCurrentTime().c_str(),
5686 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005687 dprintf(fd, " Client priority score: %d state: %d\n",
5688 clientDescriptor->getPriority().getScore(),
5689 clientDescriptor->getPriority().getState());
5690 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5691
5692 auto client = clientDescriptor->getValue();
5693 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005694 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005695
5696 client->dumpClient(fd, args);
5697}
5698
Austin Borgered99f642023-06-01 16:51:35 -07005699void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005700 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005701 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005702}
5703
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005704void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005705 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005706
5707 Mutex::Autolock l(mLogLock);
5708 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005709 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005710 }
5711
5712 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005713 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005714 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005715 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005716 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005717 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005718}
5719
Austin Borgered99f642023-06-01 16:51:35 -07005720void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005721 Mutex::Autolock lock(mLogLock);
5722 if (!isClientWatchedLocked(client)) { return; }
5723
5724 std::vector<std::string> dumpVector;
5725 client->dumpWatchedEventsToVector(dumpVector);
5726
5727 if (dumpVector.empty()) { return; }
5728
Austin Borgered99f642023-06-01 16:51:35 -07005729 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005730
Austin Borgered99f642023-06-01 16:51:35 -07005731 std::string currentTime = getFormattedCurrentTime();
5732 dumpString << "Cached @ ";
5733 dumpString << currentTime;
5734 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005735
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005736 size_t i = dumpVector.size();
5737
5738 // Store the string in reverse order (latest last)
5739 while (i > 0) {
5740 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005741 dumpString << cameraId;
5742 dumpString << ":";
5743 dumpString << client->getPackageName();
5744 dumpString << " ";
5745 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005746 }
5747
Austin Borgered99f642023-06-01 16:51:35 -07005748 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005749}
5750
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005751void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005752 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005753 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5754 if (mTorchClientMap[i] == who) {
5755 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005756 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005757 status_t res = mFlashlight->setTorchMode(cameraId, false);
5758 if (res) {
5759 ALOGE("%s: torch client died but couldn't turn off torch: "
5760 "%s (%d)", __FUNCTION__, strerror(-res), res);
5761 return;
5762 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005763 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005764 break;
5765 }
5766 }
5767}
5768
Ruben Brunkcc776712015-02-17 20:18:47 -08005769/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005770
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005771 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005772 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5773 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005774 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005775 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005776 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005777
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005778 // check torch client
5779 handleTorchClientBinderDied(who);
5780
5781 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005782 if(!evictClientIdByRemote(who)) {
5783 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005784 return;
5785 }
5786
Ruben Brunkcc776712015-02-17 20:18:47 -08005787 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5788 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005789}
5790
Austin Borgered99f642023-06-01 16:51:35 -07005791void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005792 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005793}
5794
Austin Borgered99f642023-06-01 16:51:35 -07005795void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005796 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005797 // Do not lock mServiceLock here or can get into a deadlock from
5798 // connect() -> disconnect -> updateStatus
5799
5800 auto state = getCameraState(cameraId);
5801
5802 if (state == nullptr) {
5803 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005804 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005805 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005806 }
5807
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005808 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5809 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5810 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005811 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005812 return;
5813 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005814
Biswarup Pal37a75182024-01-16 15:53:35 +00005815 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5816 CameraMetadata cameraInfo;
5817 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00005818 cameraId, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +00005819 if (res != OK) {
5820 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5821 __FUNCTION__, cameraId.c_str());
5822 } else {
5823 int32_t deviceId = getDeviceId(cameraInfo);
5824 if (deviceId != kDefaultDeviceId) {
5825 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5826 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5827 static_cast<camera_metadata_enum_android_lens_facing_t>(
5828 lensFacingEntry.data.u8[0]);
5829 std::string mappedCameraId;
5830 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5831 mappedCameraId = kVirtualDeviceBackCameraId;
5832 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5833 mappedCameraId = kVirtualDeviceFrontCameraId;
5834 } else {
5835 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5836 __func__);
5837 }
5838 if (!mappedCameraId.empty()) {
5839 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5840 }
5841 }
5842 }
5843 }
5844
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005845 // Collect the logical cameras without holding mStatusLock in updateStatus
5846 // as that can lead to a deadlock(b/162192331).
5847 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005848 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005849 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005850 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005851 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005852 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005853 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5854 auto [deviceId, mappedCameraId] =
5855 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005856
Biswarup Pal37a75182024-01-16 15:53:35 +00005857 if (status != StatusInternal::ENUMERATING) {
5858 // Update torch status if it has a flash unit.
5859 Mutex::Autolock al(mTorchStatusMutex);
5860 TorchModeStatus torchStatus;
5861 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5862 NAME_NOT_FOUND) {
5863 TorchModeStatus newTorchStatus =
5864 status == StatusInternal::PRESENT ?
5865 TorchModeStatus::AVAILABLE_OFF :
5866 TorchModeStatus::NOT_AVAILABLE;
5867 if (torchStatus != newTorchStatus) {
5868 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5869 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005870 }
5871 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005872
Biswarup Pal37a75182024-01-16 15:53:35 +00005873 Mutex::Autolock lock(mStatusListenerLock);
5874 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5875 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005876
Biswarup Pal37a75182024-01-16 15:53:35 +00005877 for (auto& listener : mListenerList) {
5878 bool isVendorListener = listener->isVendorListener();
5879 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5880 listener->getListenerPid(), listener->getListenerUid())) {
5881 ALOGV("Skipping discovery callback for system-only camera device %s",
5882 cameraId.c_str());
5883 continue;
5884 }
5885
5886 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5887 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005888 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005889 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005890 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5891 ret.exceptionCode());
Biswarup Pal37a75182024-01-16 15:53:35 +00005892
5893 // Only cameras of the default device can be remapped to a different camera
5894 // (using remapCameraIds method), so do the following only if the camera is
5895 // associated with the default device.
5896 if (deviceId == kDefaultDeviceId) {
5897 // For the default device, also trigger the callbacks for cameras that were
5898 // remapped to the current cameraId for the specific package that this
5899 // listener belongs to.
5900 std::vector<std::string> remappedCameraIds =
5901 findOriginalIdsForRemappedCameraId(cameraId,
5902 listener->getListenerUid());
5903 for (auto &remappedCameraId: remappedCameraIds) {
5904 ret = listener->getListener()->onStatusChanged(
5905 mapToInterface(status), remappedCameraId, kDefaultDeviceId);
5906 listener->handleBinderStatus(ret,
5907 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
5908 __FUNCTION__, listener->getListenerUid(),
5909 listener->getListenerPid(), ret.exceptionCode());
5910 }
5911 }
malikakash82ed4352023-07-21 22:44:34 +00005912 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005913 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005914}
5915
Austin Borgered99f642023-06-01 16:51:35 -07005916void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5917 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005918 auto state = getCameraState(cameraId);
5919 if (state == nullptr) {
5920 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005921 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005922 return;
5923 }
5924 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005925 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005926 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005927 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005928 }
5929
Biswarup Pal37a75182024-01-16 15:53:35 +00005930 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5931 auto [deviceId, mappedCameraId] =
5932 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5933
Shuzhen Wang695044d2020-03-06 09:02:23 -08005934 Mutex::Autolock lock(mStatusListenerLock);
5935
5936 for (const auto& it : mListenerList) {
5937 if (!it->isOpenCloseCallbackAllowed()) {
5938 continue;
5939 }
5940
5941 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005942 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005943 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5944 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005945 } else {
Biswarup Pal37a75182024-01-16 15:53:35 +00005946 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005947 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005948
5949 it->handleBinderStatus(ret,
5950 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5951 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005952 }
5953}
5954
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005955template<class Func>
5956void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005957 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005958 std::initializer_list<StatusInternal> rejectSourceStates,
5959 Func onStatusUpdatedLocked) {
5960 Mutex::Autolock lock(mStatusLock);
5961 StatusInternal oldStatus = mStatus;
5962 mStatus = status;
5963
5964 if (oldStatus == status) {
5965 return;
5966 }
5967
5968 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005969 cameraId.c_str(), oldStatus, status);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005970
5971 if (oldStatus == StatusInternal::NOT_PRESENT &&
5972 (status != StatusInternal::PRESENT &&
5973 status != StatusInternal::ENUMERATING)) {
5974
5975 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5976 __FUNCTION__);
5977 mStatus = oldStatus;
5978 return;
5979 }
5980
5981 /**
5982 * Sometimes we want to conditionally do a transition.
5983 * For example if a client disconnects, we want to go to PRESENT
5984 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5985 */
5986 for (auto& rejectStatus : rejectSourceStates) {
5987 if (oldStatus == rejectStatus) {
5988 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005989 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005990 mStatus = oldStatus;
5991 return;
5992 }
5993 }
5994
5995 onStatusUpdatedLocked(cameraId, status);
5996}
5997
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005998status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005999 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006000 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006001 if (!status) {
6002 return BAD_VALUE;
6003 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006004 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
6005 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006006 // invalid camera ID or the camera doesn't have a flash unit
6007 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006008 }
6009
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006010 *status = mTorchStatusMap.valueAt(index);
6011 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006012}
6013
Austin Borgered99f642023-06-01 16:51:35 -07006014status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006015 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006016 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
6017 if (index == NAME_NOT_FOUND) {
6018 return BAD_VALUE;
6019 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006020 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006021
6022 return OK;
6023}
6024
Austin Borgered99f642023-06-01 16:51:35 -07006025std::list<std::string> CameraService::getLogicalCameras(
6026 const std::string& physicalCameraId) {
6027 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08006028 Mutex::Autolock lock(mCameraStatesLock);
6029 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07006030 if (state.second->containsPhysicalCamera(physicalCameraId)) {
6031 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08006032 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006033 }
6034 return retList;
6035}
6036
6037void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07006038 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00006039 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006040 // mStatusListenerLock is expected to be locked
6041 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08006042 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006043 // Note: we check only the deviceKind of the physical camera id
6044 // since, logical camera ids and their physical camera ids are
6045 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07006046 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
6047 listener->getListenerPid(), listener->getListenerUid())) {
6048 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07006049 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07006050 continue;
6051 }
Austin Borgere8e2c422022-05-12 13:45:24 -07006052 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00006053 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07006054 listener->handleBinderStatus(ret,
6055 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
6056 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
6057 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08006058 }
6059 }
6060}
6061
Svet Ganova453d0d2018-01-11 15:37:58 -08006062void CameraService::blockClientsForUid(uid_t uid) {
6063 const auto clients = mActiveClientManager.getAll();
6064 for (auto& current : clients) {
6065 if (current != nullptr) {
6066 const auto basicClient = current->getValue();
6067 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
6068 basicClient->block();
6069 }
6070 }
6071 }
6072}
6073
Michael Grooverd1d435a2018-12-18 17:39:42 -08006074void CameraService::blockAllClients() {
6075 const auto clients = mActiveClientManager.getAll();
6076 for (auto& current : clients) {
6077 if (current != nullptr) {
6078 const auto basicClient = current->getValue();
6079 if (basicClient.get() != nullptr) {
6080 basicClient->block();
6081 }
6082 }
6083 }
6084}
6085
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00006086void CameraService::blockPrivacyEnabledClients() {
6087 const auto clients = mActiveClientManager.getAll();
6088 for (auto& current : clients) {
6089 if (current != nullptr) {
6090 const auto basicClient = current->getValue();
6091 if (basicClient.get() != nullptr) {
6092 std::string pkgName = basicClient->getPackageName();
6093 bool cameraPrivacyEnabled =
6094 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
6095 if (cameraPrivacyEnabled) {
6096 basicClient->block();
6097 }
6098 }
6099 }
6100 }
6101}
6102
Svet Ganova453d0d2018-01-11 15:37:58 -08006103// NOTE: This is a remote API - make sure all args are validated
6104status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006105 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006106 return PERMISSION_DENIED;
6107 }
6108 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
6109 return BAD_VALUE;
6110 }
Austin Borgered99f642023-06-01 16:51:35 -07006111 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006112 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006113 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006114 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006115 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006116 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07006117 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006118 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07006119 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006120 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07006121 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006122 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07006123 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006124 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07006125 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006126 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07006127 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006128 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07006129 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006130 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07006131 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006132 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07006133 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006134 handleClearStreamUseCaseOverrides();
6135 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07006136 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006137 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07006138 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006139 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07006140 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00006141 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07006142 } else if (args.size() >= 4 && args[0] == toString16("remap-camera-id")) {
malikakash82ed4352023-07-21 22:44:34 +00006143 return handleCameraIdRemapping(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006144 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006145 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006146 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08006147 }
6148 printHelp(err);
6149 return BAD_VALUE;
6150}
6151
malikakash82ed4352023-07-21 22:44:34 +00006152status_t CameraService::handleCameraIdRemapping(const Vector<String16>& args, int err) {
6153 uid_t uid = IPCThreadState::self()->getCallingUid();
6154 if (uid != AID_ROOT) {
6155 dprintf(err, "Must be adb root\n");
6156 return PERMISSION_DENIED;
6157 }
6158 if (args.size() != 4) {
6159 dprintf(err, "Expected format: remap-camera-id <PACKAGE> <Id0> <Id1>\n");
6160 return BAD_VALUE;
6161 }
Austin Borgered99f642023-06-01 16:51:35 -07006162 std::string packageName = toStdString(args[1]);
6163 std::string cameraIdToReplace = toStdString(args[2]);
6164 std::string cameraIdNew = toStdString(args[3]);
malikakash82ed4352023-07-21 22:44:34 +00006165 remapCameraIds({{packageName, {{cameraIdToReplace, cameraIdNew}}}});
6166 return OK;
6167}
6168
Svet Ganova453d0d2018-01-11 15:37:58 -08006169status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006170 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006171
Svet Ganova453d0d2018-01-11 15:37:58 -08006172 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07006173 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006174 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07006175 } else if ((args[2] != toString16("idle"))) {
6176 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08006177 return BAD_VALUE;
6178 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006179
6180 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006181 if (args.size() >= 5 && args[3] == toString16("--user")) {
6182 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006183 }
6184
6185 uid_t uid;
6186 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
6187 return BAD_VALUE;
6188 }
6189
6190 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08006191 return NO_ERROR;
6192}
6193
6194status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006195 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006196
6197 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006198 if (args.size() >= 4 && args[2] == toString16("--user")) {
6199 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006200 }
6201
6202 uid_t uid;
6203 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006204 return BAD_VALUE;
6205 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006206
6207 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08006208 return NO_ERROR;
6209}
6210
6211status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006212 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006213
6214 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006215 if (args.size() >= 4 && args[2] == toString16("--user")) {
6216 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006217 }
6218
6219 uid_t uid;
6220 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006221 return BAD_VALUE;
6222 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006223
6224 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006225 return dprintf(out, "active\n");
6226 } else {
6227 return dprintf(out, "idle\n");
6228 }
6229}
6230
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006231status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006232 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006233 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
6234 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
6235 Mutex::Autolock lock(mServiceLock);
6236
6237 mOverrideRotateAndCropMode = rotateValue;
6238
6239 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6240
6241 const auto clients = mActiveClientManager.getAll();
6242 for (auto& current : clients) {
6243 if (current != nullptr) {
6244 const auto basicClient = current->getValue();
6245 if (basicClient.get() != nullptr) {
6246 basicClient->setRotateAndCropOverride(rotateValue);
6247 }
6248 }
6249 }
6250
6251 return OK;
6252}
6253
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006254status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6255 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006256 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006257 if ((*end != '\0') ||
6258 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6259 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6260 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6261 return BAD_VALUE;
6262 }
6263
6264 Mutex::Autolock lock(mServiceLock);
6265 mOverrideAutoframingMode = autoframingValue;
6266
6267 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6268
6269 const auto clients = mActiveClientManager.getAll();
6270 for (auto& current : clients) {
6271 if (current != nullptr) {
6272 const auto basicClient = current->getValue();
6273 if (basicClient.get() != nullptr) {
6274 basicClient->setAutoframingOverride(autoframingValue);
6275 }
6276 }
6277 }
6278
6279 return OK;
6280}
6281
Ravneetaeb20dc2022-03-30 05:33:03 +00006282status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006283 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006284
6285 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6286
6287 Mutex::Autolock lock(mServiceLock);
6288
6289 mCameraServiceWatchdogEnabled = enableWatchdog;
6290
6291 const auto clients = mActiveClientManager.getAll();
6292 for (auto& current : clients) {
6293 if (current != nullptr) {
6294 const auto basicClient = current->getValue();
6295 if (basicClient.get() != nullptr) {
6296 basicClient->setCameraServiceWatchdog(enableWatchdog);
6297 }
6298 }
6299 }
6300
6301 return OK;
6302}
6303
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006304status_t CameraService::handleGetRotateAndCrop(int out) {
6305 Mutex::Autolock lock(mServiceLock);
6306
6307 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6308}
6309
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006310status_t CameraService::handleGetAutoframing(int out) {
6311 Mutex::Autolock lock(mServiceLock);
6312
6313 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6314}
6315
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006316status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6317 char *endPtr;
6318 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006319 std::string maskString = toStdString(args[1]);
6320 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006321
6322 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006323 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006324 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6325
6326 Mutex::Autolock lock(mServiceLock);
6327
6328 mImageDumpMask = maskValue;
6329
6330 return OK;
6331}
6332
6333status_t CameraService::handleGetImageDumpMask(int out) {
6334 Mutex::Autolock lock(mServiceLock);
6335
6336 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6337}
6338
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006339status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006340 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006341 if (errno != 0) return BAD_VALUE;
6342
6343 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6344 Mutex::Autolock lock(mServiceLock);
6345
6346 mOverrideCameraMuteMode = (muteValue == 1);
6347
6348 const auto clients = mActiveClientManager.getAll();
6349 for (auto& current : clients) {
6350 if (current != nullptr) {
6351 const auto basicClient = current->getValue();
6352 if (basicClient.get() != nullptr) {
6353 if (basicClient->supportsCameraMute()) {
6354 basicClient->setCameraMute(mOverrideCameraMuteMode);
6355 }
6356 }
6357 }
6358 }
6359
6360 return OK;
6361}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006362
Shuzhen Wang16610a62022-12-15 22:38:07 -08006363status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6364 std::vector<int64_t> useCasesOverride;
6365 for (size_t i = 1; i < args.size(); i++) {
6366 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006367 std::string arg = toStdString(args[i]);
6368 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006369 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006370 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006371 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006372 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006373 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006374 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006375 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006376 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006377 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006378 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006379 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006380 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006381 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6382 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006383 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006384 return BAD_VALUE;
6385 }
6386 useCasesOverride.push_back(useCase);
6387 }
6388
6389 Mutex::Autolock lock(mServiceLock);
6390 mStreamUseCaseOverrides = std::move(useCasesOverride);
6391
6392 return OK;
6393}
6394
6395void CameraService::handleClearStreamUseCaseOverrides() {
6396 Mutex::Autolock lock(mServiceLock);
6397 mStreamUseCaseOverrides.clear();
6398}
6399
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006400status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6401 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006402 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006403 if ((*end != '\0') ||
6404 (zoomOverrideValue != -1 &&
6405 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6406 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6407 return BAD_VALUE;
6408 }
6409
6410 Mutex::Autolock lock(mServiceLock);
6411 mZoomOverrideValue = zoomOverrideValue;
6412
6413 const auto clients = mActiveClientManager.getAll();
6414 for (auto& current : clients) {
6415 if (current != nullptr) {
6416 const auto basicClient = current->getValue();
6417 if (basicClient.get() != nullptr) {
6418 if (basicClient->supportsZoomOverride()) {
6419 basicClient->setZoomOverride(mZoomOverrideValue);
6420 }
6421 }
6422 }
6423 }
6424
6425 return OK;
6426}
6427
Avichal Rakesh84147132021-11-11 17:47:11 -08006428status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006429 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006430 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006431 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006432 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006433 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006434 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006435 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006436 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006437 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006438 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006439 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006440 dprintf(outFd, "Camera service watch commands:\n"
6441 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6442 " starts watching the provided tags for clients with provided package\n"
6443 " recognizes tag shorthands like '3a'\n"
6444 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006445 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006446 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006447 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006448 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006449 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006450 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006451 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006452}
6453
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006454status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6455 Mutex::Autolock lock(mLogLock);
6456 size_t tagsIdx; // index of '-m'
6457 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006458 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006459 if (tagsIdx < args.size() - 1) {
6460 tags = args[tagsIdx + 1];
6461 } else {
6462 dprintf(outFd, "No tags provided.\n");
6463 return BAD_VALUE;
6464 }
6465
6466 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006467 // watch all clients if no clients are provided
6468 String16 clients = toString16(kWatchAllClientsFlag);
6469 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006470 clientsIdx++);
6471 if (clientsIdx < args.size() - 1) {
6472 clients = args[clientsIdx + 1];
6473 }
Austin Borgered99f642023-06-01 16:51:35 -07006474 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006475
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006476 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006477 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006478
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006479 bool serviceLock = tryLock(mServiceLock);
6480 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006481 auto cameraClients = mActiveClientManager.getAll();
6482 for (const auto &clientDescriptor: cameraClients) {
6483 if (clientDescriptor == nullptr) { continue; }
6484 sp<BasicClient> client = clientDescriptor->getValue();
6485 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006486
6487 if (isClientWatchedLocked(client.get())) {
6488 client->startWatchingTags(mMonitorTags, outFd);
6489 numWatchedClients++;
6490 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006491 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006492 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6493
6494 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006495 return OK;
6496}
6497
6498status_t CameraService::stopWatchingTags(int outFd) {
6499 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006500 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006501 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006502
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006503 mWatchedClientPackages.clear();
6504 mWatchedClientsDumpCache.clear();
6505
6506 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006507 auto cameraClients = mActiveClientManager.getAll();
6508 for (const auto &clientDescriptor : cameraClients) {
6509 if (clientDescriptor == nullptr) { continue; }
6510 sp<BasicClient> client = clientDescriptor->getValue();
6511 if (client.get() == nullptr) { continue; }
6512 client->stopWatchingTags(outFd);
6513 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006514 dprintf(outFd, "Stopped watching all clients.\n");
6515 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006516 return OK;
6517}
6518
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006519status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6520 Mutex::Autolock lock(mLogLock);
6521 size_t clearedSize = mWatchedClientsDumpCache.size();
6522 mWatchedClientsDumpCache.clear();
6523 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6524 return OK;
6525}
6526
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006527status_t CameraService::printWatchedTags(int outFd) {
6528 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006529 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006530
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006531 bool printedSomething = false; // tracks if any monitoring information was printed
6532 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006533
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006534 bool serviceLock = tryLock(mServiceLock);
6535 // get all watched clients that are currently connected
6536 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6537 if (clientDescriptor == nullptr) { continue; }
6538
6539 sp<BasicClient> client = clientDescriptor->getValue();
6540 if (client.get() == nullptr) { continue; }
6541 if (!isClientWatchedLocked(client.get())) { continue; }
6542
6543 std::vector<std::string> dumpVector;
6544 client->dumpWatchedEventsToVector(dumpVector);
6545
6546 size_t printIdx = dumpVector.size();
6547 if (printIdx == 0) {
6548 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006549 }
6550
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006551 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006552 const std::string &cameraId = clientDescriptor->getKey();
6553 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006554 while(printIdx > 0) {
6555 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006556 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006557 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006558 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006559 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006560 printedSomething = true;
6561
6562 connectedMonitoredClients.emplace(client->getPackageName());
6563 }
6564 if (serviceLock) { mServiceLock.unlock(); }
6565
6566 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6567 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006568 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006569 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6570 continue;
6571 }
6572
Austin Borgered99f642023-06-01 16:51:35 -07006573 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006574 dprintf(outFd, "%s\n", kv.second.c_str());
6575 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006576 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006577
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006578 if (!printedSomething) {
6579 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006580 }
6581
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006582 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006583}
6584
Avichal Rakesh84147132021-11-11 17:47:11 -08006585// Print all events in vector `events' that came after lastPrintedEvent
6586void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006587 const std::string &cameraId,
6588 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006589 const std::vector<std::string> &events,
6590 const std::string &lastPrintedEvent) {
6591 if (events.empty()) { return; }
6592
6593 // index of lastPrintedEvent in events.
6594 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6595 size_t lastPrintedIdx;
6596 for (lastPrintedIdx = 0;
6597 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6598 lastPrintedIdx++);
6599
6600 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6601
Avichal Rakesh84147132021-11-11 17:47:11 -08006602 // print events in chronological order (latest event last)
6603 size_t idxToPrint = lastPrintedIdx;
6604 do {
6605 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006606 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6607 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006608 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006609}
6610
6611// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6612// command should be interrupted if the user presses the return key, or if user loses any way to
6613// signal interrupt.
6614// If timeoutMs == 0, this function will always return false
6615bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6616 struct timeval startTime;
6617 int startTimeError = gettimeofday(&startTime, nullptr);
6618 if (startTimeError) {
6619 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6620 return true;
6621 }
6622
6623 const nfds_t numFds = 1;
6624 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6625
6626 struct timeval currTime;
6627 char buffer[2];
6628 while(true) {
6629 int currTimeError = gettimeofday(&currTime, nullptr);
6630 if (currTimeError) {
6631 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6632 return true;
6633 }
6634
6635 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6636 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6637 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6638
6639 if (remainingTimeMs <= 0) {
6640 // No user interrupt within timeoutMs, don't interrupt watch command
6641 return false;
6642 }
6643
6644 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6645 if (numFdsUpdated < 0) {
6646 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6647 return true;
6648 }
6649
6650 if (numFdsUpdated == 0) {
6651 // No user input within timeoutMs, don't interrupt watch command
6652 return false;
6653 }
6654
6655 if (!(pollFd.revents & POLLIN)) {
6656 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6657 return true;
6658 }
6659
6660 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6661 if (sizeRead < 0) {
6662 dprintf(outFd, "Error reading user input. Exiting.\n");
6663 return true;
6664 }
6665
6666 if (sizeRead == 0) {
6667 // Reached end of input fd (can happen if input is piped)
6668 // User has no way to signal an interrupt, so interrupt here
6669 return true;
6670 }
6671
6672 if (buffer[0] == '\n') {
6673 // User pressed return, interrupt watch command.
6674 return true;
6675 }
6676 }
6677}
6678
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006679status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6680 int inFd, int outFd) {
6681 // Figure out refresh interval, if present in args
6682 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006683 if (args.size() > 2) {
6684 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006685 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006686 intervalIdx++);
6687
6688 size_t intervalValIdx = intervalIdx + 1;
6689 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006690 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006691 if (errno) { return BAD_VALUE; }
6692 }
6693 }
6694
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006695 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6696 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006697
Avichal Rakesh84147132021-11-11 17:47:11 -08006698 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006699 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006700
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006701 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006702 bool serviceLock = tryLock(mServiceLock);
6703 auto cameraClients = mActiveClientManager.getAll();
6704 if (serviceLock) { mServiceLock.unlock(); }
6705
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006706 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006707 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006708 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006709
6710 sp<BasicClient> client = clientDescriptor->getValue();
6711 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006712 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006713
Austin Borgered99f642023-06-01 16:51:35 -07006714 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006715 // This also initializes the map entries with an empty string
6716 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6717
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006718 std::vector<std::string> latestEvents;
6719 client->dumpWatchedEventsToVector(latestEvents);
6720
6721 if (!latestEvents.empty()) {
6722 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006723 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006724 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006725 latestEvents,
6726 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006727 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006728 }
6729 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006730 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006731 break;
6732 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006733 }
6734 return OK;
6735}
6736
Austin Borgered99f642023-06-01 16:51:35 -07006737void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006738 mWatchedClientPackages.clear();
6739
Austin Borgered99f642023-06-01 16:51:35 -07006740 std::istringstream iss(clients);
6741 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006742
Austin Borgered99f642023-06-01 16:51:35 -07006743 while (std::getline(iss, nextClient, ',')) {
6744 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006745 // Don't need to track any other package if 'all' is present
6746 mWatchedClientPackages.clear();
6747 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6748 break;
6749 }
6750
6751 // track package names
6752 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006753 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006754}
6755
Svet Ganova453d0d2018-01-11 15:37:58 -08006756status_t CameraService::printHelp(int out) {
6757 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006758 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6759 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6760 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006761 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6762 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6763 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006764 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6765 " Valid values 0=false, 1=true, 2=auto\n"
6766 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006767 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6768 " Valid values 0=OFF, 1=ON for JPEG\n"
6769 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006770 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006771 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6772 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6773 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6774 " on. In case the number of usecases is smaller than the number of streams, the\n"
6775 " last use case is assigned to all the remaining streams. In case of multiple\n"
6776 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6777 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6778 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6779 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006780 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6781 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006782 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6783 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006784 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
malikakash73125c62023-07-21 22:44:34 +00006785 " remap-camera-id <PACKAGE> <Id0> <Id1> remaps camera ids. Must use adb root\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006786 " help print this message\n");
6787}
6788
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006789bool CameraService::isClientWatched(const BasicClient *client) {
6790 Mutex::Autolock lock(mLogLock);
6791 return isClientWatchedLocked(client);
6792}
6793
6794bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6795 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6796 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6797}
6798
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006799int32_t CameraService::updateAudioRestriction() {
6800 Mutex::Autolock lock(mServiceLock);
6801 return updateAudioRestrictionLocked();
6802}
6803
6804int32_t CameraService::updateAudioRestrictionLocked() {
6805 int32_t mode = 0;
6806 // iterate through all active client
6807 for (const auto& i : mActiveClientManager.getAll()) {
6808 const auto clientSp = i->getValue();
6809 mode |= clientSp->getAudioRestriction();
6810 }
6811
6812 bool modeChanged = (mAudioRestriction != mode);
6813 mAudioRestriction = mode;
6814 if (modeChanged) {
6815 mAppOps.setCameraAudioRestriction(mode);
6816 }
6817 return mode;
6818}
6819
Austin Borgered99f642023-06-01 16:51:35 -07006820status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006821 sp<BasicClient> clientSp) {
6822 std::unique_ptr<AutoConditionLock> lock =
6823 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6824 status_t res = NO_ERROR;
6825 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006826 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006827 mInjectionStatusListener->notifyInjectionError(
6828 externalCamId, UNKNOWN_TRANSACTION);
6829 clientSp->notifyError(
6830 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6831 CaptureResultExtras());
6832
6833 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6834 // other clients from connecting in mServiceLockWrapper if held
6835 mServiceLock.unlock();
6836
6837 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006838 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006839 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006840 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006841
6842 // Reacquire mServiceLock
6843 mServiceLock.lock();
6844 }
6845
6846 return res;
6847}
6848
Cliff Wud3a05312021-04-26 23:07:31 +08006849void CameraService::clearInjectionParameters() {
6850 {
6851 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006852 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006853 mInjectionInternalCamId = "";
6854 }
6855 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006856 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006857}
6858
Biswarup Pal37a75182024-01-16 15:53:35 +00006859} // namespace android