blob: dd64ff92046936cd8b07168884b863874da2f1f7 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080024#include <cstdlib>
Ruben Brunkcc776712015-02-17 20:18:47 -080025#include <cstring>
26#include <ctime>
Austin Borgered99f642023-06-01 16:51:35 -070027#include <iostream>
28#include <sstream>
Ruben Brunkcc776712015-02-17 20:18:47 -080029#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080031#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <pthread.h>
Avichal Rakesh84147132021-11-11 17:47:11 -080033#include <poll.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070034
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080035#include <android/hardware/ICamera.h>
36#include <android/hardware/ICameraClient.h>
37
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -070038#include <aidl/AidlCameraService.h>
Alex Deymo9c2a2c22016-08-25 11:59:14 -070039#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080040#include <android-base/parseint.h>
Biswarup Pal37a75182024-01-16 15:53:35 +000041#include <android_companion_virtualdevice_flags.h>
42#include <android/companion/virtualnative/IVirtualDeviceManagerNative.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080043#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080044#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046#include <binder/MemoryBase.h>
47#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080048#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080049#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080050#include <binderthreadstate/CallerUtils.h>
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -070051#include <com_android_internal_camera_flags.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070052#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070053#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080054#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080055#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070057#include "hidl/HidlCameraService.h"
58#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080059#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070060#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080062#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070063#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070064#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000065#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070066#include <utils/Errors.h>
67#include <utils/Log.h>
68#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070069#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080070#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080071#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080072#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080073#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070074#include <system/camera_metadata.h>
Kunal Malhotrabfc96052023-02-28 23:25:34 +000075#include <binder/IServiceManager.h>
76#include <binder/IActivityManager.h>
Biswarup Pal37a75182024-01-16 15:53:35 +000077#include <camera/CameraUtils.h>
Austin Borgered99f642023-06-01 16:51:35 -070078#include <camera/StringUtils.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080079
Ruben Brunkb2119af2014-05-09 19:57:56 -070080#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070081
82#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070083#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070084#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070085#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000086#include "utils/TagMonitor.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070087#include "utils/CameraServiceProxyWrapper.h"
Shuzhen Wang045be6c2023-10-12 10:01:10 -070088#include "utils/SessionConfigurationUtils.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080090namespace {
91 const char* kPermissionServiceName = "permission";
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080092 const char* kActivityServiceName = "activity";
93 const char* kSensorPrivacyServiceName = "sensor_privacy";
94 const char* kAppopsServiceName = "appops";
Jyoti Bhayanada519ab2023-05-15 15:49:15 -070095 const char* kProcessInfoServiceName = "processinfo";
Biswarup Pal37a75182024-01-16 15:53:35 +000096 const char* kVirtualDeviceBackCameraId = "0";
97 const char* kVirtualDeviceFrontCameraId = "1";
98
99 int32_t getDeviceId(const android::CameraMetadata& cameraInfo) {
100 if (!cameraInfo.exists(ANDROID_INFO_DEVICE_ID)) {
101 return android::kDefaultDeviceId;
102 }
103
104 const auto &deviceIdEntry = cameraInfo.find(ANDROID_INFO_DEVICE_ID);
105 return deviceIdEntry.data.i32[0];
106 }
107} // namespace anonymous
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -0800108
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109namespace android {
110
Austin Borgerea931242021-12-13 23:10:41 +0000111using namespace camera3;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700112using namespace camera3::SessionConfigurationUtils;
113
114using binder::Status;
Biswarup Pal37a75182024-01-16 15:53:35 +0000115using companion::virtualnative::IVirtualDeviceManagerNative;
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700116using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700117using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800118using hardware::ICamera;
119using hardware::ICameraClient;
120using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800121using hardware::camera2::ICameraInjectionCallback;
122using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800123using hardware::camera2::utils::CameraIdAndSessionConfiguration;
124using hardware::camera2::utils::ConcurrentCameraIdCombination;
Biswarup Pal37a75182024-01-16 15:53:35 +0000125
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -0700126namespace flags = com::android::internal::camera::flags;
Biswarup Pal37a75182024-01-16 15:53:35 +0000127namespace vd_flags = android::companion::virtualdevice::flags;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800128
Mathias Agopian65ab4712010-07-14 17:59:35 -0700129// ----------------------------------------------------------------------------
130// Logging support -- this is for debugging only
131// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700132volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700133
Steve Blockb8a80522011-12-20 16:23:08 +0000134#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
135#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700136
137static void setLogLevel(int level) {
138 android_atomic_write(level, &gLogLevel);
139}
140
Henri Chataingbcb99452023-11-01 17:40:30 +0000141int32_t format_as(CameraService::StatusInternal s) {
142 return fmt::underlying(s);
143}
144
Mathias Agopian65ab4712010-07-14 17:59:35 -0700145// ----------------------------------------------------------------------------
146
Austin Borger249e6592024-03-10 22:28:11 -0700147// Permission strings (references to AttributionAndPermissionUtils for brevity)
148static const std::string &sDumpPermission =
149 AttributionAndPermissionUtils::sDumpPermission;
150static const std::string &sManageCameraPermission =
151 AttributionAndPermissionUtils::sManageCameraPermission;
152static const std::string &sCameraSendSystemEventsPermission =
153 AttributionAndPermissionUtils::sCameraSendSystemEventsPermission;
154static const std::string &sCameraInjectExternalCameraPermission =
155 AttributionAndPermissionUtils::sCameraInjectExternalCameraPermission;
156
Kunal Malhotrabfc96052023-02-28 23:25:34 +0000157// Constant integer for FGS Logging, used to denote the API type for logger
158static const int LOG_FGS_CAMERA_API = 1;
Rucha Katakwardf223072021-06-15 10:21:00 -0700159const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800160static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
161static constexpr int32_t kSystemNativeClientState =
162 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Austin Borgered99f642023-06-01 16:51:35 -0700163static const std::string kServiceName("cameraserver");
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700164
Austin Borgered99f642023-06-01 16:51:35 -0700165const std::string CameraService::kOfflineDevice("offline-");
166const std::string CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700167
Rucha Katakward9ea6452021-05-06 11:57:16 -0700168// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700169static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700170
Austin Borger74fca042022-05-23 12:41:21 -0700171CameraService::CameraService(
Austin Borger249e6592024-03-10 22:28:11 -0700172 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,
173 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils) :
174 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils == nullptr ?
175 std::make_shared<AttributionAndPermissionUtils>()\
176 : attributionAndPermissionUtils),
Austin Borger74fca042022-05-23 12:41:21 -0700177 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
178 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800179 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800180 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700181 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700182 mSoundRef(0), mInitialized(false),
183 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000184 ALOGI("CameraService started (pid=%d)", getpid());
Austin Borger249e6592024-03-10 22:28:11 -0700185 mAttributionAndPermissionUtils->setCameraService(this);
Ruben Brunkcc776712015-02-17 20:18:47 -0800186 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700187 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
188 if (mMemFd == -1) {
189 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
190 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700191}
192
Charles Chena7b613c2023-01-24 21:57:33 +0000193// Enable processes with isolated AID to request the binder
194void CameraService::instantiate() {
195 CameraService::publish(true);
196}
197
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800198void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700199 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800200 return;
201 }
202
203 ALOGV("appops service registered. setting camera audio restriction");
204 mAppOps.setCameraAudioRestriction(mAudioRestriction);
205}
206
Iliyan Malchev8951a972011-04-14 16:55:59 -0700207void CameraService::onFirstRef()
208{
Ruben Brunkcc776712015-02-17 20:18:47 -0800209 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800210
Iliyan Malchev8951a972011-04-14 16:55:59 -0700211 BnCameraService::onFirstRef();
212
Ruben Brunk99e69712015-05-26 17:25:07 -0700213 // Update battery life tracking if service is restarting
214 BatteryNotifier& notifier(BatteryNotifier::getInstance());
215 notifier.noteResetCamera();
216 notifier.noteResetFlashlight();
217
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800218 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800219
Emilian Peevf53f66e2017-04-11 14:29:43 +0100220 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800221 if (res == OK) {
222 mInitialized = true;
223 }
224
Svet Ganova453d0d2018-01-11 15:37:58 -0800225 mUidPolicy = new UidPolicy(this);
226 mUidPolicy->registerSelf();
Austin Borger249e6592024-03-10 22:28:11 -0700227 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this, mAttributionAndPermissionUtils);
Michael Grooverd1d435a2018-12-18 17:39:42 -0800228 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800229 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800230
231 // appops function setCamerAudioRestriction uses getService which
232 // is blocking till the appops service is ready. To enable early
233 // boot availability for cameraservice, use checkService which is
234 // non blocking and register for notifications
235 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700236 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800237 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700238 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800239 } else {
240 mAppOps.setCameraAudioRestriction(mAudioRestriction);
241 }
242
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700243 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
244 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000245 // Deprecated, so it will fail to register on newer devices
246 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700247 __FUNCTION__);
248 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700249
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700250 if (!AidlCameraService::registerService(this)) {
251 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
252 }
253
Shuzhen Wang24b44152019-09-20 10:38:11 -0700254 // This needs to be last call in this function, so that it's as close to
255 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700256 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700257 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800258}
259
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800260status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800261 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100262
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800263 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000264 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800265 {
266 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800267
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800268 if (nullptr == mCameraProviderManager.get()) {
269 mCameraProviderManager = new CameraProviderManager();
270 res = mCameraProviderManager->initialize(this);
271 if (res != OK) {
272 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
273 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700274 logServiceError("Unable to initialize camera provider manager",
275 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800276 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100277 }
278 }
279
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800280 // Setup vendor tags before we call get_camera_info the first time
281 // because HAL might need to setup static vendor keys in get_camera_info
282 // TODO: maybe put this into CameraProviderManager::initialize()?
283 mCameraProviderManager->setUpVendorTags();
284
285 if (nullptr == mFlashlight.get()) {
286 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700287 }
288
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800289 res = mFlashlight->findFlashUnits();
290 if (res != OK) {
291 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
292 }
293
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000294 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800295 }
296
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800297 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700298 if (getCameraState(cameraId) == nullptr) {
299 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800300 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000301 if (unavailPhysicalIds.count(cameraId) > 0) {
302 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700303 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000304 }
305 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800306 }
307
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700308 // Derive primary rear/front cameras, and filter their charactierstics.
309 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700310 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700311 // Assume internal cameras are advertised from the same
312 // provider. If multiple providers are registered at different time,
313 // and each provider contains multiple internal color cameras, the current
314 // logic may filter the characteristics of more than one front/rear color
315 // cameras.
316 Mutex::Autolock l(mServiceLock);
317 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700318 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700319
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800320 return OK;
321}
322
Austin Borgered99f642023-06-01 16:51:35 -0700323void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700324 SystemCameraKind systemCameraKind) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000325 // Get the device id and app-visible camera id for the given HAL-visible camera id.
326 auto [deviceId, mappedCameraId] =
327 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
328
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800329 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800330 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700331 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
332 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000333 ALOGV("%s: Skipping torch callback for system-only camera device %s",
334 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700335 continue;
336 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000337
Austin Borgere8e2c422022-05-12 13:45:24 -0700338 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Biswarup Pal37a75182024-01-16 15:53:35 +0000339 mappedCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700340 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
341 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Biswarup Pal37a75182024-01-16 15:53:35 +0000342
343 // Only cameras of the default device can be remapped to a different camera (using
344 // remapCameraIds method), so do the following only if the camera is associated with the
345 // default device.
346 if (deviceId == kDefaultDeviceId) {
347 // For the default device, also trigger the torch callbacks for cameras that were
348 // remapped to the current cameraId for the specific package that this listener belongs
349 // to.
350 std::vector<std::string> remappedCameraIds =
351 findOriginalIdsForRemappedCameraId(cameraId, i->getListenerUid());
352 for (auto &remappedCameraId: remappedCameraIds) {
353 ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
354 remappedCameraId, kDefaultDeviceId);
355 i->handleBinderStatus(ret,
356 "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
357 __FUNCTION__, i->getListenerUid(), i->getListenerPid(),
358 ret.exceptionCode());
359 }
malikakash82ed4352023-07-21 22:44:34 +0000360 }
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800361 }
362}
363
Mathias Agopian65ab4712010-07-14 17:59:35 -0700364CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800365 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800366 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800367 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800368 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700369}
370
Emilian Peevaee727d2017-05-04 16:35:48 +0100371void CameraService::onNewProviderRegistered() {
372 enumerateProviders();
373}
374
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700375void CameraService::filterAPI1SystemCameraLocked(
376 const std::vector<std::string> &normalDeviceIds) {
377 mNormalDeviceIdsWithoutSystemCamera.clear();
Biswarup Pal37a75182024-01-16 15:53:35 +0000378 for (auto &cameraId : normalDeviceIds) {
379 if (vd_flags::camera_device_awareness()) {
380 CameraMetadata cameraInfo;
381 status_t res = mCameraProviderManager->getCameraCharacteristics(
382 cameraId, false, &cameraInfo, false);
383 int32_t deviceId = kDefaultDeviceId;
384 if (res != OK) {
385 ALOGW("%s: Not able to get camera characteristics for camera id %s",
386 __FUNCTION__, cameraId.c_str());
387 } else {
388 deviceId = getDeviceId(cameraInfo);
389 }
390 // Cameras associated with non-default device id's (i.e., virtual cameras) can never be
391 // system cameras, so skip for non-default device id's.
392 if (deviceId != kDefaultDeviceId) {
393 continue;
394 }
395 }
396
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700397 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Biswarup Pal37a75182024-01-16 15:53:35 +0000398 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
399 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700400 continue;
401 }
402 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700403 // All system camera ids will necessarily come after public camera
404 // device ids as per the HAL interface contract.
405 break;
406 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000407 mNormalDeviceIdsWithoutSystemCamera.push_back(cameraId);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700408 }
409 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
410 mNormalDeviceIdsWithoutSystemCamera.size());
411}
412
Austin Borgered99f642023-06-01 16:51:35 -0700413status_t CameraService::getSystemCameraKind(const std::string& cameraId,
414 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700415 auto state = getCameraState(cameraId);
416 if (state != nullptr) {
417 *kind = state->getSystemCameraKind();
418 return OK;
419 }
420 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700421 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700422}
423
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800424void CameraService::updateCameraNumAndIds() {
425 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700426 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
427 // Excludes hidden secure cameras
428 mNumberOfCameras =
429 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
430 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800431 mNormalDeviceIds =
432 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700433 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800434}
435
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700436void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700437 // To claim to be S Performance primary cameras, the cameras must be
438 // backward compatible. So performance class primary camera Ids must be API1
439 // compatible.
440 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
441 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
442 int facing = -1;
443 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800444 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -0700445 getDeviceVersion(cameraId, /*overrideToPortrait*/false, /*out*/&portraitRotation,
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800446 /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700447 if (facing == -1) {
448 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
449 return;
450 }
451
452 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
453 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700454 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
455 if (res == OK) {
456 mPerfClassPrimaryCameraIds.insert(cameraId);
457 } else {
458 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
459 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
460 break;
461 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700462
463 if (facing == hardware::CAMERA_FACING_BACK) {
464 firstRearCameraSeen = true;
465 }
466 if (facing == hardware::CAMERA_FACING_FRONT) {
467 firstFrontCameraSeen = true;
468 }
469 }
470
471 if (firstRearCameraSeen && firstFrontCameraSeen) {
472 break;
473 }
474 }
475}
476
Austin Borgered99f642023-06-01 16:51:35 -0700477void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700478 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100479 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
480 if (res != OK) {
481 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
482 return;
483 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000484 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700485 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
486 if (res != OK) {
487 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
488 return;
489 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000490 std::vector<std::string> physicalCameraIds;
491 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700492 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100493 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700494 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100495 }
496
497 {
498 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700499 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000500 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100501 }
502
Austin Borgered99f642023-06-01 16:51:35 -0700503 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100504 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700505 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800506
Austin Borgered99f642023-06-01 16:51:35 -0700507 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100508 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800509
510 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700511 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100512}
513
Austin Borgered99f642023-06-01 16:51:35 -0700514void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800515 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700516 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100517 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700518 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100519 }
520
521 {
522 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700523 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100524 }
525}
526
Austin Borgered99f642023-06-01 16:51:35 -0700527void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800528 CameraDeviceStatus newHalStatus) {
529 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700530 cameraId.c_str(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700531
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800532 StatusInternal newStatus = mapToInternal(newHalStatus);
533
Austin Borgered99f642023-06-01 16:51:35 -0700534 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800535
536 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700537 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100538 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700539 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100540
541 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700542 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100543
Austin Borgered99f642023-06-01 16:51:35 -0700544 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700545 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700546 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700547 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700548 return;
549 }
550
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800551 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800552
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800553 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800554 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700555 return;
556 }
557
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800558 if (newStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000559 logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
560 oldStatus, newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800561 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
562 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700563 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000564 mVirtualDeviceCameraIdMapper.removeCamera(cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800565
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800566 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700567 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800568 // Don't do this in updateStatus to avoid deadlock over mServiceLock
569 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700570
Ruben Brunkcc776712015-02-17 20:18:47 -0800571 // Remove cached shim parameters
572 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700573
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800574 // Remove online as well as offline client from the list of active clients,
575 // if they are present
Austin Borgered99f642023-06-01 16:51:35 -0700576 clientToDisconnectOnline = removeClientLocked(cameraId);
577 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700578 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800579
Austin Borgered99f642023-06-01 16:51:35 -0700580 disconnectClient(cameraId, clientToDisconnectOnline);
581 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700582
Austin Borgered99f642023-06-01 16:51:35 -0700583 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800584 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800585 if (oldStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000586 logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
587 oldStatus, newStatus));
Ruben Brunka8ca9152015-04-07 14:23:40 -0700588 }
Austin Borgered99f642023-06-01 16:51:35 -0700589 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700590 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800591}
Igor Murashkincba2c162013-03-20 15:56:31 -0700592
Austin Borgered99f642023-06-01 16:51:35 -0700593void CameraService::onDeviceStatusChanged(const std::string& id,
594 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800595 CameraDeviceStatus newHalStatus) {
596 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700597 __FUNCTION__, id.c_str(), physicalId.c_str(), newHalStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800598
599 StatusInternal newStatus = mapToInternal(newHalStatus);
600
601 std::shared_ptr<CameraState> state = getCameraState(id);
602
603 if (state == nullptr) {
604 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700605 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800606 return;
607 }
608
609 StatusInternal logicalCameraStatus = state->getStatus();
610 if (logicalCameraStatus != StatusInternal::PRESENT &&
611 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
612 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Austin Borgered99f642023-06-01 16:51:35 -0700613 __FUNCTION__, physicalId.c_str(), newHalStatus, logicalCameraStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800614 return;
615 }
616
617 bool updated = false;
618 if (newStatus == StatusInternal::PRESENT) {
619 updated = state->removeUnavailablePhysicalId(physicalId);
620 } else {
621 updated = state->addUnavailablePhysicalId(physicalId);
622 }
623
624 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700625 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800626 if (newStatus == StatusInternal::PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000627 logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800628 } else {
Henri Chataingbcb99452023-11-01 17:40:30 +0000629 logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800630 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700631 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
632 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
633 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700634 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700635 return;
636 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800637 Mutex::Autolock lock(mStatusListenerLock);
638 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700639 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
640 listener->getListenerPid(), listener->getListenerUid())) {
641 ALOGV("Skipping discovery callback for system-only camera device %s",
642 id.c_str());
643 continue;
644 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700645 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Biswarup Pal37a75182024-01-16 15:53:35 +0000646 mapToInterface(newStatus), id, physicalId, kDefaultDeviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700647 listener->handleBinderStatus(ret,
648 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
649 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
650 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800651 }
652 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700653}
654
Austin Borgered99f642023-06-01 16:51:35 -0700655void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800656 if (clientToDisconnect.get() != nullptr) {
657 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700658 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800659 // Notify the client of disconnection
660 clientToDisconnect->notifyError(
661 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
662 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800663 clientToDisconnect->disconnect();
664 }
665}
666
Austin Borgered99f642023-06-01 16:51:35 -0700667void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800668 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700669 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
670 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
671 if (res != OK) {
672 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700673 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700674 return;
675 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800676 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700677 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800678}
679
Austin Borgered99f642023-06-01 16:51:35 -0700680void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700681 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
682 Mutex::Autolock al(mTorchStatusMutex);
683 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
684}
685
Austin Borgered99f642023-06-01 16:51:35 -0700686void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800687 int32_t newStrengthLevel) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000688 // Get the device id and app-visible camera id for the given HAL-visible camera id.
689 auto [deviceId, mappedCameraId] =
690 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
691
Rucha Katakwar38284522021-11-10 11:25:21 -0800692 Mutex::Autolock lock(mStatusListenerLock);
693 for (auto& i : mListenerList) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000694 auto ret = i->getListener()->onTorchStrengthLevelChanged(mappedCameraId,
695 newStrengthLevel, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700696 i->handleBinderStatus(ret,
697 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
698 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800699 }
700}
701
Austin Borgered99f642023-06-01 16:51:35 -0700702void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700703 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800704 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700705 __FUNCTION__, cameraId.c_str(), newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800706
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800707 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800708 status_t res = getTorchStatusLocked(cameraId, &status);
709 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700710 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700711 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800712 return;
713 }
714 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800715 return;
716 }
717
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800718 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800719 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800720 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
721 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800722 return;
723 }
724
Ruben Brunkcc776712015-02-17 20:18:47 -0800725 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700726 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700727 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700728 auto iter = mTorchUidMap.find(cameraId);
729 if (iter != mTorchUidMap.end()) {
730 int oldUid = iter->second.second;
731 int newUid = iter->second.first;
732 BatteryNotifier& notifier(BatteryNotifier::getInstance());
733 if (oldUid != newUid) {
734 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800735 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700736 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700737 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800738 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700739 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700740 }
741 iter->second.second = newUid;
742 } else {
743 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800744 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700745 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700746 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700747 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700748 }
749 }
750 }
751 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700752 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800753}
754
Austin Borger249e6592024-03-10 22:28:11 -0700755bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700756 // Returns false if this is not an automotive device type.
757 if (!isAutomotiveDevice())
758 return false;
759
760 // Returns false if no camera id is provided.
Austin Borger1c1bee02023-06-01 16:51:35 -0700761 if (cam_id.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700762 return false;
763
764 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
765 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
766 // This isn't a known camera ID, so it's not a system camera.
767 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
768 return false;
769 }
770
771 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
772 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
773 return false;
774 }
775
776 CameraMetadata cameraInfo;
777 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borger1c1bee02023-06-01 16:51:35 -0700778 cam_id, false, &cameraInfo, false);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700779 if (res != OK){
780 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
781 cam_id.c_str());
782 return false;
783 }
784
785 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
786 if (auto_location.count != 1)
787 return false;
788
789 uint8_t location = auto_location.data.u8[0];
790 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
791 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
792 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
793 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
794 return false;
795 }
796
797 return true;
798}
799
Biswarup Pal37a75182024-01-16 15:53:35 +0000800Status CameraService::getNumberOfCameras(int32_t type, int32_t deviceId, int32_t devicePolicy,
801 int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700802 ATRACE_CALL();
Biswarup Pal37a75182024-01-16 15:53:35 +0000803 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
804 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
805 *numCameras = mVirtualDeviceCameraIdMapper.getNumberOfCameras(deviceId);
806 return Status::ok();
807 }
808
Emilian Peevaee727d2017-05-04 16:35:48 +0100809 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700810 bool hasSystemCameraPermissions =
Austin Borger22c5c852024-03-08 13:31:36 -0800811 hasPermissionsForSystemCamera(std::string(), getCallingPid(),
812 getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700813 switch (type) {
814 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700815 if (hasSystemCameraPermissions) {
816 *numCameras = static_cast<int>(mNormalDeviceIds.size());
817 } else {
818 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
819 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800820 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700821 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700822 if (hasSystemCameraPermissions) {
823 *numCameras = mNumberOfCameras;
824 } else {
825 *numCameras = mNumberOfCamerasWithoutSystemCamera;
826 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800827 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700828 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800829 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700830 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800831 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
832 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700833 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800834 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700835}
836
malikakash73125c62023-07-21 22:44:34 +0000837Status CameraService::remapCameraIds(const hardware::CameraIdRemapping& cameraIdRemapping) {
Austin Borgered99f642023-06-01 16:51:35 -0700838 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -0800839 const int pid = getCallingPid();
840 const int uid = getCallingUid();
malikakash82ed4352023-07-21 22:44:34 +0000841 ALOGE("%s: Permission Denial: can't configure camera ID mapping pid=%d, uid=%d",
842 __FUNCTION__, pid, uid);
843 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
844 "Permission Denial: no permission to configure camera id mapping");
845 }
846 TCameraIdRemapping cameraIdRemappingMap{};
malikakash214f6e62023-08-10 23:50:56 +0000847 binder::Status parseStatus = parseCameraIdRemapping(cameraIdRemapping, &cameraIdRemappingMap);
malikakash82ed4352023-07-21 22:44:34 +0000848 if (!parseStatus.isOk()) {
849 return parseStatus;
850 }
851 remapCameraIds(cameraIdRemappingMap);
852 return Status::ok();
853}
854
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700855Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
Biswarup Pal37a75182024-01-16 15:53:35 +0000856 int32_t deviceId, int32_t devicePolicy,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700857 /* out */
858 hardware::camera2::impl::CameraMetadataNative* request) {
859 ATRACE_CALL();
860
861 if (!flags::feature_combination_query()) {
862 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
863 "Camera subsystem doesn't support this method!");
864 }
865 if (!mInitialized) {
866 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
867 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
868 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
869 }
870
Biswarup Pal37a75182024-01-16 15:53:35 +0000871 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
872 devicePolicy, getCallingUid());
873 if (!cameraIdOptional.has_value()) {
874 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
875 unresolvedCameraId.c_str(), deviceId);
876 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
877 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
878 }
879 std::string cameraId = cameraIdOptional.value();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700880
881 binder::Status res;
882 if (request == nullptr) {
883 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
884 "Camera %s: Error creating default request", cameraId.c_str());
885 return res;
886 }
887 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
888 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
889 cameraId, templateId, &tempId);
890 if (!res.isOk()) {
891 ALOGE("%s: Camera %s: failed to map request Template %d",
892 __FUNCTION__, cameraId.c_str(), templateId);
893 return res;
894 }
895
896 if (shouldRejectSystemCameraConnection(cameraId)) {
897 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
898 "request for system only device %s: ", cameraId.c_str());
899 }
900
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700901 CameraMetadata metadata;
902 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
903 if (err == OK) {
904 request->swap(metadata);
905 } else if (err == BAD_VALUE) {
906 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
907 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
908 cameraId.c_str(), templateId, strerror(-err), err);
909 } else {
910 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
911 "Camera %s: Error creating default request for template %d: %s (%d)",
912 cameraId.c_str(), templateId, strerror(-err), err);
913 }
914 return res;
915}
916
917Status CameraService::isSessionConfigurationWithParametersSupported(
918 const std::string& unresolvedCameraId,
919 const SessionConfiguration& sessionConfiguration,
Biswarup Pal37a75182024-01-16 15:53:35 +0000920 int32_t deviceId, int32_t devicePolicy,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700921 /*out*/
922 bool* supported) {
923 ATRACE_CALL();
924
925 if (!flags::feature_combination_query()) {
926 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
927 "Camera subsystem doesn't support this method!");
928 }
929 if (!mInitialized) {
930 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
931 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
932 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
933 }
934
Biswarup Pal37a75182024-01-16 15:53:35 +0000935 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
936 devicePolicy, getCallingUid());
937 if (!cameraIdOptional.has_value()) {
938 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
939 unresolvedCameraId.c_str(), deviceId);
940 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
941 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
942 }
943 std::string cameraId = cameraIdOptional.value();
944
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700945 if (supported == nullptr) {
946 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
947 unresolvedCameraId.c_str());
948 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
949 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
950 }
951
952 if (shouldRejectSystemCameraConnection(cameraId)) {
953 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
954 "session configuration with parameters support for system only device %s: ",
955 cameraId.c_str());
956 }
957
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700958 return isSessionConfigurationWithParametersSupportedUnsafe(cameraId, sessionConfiguration,
959 /*overrideForPerfClass=*/false,
960 supported);
961}
962
963Status CameraService::isSessionConfigurationWithParametersSupportedUnsafe(
964 const std::string& cameraId, const SessionConfiguration& sessionConfiguration,
965 bool overrideForPerfClass, /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700966 *supported = false;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700967 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(
968 cameraId, sessionConfiguration, overrideForPerfClass,
969 /*checkSessionParams=*/true, supported);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700970 binder::Status res;
971 switch (ret) {
972 case OK:
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700973 // Expected. Do Nothing.
974 return Status::ok();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700975 case INVALID_OPERATION: {
976 std::string msg = fmt::sprintf(
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700977 "Camera %s: Session configuration with parameters supported query not "
978 "supported!",
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700979 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700980 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
981 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
982 *supported = false;
983 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700984 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700985 break;
986 case NAME_NOT_FOUND: {
987 std::string msg = fmt::sprintf("Camera %s: Unknown camera ID.", cameraId.c_str());
988 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
989 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
990 *supported = false;
991 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
992 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700993 break;
994 default: {
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700995 std::string msg = fmt::sprintf(
996 "Unable to retrieve session configuration support for camera "
997 "device %s: Error: %s (%d)",
998 cameraId.c_str(), strerror(-ret), ret);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700999 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001000 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1001 *supported = false;
1002 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001003 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001004 break;
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001005 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001006}
1007
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001008Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +00001009 int targetSdkVersion, bool overrideToPortrait,
1010 const SessionConfiguration& sessionConfiguration, int32_t deviceId, int32_t devicePolicy,
1011 /*out*/ CameraMetadata* outMetadata) {
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001012 ATRACE_CALL();
1013
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001014 if (outMetadata == nullptr) {
1015 std::string msg =
1016 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
1017 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1018 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1019 }
1020
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001021 if (!mInitialized) {
1022 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1023 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
1024 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
1025 }
1026
Biswarup Pal37a75182024-01-16 15:53:35 +00001027 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001028 devicePolicy, getCallingUid());
Biswarup Pal37a75182024-01-16 15:53:35 +00001029 if (!cameraIdOptional.has_value()) {
1030 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001031 unresolvedCameraId.c_str(), deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001032 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1033 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1034 }
1035 std::string cameraId = cameraIdOptional.value();
1036
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001037 if (shouldRejectSystemCameraConnection(cameraId)) {
1038 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1039 "Unable to retrieve camera"
1040 "characteristics for system only device %s: ",
1041 cameraId.c_str());
1042 }
1043
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001044 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1045 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001046 if (flags::check_session_support_before_session_char()) {
1047 bool sessionConfigSupported;
1048 Status res = isSessionConfigurationWithParametersSupportedUnsafe(
1049 cameraId, sessionConfiguration, overrideForPerfClass, &sessionConfigSupported);
1050 if (!res.isOk()) {
1051 // isSessionConfigurationWithParametersSupportedUnsafe should log what went wrong and
1052 // report the correct Status to send to the client. Simply forward the error to
1053 // the client.
1054 outMetadata->clear();
1055 return res;
1056 }
1057 if (!sessionConfigSupported) {
1058 std::string msg = fmt::sprintf(
1059 "Session configuration not supported for camera device %s.", cameraId.c_str());
1060 outMetadata->clear();
1061 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1062 }
1063 }
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001064
1065 status_t ret = mCameraProviderManager->getSessionCharacteristics(
1066 cameraId, sessionConfiguration, overrideForPerfClass, overrideToPortrait, outMetadata);
1067
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001068 switch (ret) {
1069 case OK:
1070 // Expected, no handling needed.
1071 break;
1072 case INVALID_OPERATION: {
1073 std::string msg = fmt::sprintf(
1074 "Camera %s: Session characteristics query not supported!",
1075 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001076 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001077 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1078 outMetadata->clear();
1079 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1080 }
1081 break;
1082 case NAME_NOT_FOUND: {
1083 std::string msg = fmt::sprintf(
1084 "Camera %s: Unknown camera ID.",
1085 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001086 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001087 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1088 outMetadata->clear();
1089 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001090 }
1091 break;
1092 default: {
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001093 std::string msg = fmt::sprintf(
1094 "Unable to retrieve session characteristics for camera device %s: "
1095 "Error: %s (%d)",
1096 cameraId.c_str(), strerror(-ret), ret);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001097 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001098 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1099 outMetadata->clear();
1100 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001101 }
1102 }
1103
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001104 return filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
1105}
1106
1107Status CameraService::filterSensitiveMetadataIfNeeded(
1108 const std::string& cameraId, CameraMetadata* metadata) {
1109 int callingPid = getCallingPid();
1110 int callingUid = getCallingUid();
1111
1112 if (callingPid == getpid()) {
1113 // Caller is cameraserver; no need to remove keys
1114 return Status::ok();
1115 }
1116
1117 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1118 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1119 ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
1120 metadata->clear();
1121 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1122 "Unable to retrieve camera kind for device %s", cameraId.c_str());
1123 }
1124 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
1125 // Attempting to query system only camera without system camera permission would have
1126 // failed the shouldRejectSystemCameraConnection in the caller. So if we get here
1127 // for a system only camera, then the caller has the required permission.
1128 // No need to remove keys
1129 return Status::ok();
1130 }
1131
1132 std::vector<int32_t> tagsRemoved;
1133 bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid);
1134 if (hasCameraPermission) {
1135 // Caller has camera permission; no need to remove keys
1136 return Status::ok();
1137 }
1138
1139 status_t ret = metadata->removePermissionEntries(
1140 mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1141 if (ret != OK) {
1142 metadata->clear();
1143 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1144 "Failed to remove camera characteristics needing camera permission "
1145 "for device %s:%s (%d)",
1146 cameraId.c_str(), strerror(-ret), ret);
1147 }
1148
1149 if (!tagsRemoved.empty()) {
1150 ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1151 tagsRemoved.data(), tagsRemoved.size());
1152 if (ret != OK) {
1153 metadata->clear();
1154 return STATUS_ERROR_FMT(
1155 ERROR_INVALID_OPERATION,
1156 "Failed to insert camera keys needing permission for device %s: %s (%d)",
1157 cameraId.c_str(), strerror(-ret), ret);
1158 }
1159 }
1160 return Status::ok();
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001161}
1162
malikakash82ed4352023-07-21 22:44:34 +00001163Status CameraService::parseCameraIdRemapping(
1164 const hardware::CameraIdRemapping& cameraIdRemapping,
malikakash214f6e62023-08-10 23:50:56 +00001165 /* out */ TCameraIdRemapping* cameraIdRemappingMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001166 std::string packageName;
1167 std::string cameraIdToReplace, updatedCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001168 for (const auto& packageIdRemapping: cameraIdRemapping.packageIdRemappings) {
malikakash82ed4352023-07-21 22:44:34 +00001169 packageName = packageIdRemapping.packageName;
malikakash0894f5b2023-08-10 22:46:47 +00001170 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001171 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1172 "CameraIdRemapping: Package name cannot be empty");
1173 }
malikakash214f6e62023-08-10 23:50:56 +00001174 if (packageIdRemapping.cameraIdsToReplace.size()
1175 != packageIdRemapping.updatedCameraIds.size()) {
malikakash82ed4352023-07-21 22:44:34 +00001176 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1177 "CameraIdRemapping: Mismatch in CameraId Remapping lists sizes for package %s",
malikakash73125c62023-07-21 22:44:34 +00001178 packageName.c_str());
malikakash82ed4352023-07-21 22:44:34 +00001179 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001180 for (size_t i = 0; i < packageIdRemapping.cameraIdsToReplace.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -07001181 cameraIdToReplace = packageIdRemapping.cameraIdsToReplace[i];
1182 updatedCameraId = packageIdRemapping.updatedCameraIds[i];
malikakash0894f5b2023-08-10 22:46:47 +00001183 if (cameraIdToReplace.empty() || updatedCameraId.empty()) {
malikakash214f6e62023-08-10 23:50:56 +00001184 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1185 "CameraIdRemapping: Camera Id cannot be empty for package %s",
Austin Borgered99f642023-06-01 16:51:35 -07001186 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001187 }
1188 if (cameraIdToReplace == updatedCameraId) {
1189 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1190 "CameraIdRemapping: CameraIdToReplace cannot be the same"
1191 " as updatedCameraId for %s",
Austin Borgered99f642023-06-01 16:51:35 -07001192 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001193 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001194
1195 // Do not allow any camera remapping that involves a virtual camera.
1196 auto [deviceIdForCameraToReplace, _] =
1197 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1198 cameraIdToReplace);
1199 if (deviceIdForCameraToReplace != kDefaultDeviceId) {
1200 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1201 "CameraIdRemapping: CameraIdToReplace cannot be a virtual camera");
1202 }
1203 [[maybe_unused]] auto [deviceIdForUpdatedCamera, unusedMappedCameraId] =
1204 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(updatedCameraId);
1205 if (deviceIdForUpdatedCamera != kDefaultDeviceId) {
1206 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1207 "CameraIdRemapping: UpdatedCameraId cannot be a virtual camera");
1208 }
1209
malikakash214f6e62023-08-10 23:50:56 +00001210 (*cameraIdRemappingMap)[packageName][cameraIdToReplace] = updatedCameraId;
malikakash82ed4352023-07-21 22:44:34 +00001211 }
1212 }
1213 return Status::ok();
1214}
1215
1216void CameraService::remapCameraIds(const TCameraIdRemapping& cameraIdRemapping) {
1217 // Acquire mServiceLock and prevent other clients from connecting
1218 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1219 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1220
malikakashedb38962023-09-06 00:03:35 +00001221 // Collect all existing clients for camera Ids that are being
1222 // remapped in the new cameraIdRemapping, but only if they were being used by a
1223 // targeted packageName.
malikakash82ed4352023-07-21 22:44:34 +00001224 std::vector<sp<BasicClient>> clientsToDisconnect;
Austin Borgered99f642023-06-01 16:51:35 -07001225 std::vector<std::string> cameraIdsToUpdate;
malikakash82ed4352023-07-21 22:44:34 +00001226 for (const auto& [packageName, injectionMap] : cameraIdRemapping) {
1227 for (auto& [id0, id1] : injectionMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001228 ALOGI("%s: UPDATE:= %s: %s: %s", __FUNCTION__, packageName.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001229 id0.c_str(), id1.c_str());
1230 auto clientDescriptor = mActiveClientManager.get(id0);
1231 if (clientDescriptor != nullptr) {
1232 sp<BasicClient> clientSp = clientDescriptor->getValue();
1233 if (clientSp->getPackageName() == packageName) {
malikakashedb38962023-09-06 00:03:35 +00001234 // This camera is being used by a targeted packageName and
1235 // being remapped to a new camera Id. We should disconnect it.
malikakash82ed4352023-07-21 22:44:34 +00001236 clientsToDisconnect.push_back(clientSp);
1237 cameraIdsToUpdate.push_back(id0);
1238 }
1239 }
1240 }
1241 }
1242
malikakashedb38962023-09-06 00:03:35 +00001243 for (auto& clientSp : clientsToDisconnect) {
malikakashf4c80f22023-09-25 21:50:28 +00001244 // Notify the clients about the disconnection.
1245 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
malikakashedb38962023-09-06 00:03:35 +00001246 CaptureResultExtras{});
1247 }
malikakash82ed4352023-07-21 22:44:34 +00001248
1249 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1250 // blocking other clients from connecting in mServiceLockWrapper if held.
1251 mServiceLock.unlock();
1252
malikakashedb38962023-09-06 00:03:35 +00001253 // Clear calling identity for disconnect() PID checks.
Austin Borger22c5c852024-03-08 13:31:36 -08001254 int64_t token = clearCallingIdentity();
malikakashedb38962023-09-06 00:03:35 +00001255
malikakash82ed4352023-07-21 22:44:34 +00001256 // Disconnect clients.
1257 for (auto& clientSp : clientsToDisconnect) {
malikakashedb38962023-09-06 00:03:35 +00001258 // This also triggers a call to updateStatus() which also reads mCameraIdRemapping
1259 // and requires mCameraIdRemappingLock.
malikakash82ed4352023-07-21 22:44:34 +00001260 clientSp->disconnect();
1261 }
1262
malikakashedb38962023-09-06 00:03:35 +00001263 // Invoke destructors (which call disconnect()) now while we don't hold the mServiceLock.
1264 clientsToDisconnect.clear();
1265
Austin Borger22c5c852024-03-08 13:31:36 -08001266 restoreCallingIdentity(token);
malikakash82ed4352023-07-21 22:44:34 +00001267 mServiceLock.lock();
malikakashedb38962023-09-06 00:03:35 +00001268
1269 {
1270 Mutex::Autolock lock(mCameraIdRemappingLock);
1271 // Update mCameraIdRemapping.
1272 mCameraIdRemapping.clear();
1273 mCameraIdRemapping.insert(cameraIdRemapping.begin(), cameraIdRemapping.end());
1274 }
malikakash82ed4352023-07-21 22:44:34 +00001275}
1276
malikakash22af94c2023-12-04 18:13:14 +00001277Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001278 const std::string& cameraId,
1279 const CameraMetadata& sessionParams) {
1280 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001281 const int pid = getCallingPid();
1282 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001283 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1284 __FUNCTION__, pid, uid);
1285 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1286 "Permission Denial: no permission to inject session params");
1287 }
1288
Biswarup Pal37a75182024-01-16 15:53:35 +00001289 // Do not allow session params injection for a virtual camera.
1290 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1291 if (deviceId != kDefaultDeviceId) {
1292 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1293 "Cannot inject session params for a virtual camera");
1294 }
1295
malikakash22af94c2023-12-04 18:13:14 +00001296 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1297 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1298
1299 auto clientDescriptor = mActiveClientManager.get(cameraId);
1300 if (clientDescriptor == nullptr) {
1301 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1302 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1303 "No active client for camera id %s", cameraId.c_str());
1304 }
1305
1306 sp<BasicClient> clientSp = clientDescriptor->getValue();
1307 status_t res = clientSp->injectSessionParams(sessionParams);
1308
1309 if (res != OK) {
1310 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1311 "Error injecting session params into camera \"%s\": %s (%d)",
1312 cameraId.c_str(), strerror(-res), res);
1313 }
1314 return Status::ok();
1315}
1316
Austin Borgered99f642023-06-01 16:51:35 -07001317std::vector<std::string> CameraService::findOriginalIdsForRemappedCameraId(
1318 const std::string& inputCameraId, int clientUid) {
1319 std::string packageName = getPackageNameFromUid(clientUid);
1320 std::vector<std::string> cameraIds;
malikakash82ed4352023-07-21 22:44:34 +00001321 Mutex::Autolock lock(mCameraIdRemappingLock);
1322 if (auto packageMapIter = mCameraIdRemapping.find(packageName);
1323 packageMapIter != mCameraIdRemapping.end()) {
1324 for (auto& [id0, id1]: packageMapIter->second) {
1325 if (id1 == inputCameraId) {
1326 cameraIds.push_back(id0);
1327 }
1328 }
1329 }
1330 return cameraIds;
1331}
1332
Austin Borgered99f642023-06-01 16:51:35 -07001333std::string CameraService::resolveCameraId(
1334 const std::string& inputCameraId,
malikakashedb38962023-09-06 00:03:35 +00001335 int clientUid,
Austin Borgered99f642023-06-01 16:51:35 -07001336 const std::string& packageName) {
1337 std::string packageNameVal = packageName;
malikakashedb38962023-09-06 00:03:35 +00001338 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001339 packageNameVal = getPackageNameFromUid(clientUid);
1340 }
malikakash65d20692023-09-07 01:06:33 +00001341 if (clientUid < AID_APP_START || packageNameVal.empty()) {
malikakashedb38962023-09-06 00:03:35 +00001342 // We shouldn't remap cameras for processes with system/vendor UIDs.
1343 return inputCameraId;
1344 }
malikakash82ed4352023-07-21 22:44:34 +00001345 Mutex::Autolock lock(mCameraIdRemappingLock);
1346 if (auto packageMapIter = mCameraIdRemapping.find(packageNameVal);
1347 packageMapIter != mCameraIdRemapping.end()) {
malikakash82ed4352023-07-21 22:44:34 +00001348 auto packageMap = packageMapIter->second;
1349 if (auto replacementIdIter = packageMap.find(inputCameraId);
1350 replacementIdIter != packageMap.end()) {
malikakashedb38962023-09-06 00:03:35 +00001351 ALOGI("%s: resolveCameraId: remapping cameraId %s for %s to %s",
malikakash82ed4352023-07-21 22:44:34 +00001352 __FUNCTION__, inputCameraId.c_str(),
malikakashedb38962023-09-06 00:03:35 +00001353 packageNameVal.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001354 replacementIdIter->second.c_str());
1355 return replacementIdIter->second;
1356 }
1357 }
1358 return inputCameraId;
1359}
1360
Biswarup Pal37a75182024-01-16 15:53:35 +00001361std::optional<std::string> CameraService::resolveCameraId(
1362 const std::string& inputCameraId,
1363 int32_t deviceId,
1364 int32_t devicePolicy,
1365 int clientUid,
1366 const std::string& packageName) {
1367 if ((deviceId == kDefaultDeviceId)
1368 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1369 auto [storedDeviceId, _] =
1370 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1371 if (storedDeviceId != kDefaultDeviceId) {
1372 // Trying to access a virtual camera from default-policy device context, we should fail.
1373 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1374 inputCameraId.c_str(), deviceId);
1375 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1376 return std::nullopt;
1377 }
1378 return resolveCameraId(inputCameraId, clientUid, packageName);
1379 }
1380
1381 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1382}
1383
1384Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait, int32_t deviceId,
1385 int32_t devicePolicy, CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001386 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001387 Mutex::Autolock l(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001388 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId, deviceId, devicePolicy);
1389 if (cameraIdStr.empty()) {
1390 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
1391 cameraId, deviceId);
1392 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1393 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1394 }
malikakashedb38962023-09-06 00:03:35 +00001395
Austin Borgered99f642023-06-01 16:51:35 -07001396 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001397 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1398 "characteristics for system only device %s: ", cameraIdStr.c_str());
1399 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001400
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001401 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001402 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001403 return STATUS_ERROR(ERROR_DISCONNECTED,
1404 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001405 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001406 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001407 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001408 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1409 if (hasSystemCameraPermissions) {
1410 cameraIdBound = mNumberOfCameras;
1411 }
1412 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001413 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1414 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001415 }
1416
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001417 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001418 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001419 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borgered99f642023-06-01 16:51:35 -07001420 cameraIdStr, overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001421 if (err != OK) {
1422 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1423 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1424 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001425 logServiceError(std::string("Error retrieving camera info from device ")
1426 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001427 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001428
Ruben Brunkcc776712015-02-17 20:18:47 -08001429 return ret;
1430}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001431
Biswarup Pal37a75182024-01-16 15:53:35 +00001432std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1433 int32_t deviceId, int32_t devicePolicy) {
1434 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1435 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1436 std::optional<std::string> cameraIdOptional =
1437 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1438 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1439 }
1440
1441 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001442 auto callingPid = getCallingPid();
1443 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001444 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1445 callingPid, callingUid, /* checkCameraPermissions= */ false);
1446 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001447 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001448 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001449 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1450 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1451 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001452 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001453 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001454
Biswarup Pal37a75182024-01-16 15:53:35 +00001455 std::string unresolvedCameraId = (*cameraIds)[cameraIdInt];
1456 return resolveCameraId(unresolvedCameraId, getCallingUid());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001457}
1458
Biswarup Pal37a75182024-01-16 15:53:35 +00001459std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1460 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001461 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001462 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001463}
1464
Austin Borgered99f642023-06-01 16:51:35 -07001465Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +00001466 int targetSdkVersion, bool overrideToPortrait, int32_t deviceId, int32_t devicePolicy,
1467 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001468 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001469
Zhijun He2b59be82013-09-25 10:14:30 -07001470 if (!cameraInfo) {
1471 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001472 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001473 }
1474
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001475 if (!mInitialized) {
1476 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001477 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001478 return STATUS_ERROR(ERROR_DISCONNECTED,
1479 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001480 }
1481
Biswarup Pal37a75182024-01-16 15:53:35 +00001482 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
1483 devicePolicy, getCallingUid());
1484 if (!cameraIdOptional.has_value()) {
1485 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1486 unresolvedCameraId.c_str(), deviceId);
1487 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1488 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1489 }
1490 std::string cameraId = cameraIdOptional.value();
1491
Austin Borgered99f642023-06-01 16:51:35 -07001492 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001493 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001494 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001495 }
1496
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001497 bool overrideForPerfClass =
1498 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001499 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001500 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borgered99f642023-06-01 16:51:35 -07001501 cameraId, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001502 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001503 if (res == NAME_NOT_FOUND) {
1504 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001505 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001506 strerror(-res), res);
1507 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001508 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1509 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001510 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001511 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001512 strerror(-res), res);
1513 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001514 }
Emilian Peeve20c6372018-08-14 18:45:53 +01001515
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001516 return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -07001517}
1518
Biswarup Pal37a75182024-01-16 15:53:35 +00001519Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId, int32_t deviceId,
1520 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001521 ATRACE_CALL();
1522 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001523
Biswarup Pal37a75182024-01-16 15:53:35 +00001524 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
1525 devicePolicy, getCallingUid());
1526 if (!cameraIdOptional.has_value()) {
1527 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1528 unresolvedCameraId.c_str(), deviceId);
1529 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1530 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1531 }
1532 std::string cameraId = cameraIdOptional.value();
1533
Rucha Katakwar38284522021-11-10 11:25:21 -08001534 if (!mInitialized) {
1535 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1536 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1537 }
1538
Biswarup Pal37a75182024-01-16 15:53:35 +00001539 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001540 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1541 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1542 }
1543
Austin Borgered99f642023-06-01 16:51:35 -07001544 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001545 if (res != OK) {
1546 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001547 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001548 strerror(-res), res);
1549 }
1550 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1551 return Status::ok();
1552}
1553
Austin Borgered99f642023-06-01 16:51:35 -07001554std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001555 time_t now = time(nullptr);
1556 char formattedTime[64];
1557 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001558 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001559}
1560
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001561Status CameraService::getCameraVendorTagDescriptor(
1562 /*out*/
1563 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001564 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001565 if (!mInitialized) {
1566 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001567 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001568 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001569 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1570 if (globalDescriptor != nullptr) {
1571 *desc = *(globalDescriptor.get());
1572 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001573 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001574}
1575
Emilian Peev71c73a22017-03-21 16:35:51 +00001576Status CameraService::getCameraVendorTagCache(
1577 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1578 ATRACE_CALL();
1579 if (!mInitialized) {
1580 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1581 return STATUS_ERROR(ERROR_DISCONNECTED,
1582 "Camera subsystem not available");
1583 }
1584 sp<VendorTagDescriptorCache> globalCache =
1585 VendorTagDescriptorCache::getGlobalVendorTagCache();
1586 if (globalCache != nullptr) {
1587 *cache = *(globalCache.get());
1588 }
1589 return Status::ok();
1590}
1591
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001592void CameraService::clearCachedVariables() {
1593 BasicClient::BasicClient::sCameraService = nullptr;
1594}
1595
Austin Borgered99f642023-06-01 16:51:35 -07001596std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001597 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001598 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001599
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001600 int deviceVersion = 0;
1601
Emilian Peevf53f66e2017-04-11 14:29:43 +01001602 status_t res;
1603 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001604 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001605 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001606 if (res != OK || transport == IPCTransport::INVALID) {
1607 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001608 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001609 return std::make_pair(-1, IPCTransport::INVALID) ;
1610 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001611 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001612
Emilian Peevf53f66e2017-04-11 14:29:43 +01001613 hardware::CameraInfo info;
1614 if (facing) {
Austin Borgered99f642023-06-01 16:51:35 -07001615 res = mCameraProviderManager->getCameraInfo(cameraId, overrideToPortrait,
Austin Borger18b30a72022-10-27 12:20:29 -07001616 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001617 if (res != OK) {
1618 return std::make_pair(-1, IPCTransport::INVALID);
1619 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001620 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001621 if (orientation) {
1622 *orientation = info.orientation;
1623 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001624 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001625
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001626 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001627}
1628
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001629Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001630 switch(err) {
1631 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001632 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001633 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001634 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1635 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001636 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001637 return STATUS_ERROR(ERROR_DISCONNECTED,
1638 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001639 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001640 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1641 "Camera HAL encountered error %d: %s",
1642 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001643 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001644}
1645
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001646Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001647 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1648 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001649 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001650 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001651 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
malikakash73125c62023-07-21 22:44:34 +00001652 bool forceSlowJpegMode, const std::string& originalCameraId,
1653 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001654 // For HIDL devices
1655 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1656 // Create CameraClient based on device version reported by the HAL.
1657 int deviceVersion = deviceVersionAndTransport.first;
1658 switch(deviceVersion) {
1659 case CAMERA_DEVICE_API_VERSION_1_0:
1660 ALOGE("Camera using old HAL version: %d", deviceVersion);
1661 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1662 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001663 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001664 break;
1665 case CAMERA_DEVICE_API_VERSION_3_0:
1666 case CAMERA_DEVICE_API_VERSION_3_1:
1667 case CAMERA_DEVICE_API_VERSION_3_2:
1668 case CAMERA_DEVICE_API_VERSION_3_3:
1669 case CAMERA_DEVICE_API_VERSION_3_4:
1670 case CAMERA_DEVICE_API_VERSION_3_5:
1671 case CAMERA_DEVICE_API_VERSION_3_6:
1672 case CAMERA_DEVICE_API_VERSION_3_7:
1673 break;
1674 default:
1675 // Should not be reachable
1676 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1677 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1678 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001679 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001680 }
1681 }
1682 if (effectiveApiLevel == API_1) { // Camera1 API route
1683 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001684 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001685 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001686 api1CameraId, facing, sensorOrientation,
Chengfei Taobe683db2023-01-31 18:52:49 +00001687 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait,
1688 forceSlowJpegMode);
1689 ALOGI("%s: Camera1 API (legacy), override to portrait %d, forceSlowJpegMode %d",
1690 __FUNCTION__, overrideToPortrait, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001691 } else { // Camera2 API route
1692 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1693 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001694 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001695 cameraService->mCameraServiceProxyWrapper,
1696 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001697 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
malikakash82ed4352023-07-21 22:44:34 +00001698 overrideForPerfClass, overrideToPortrait, originalCameraId);
Austin Borger18b30a72022-10-27 12:20:29 -07001699 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001700 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001701 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001702}
1703
Austin Borgered99f642023-06-01 16:51:35 -07001704std::string CameraService::toString(std::set<userid_t> intSet) {
1705 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001706 bool first = true;
1707 for (userid_t i : intSet) {
1708 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001709 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001710 first = false;
1711 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001712 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001713 }
1714 }
Austin Borgered99f642023-06-01 16:51:35 -07001715 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001716}
1717
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001718int32_t CameraService::mapToInterface(TorchModeStatus status) {
1719 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1720 switch (status) {
1721 case TorchModeStatus::NOT_AVAILABLE:
1722 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1723 break;
1724 case TorchModeStatus::AVAILABLE_OFF:
1725 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1726 break;
1727 case TorchModeStatus::AVAILABLE_ON:
1728 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1729 break;
1730 default:
1731 ALOGW("Unknown new flash status: %d", status);
1732 }
1733 return serviceStatus;
1734}
1735
1736CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1737 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1738 switch (status) {
1739 case CameraDeviceStatus::NOT_PRESENT:
1740 serviceStatus = StatusInternal::NOT_PRESENT;
1741 break;
1742 case CameraDeviceStatus::PRESENT:
1743 serviceStatus = StatusInternal::PRESENT;
1744 break;
1745 case CameraDeviceStatus::ENUMERATING:
1746 serviceStatus = StatusInternal::ENUMERATING;
1747 break;
1748 default:
1749 ALOGW("Unknown new HAL device status: %d", status);
1750 }
1751 return serviceStatus;
1752}
1753
1754int32_t CameraService::mapToInterface(StatusInternal status) {
1755 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1756 switch (status) {
1757 case StatusInternal::NOT_PRESENT:
1758 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1759 break;
1760 case StatusInternal::PRESENT:
1761 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1762 break;
1763 case StatusInternal::ENUMERATING:
1764 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1765 break;
1766 case StatusInternal::NOT_AVAILABLE:
1767 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1768 break;
1769 case StatusInternal::UNKNOWN:
1770 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1771 break;
1772 default:
1773 ALOGW("Unknown new internal device status: %d", status);
1774 }
1775 return serviceStatus;
1776}
1777
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001778Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001779 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001780
Austin Borgered99f642023-06-01 16:51:35 -07001781 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001782 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001783 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001784 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001785 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1786 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001787 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Chengfei Taobe683db2023-01-31 18:52:49 +00001788 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true,
Austin Borgered99f642023-06-01 16:51:35 -07001789 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001790 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001791 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001792 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001793 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001794}
1795
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001796Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001797 /*out*/
1798 CameraParameters* parameters) {
1799
1800 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1801
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001802 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001803
1804 if (parameters == NULL) {
1805 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001806 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001807 }
1808
malikakashedb38962023-09-06 00:03:35 +00001809 std::string unresolvedCameraId = std::to_string(cameraId);
1810 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08001811 getCallingUid());
Ruben Brunkcc776712015-02-17 20:18:47 -08001812
1813 // Check if we already have parameters
1814 {
1815 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001816 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001817 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001818 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001819 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001820 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001821 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001822 }
1823 CameraParameters p = cameraState->getShimParams();
1824 if (!p.isEmpty()) {
1825 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001826 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001827 }
1828 }
1829
Austin Borger22c5c852024-03-08 13:31:36 -08001830 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001831 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001832 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001833 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001834 // Error already logged by callee
1835 return ret;
1836 }
1837
1838 // Check for parameters again
1839 {
1840 // Scope for service lock
1841 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001842 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001843 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001844 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001845 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001846 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001847 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001848 CameraParameters p = cameraState->getShimParams();
1849 if (!p.isEmpty()) {
1850 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001851 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001852 }
1853 }
1854
Ruben Brunkcc776712015-02-17 20:18:47 -08001855 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1856 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001857 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001858}
1859
Austin Borgered99f642023-06-01 16:51:35 -07001860Status CameraService::validateConnectLocked(const std::string& cameraId,
1861 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001862 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001863
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001864#ifdef __BRILLO__
1865 UNUSED(clientName8);
1866 UNUSED(clientUid);
1867 UNUSED(clientPid);
1868 UNUSED(originalClientPid);
1869#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001870 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1871 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001872 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001873 return allowed;
1874 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001875#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001876
Austin Borger22c5c852024-03-08 13:31:36 -08001877 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001878
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001879 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001880 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1881 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001882 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001883 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001884 }
1885
Ruben Brunkcc776712015-02-17 20:18:47 -08001886 if (getCameraState(cameraId) == nullptr) {
1887 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001888 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001889 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001890 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001891 }
1892
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001893 status_t err = checkIfDeviceIsUsable(cameraId);
1894 if (err != NO_ERROR) {
1895 switch(err) {
1896 case -ENODEV:
1897 case -EBUSY:
1898 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001899 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001900 default:
1901 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001902 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001903 }
1904 }
1905 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001906}
1907
Austin Borgered99f642023-06-01 16:51:35 -07001908Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1909 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001910 /*out*/int& originalClientPid) const {
Austin Borger22c5c852024-03-08 13:31:36 -08001911 int callingPid = getCallingPid();
1912 int callingUid = getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001913
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001914 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001915 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001916 clientUid = callingUid;
1917 } else if (!isTrustedCallingUid(callingUid)) {
1918 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1919 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001920 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1921 "Untrusted caller (calling PID %d, UID %d) trying to "
1922 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001923 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001924 clientName.c_str(), clientPid, clientUid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001925 }
1926
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001927 // Check if we can trust clientPid
1928 if (clientPid == USE_CALLING_PID) {
1929 clientPid = callingPid;
1930 } else if (!isTrustedCallingUid(callingUid)) {
1931 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1932 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001933 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1934 "Untrusted caller (calling PID %d, UID %d) trying to "
1935 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001936 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001937 clientName.c_str(), clientPid, clientUid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001938 }
1939
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001940 if (shouldRejectSystemCameraConnection(cameraId)) {
1941 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1942 cameraId.c_str());
1943 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001944 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001945 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001946 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1947 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001948 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001949 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001950 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001951
1952 }
1953
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001954 // If it's not calling from cameraserver, check the permission if the
1955 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1956 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001957 bool checkPermissionForCamera =
1958 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001959 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001960 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001961 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001962 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1963 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001964 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001965 }
1966
Svet Ganova453d0d2018-01-11 15:37:58 -08001967 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001968 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001969 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001970 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1971 clientPid, clientUid);
1972 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001973 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1974 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001975 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001976 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001977 }
1978
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001979 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1980 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1981 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1982 if ((!isAutomotivePrivilegedClient(callingUid) ||
1983 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1984 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001985 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1986 return STATUS_ERROR_FMT(ERROR_DISABLED,
1987 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001988 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001989 }
1990
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001991 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1992 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001993 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001994 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001995
Ruben Brunk6267b532015-04-30 17:44:07 -07001996 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001997
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001998 // For non-system clients : Only allow clients who are being used by the current foreground
1999 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08002000 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08002001 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002002 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
2003 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07002004 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002005 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2006 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002007 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07002008 }
2009
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07002010 if (flags::camera_hsum_permission()) {
2011 // If the System User tries to access the camera when the device is running in
2012 // headless system user mode, ensure that client has the required permission
2013 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07002014 if (isHeadlessSystemUserMode()
2015 && (clientUserId == USER_SYSTEM)
2016 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07002017 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
2018 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2019 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
2020 User without camera headless system user permission",
Austin Borger249e6592024-03-10 22:28:11 -07002021 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07002022 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07002023 }
2024
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002025 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002026}
2027
Austin Borgered99f642023-06-01 16:51:35 -07002028status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08002029 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08002030 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08002031 if (cameraState == nullptr) {
2032 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07002033 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002034 return -ENODEV;
2035 }
2036
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002037 StatusInternal currentStatus = cameraState->getStatus();
2038 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002039 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07002040 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002041 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002042 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002043 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07002044 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002045 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07002046 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002047
Ruben Brunkcc776712015-02-17 20:18:47 -08002048 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08002049}
2050
Ruben Brunkcc776712015-02-17 20:18:47 -08002051void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002052 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08002053
Ruben Brunkcc776712015-02-17 20:18:47 -08002054 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002055 auto clientDescriptor =
2056 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002057 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08002058 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
2059
2060 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002061 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08002062
2063 if (evicted.size() > 0) {
2064 // This should never happen - clients should already have been removed in disconnect
2065 for (auto& i : evicted) {
2066 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07002067 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002068 }
2069
2070 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
2071 __FUNCTION__);
2072 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002073
2074 // And register a death notification for the client callback. Do
2075 // this last to avoid Binder policy where a nested Binder
2076 // transaction might be pre-empted to service the client death
2077 // notification if the client process dies before linkToDeath is
2078 // invoked.
2079 sp<IBinder> remoteCallback = client->getRemote();
2080 if (remoteCallback != nullptr) {
2081 remoteCallback->linkToDeath(this);
2082 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002083}
2084
Austin Borgered99f642023-06-01 16:51:35 -07002085status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
2086 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
2087 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08002088 /*out*/
2089 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07002090 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002091 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08002092 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002093 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08002094 DescriptorPtr clientDescriptor;
2095 {
2096 if (effectiveApiLevel == API_1) {
2097 // If we are using API1, any existing client for this camera ID with the same remote
2098 // should be returned rather than evicted to allow MediaRecorder to work properly.
2099
2100 auto current = mActiveClientManager.get(cameraId);
2101 if (current != nullptr) {
2102 auto clientSp = current->getValue();
2103 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002104 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07002105 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002106 " API level, evicting prior client...");
2107 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002108 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002109 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002110 *client = clientSp;
2111 return NO_ERROR;
2112 }
2113 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002114 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002115 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08002116
Ruben Brunkcc776712015-02-17 20:18:47 -08002117 // Get state for the given cameraId
2118 auto state = getCameraState(cameraId);
2119 if (state == nullptr) {
2120 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07002121 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002122 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07002123 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002124 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002125
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002126 sp<IServiceManager> sm = defaultServiceManager();
2127 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08002128 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002129 // If processinfo service is not available and the client is automotive privileged
2130 // client used for safety critical uses cases such as rear-view and surround-view which
2131 // needs to be available before android boot completes, then use the hardcoded values
2132 // for the process state and priority score. As this scenario is before android system
2133 // services are up and client is native client, hence using NATIVE_ADJ as the priority
2134 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
2135 // visible on the top.
2136 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2137 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2138 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
2139 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
2140 } else {
2141 // Get current active client PIDs
2142 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
2143 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002144
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002145 std::vector<int> priorityScores(ownerPids.size());
2146 std::vector<int> states(ownerPids.size());
2147
2148 // Get priority scores of all active PIDs
2149 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
2150 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
2151 if (err != OK) {
2152 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
2153 return err;
2154 }
2155
2156 // Update all active clients' priorities
2157 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
2158 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
2159 pidToPriorityMap.emplace(ownerPids[i],
2160 resource_policy::ClientPriority(priorityScores[i], states[i],
2161 /* isVendorClient won't get copied over*/ false,
2162 /* oomScoreOffset won't get copied over*/ 0));
2163 }
2164 mActiveClientManager.updatePriorities(pidToPriorityMap);
2165
2166 int32_t actualScore = priorityScores[priorityScores.size() - 1];
2167 int32_t actualState = states[states.size() - 1];
2168
2169 // Make descriptor for incoming client. We store the oomScoreOffset
2170 // since we might need it later on new handleEvictionsLocked and
2171 // ProcessInfoService would not take that into account.
2172 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2173 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2174 state->getConflicting(), actualScore, clientPid, actualState,
2175 oomScoreOffset, systemNativeClient);
2176 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002177
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002178 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
2179
Ruben Brunkcc776712015-02-17 20:18:47 -08002180 // Find clients that would be evicted
2181 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
2182
2183 // If the incoming client was 'evicted,' higher priority clients have the camera in the
2184 // background, so we cannot do evictions
2185 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2186 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2187 " priority).", clientPid);
2188
2189 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002190 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002191 auto incompatibleClients =
2192 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2193
Austin Borgered99f642023-06-01 16:51:35 -07002194 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2195 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2196 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002197 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002198
2199 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002200 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002201 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002202 i->getKey().c_str(),
2203 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002204 i->getOwnerId(), i->getPriority().getScore(),
2205 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002206 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002207 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2208 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002209 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002210 }
2211
2212 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002213 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002214 mEventLog.add(msg);
2215
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002216 auto current = mActiveClientManager.get(cameraId);
2217 if (current != nullptr) {
2218 return -EBUSY; // CAMERA_IN_USE
2219 } else {
2220 return -EUSERS; // MAX_CAMERAS_IN_USE
2221 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002222 }
2223
2224 for (auto& i : evicted) {
2225 sp<BasicClient> clientSp = i->getValue();
2226 if (clientSp.get() == nullptr) {
2227 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2228
2229 // TODO: Remove this
2230 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2231 __FUNCTION__);
2232 mActiveClientManager.remove(i);
2233 continue;
2234 }
2235
2236 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002237 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002238 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002239
Ruben Brunkcc776712015-02-17 20:18:47 -08002240 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002241 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002242 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2243 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002244 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002245 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002246 i->getPriority().getState(), cameraId.c_str(),
2247 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002248 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002249
2250 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002251 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002252 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002253 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002254 }
2255
Ruben Brunkcc776712015-02-17 20:18:47 -08002256 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2257 // other clients from connecting in mServiceLockWrapper if held
2258 mServiceLock.unlock();
2259
2260 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002261 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002262
2263 // Destroy evicted clients
2264 for (auto& i : evictedClients) {
2265 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002266 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002267 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002268
Austin Borger22c5c852024-03-08 13:31:36 -08002269 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002270
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002271 for (const auto& i : evictedClients) {
2272 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002273 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002274 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2275 if (ret == TIMED_OUT) {
2276 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002277 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2278 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002279 return -EBUSY;
2280 }
2281 if (ret != NO_ERROR) {
2282 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002283 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2284 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002285 return ret;
2286 }
2287 }
2288
2289 evictedClients.clear();
2290
Ruben Brunkcc776712015-02-17 20:18:47 -08002291 // Once clients have been disconnected, relock
2292 mServiceLock.lock();
2293
2294 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2295 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2296 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002297 }
2298
Ruben Brunkcc776712015-02-17 20:18:47 -08002299 *partial = clientDescriptor;
2300 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002301}
2302
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002303Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002304 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002305 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07002306 const std::string& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002307 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08002308 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002309 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07002310 bool overrideToPortrait,
Chengfei Taobe683db2023-01-31 18:52:49 +00002311 bool forceSlowJpegMode,
Biswarup Pal37a75182024-01-16 15:53:35 +00002312 int32_t deviceId,
2313 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002314 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002315 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002316 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002317 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002318
Biswarup Pal37a75182024-01-16 15:53:35 +00002319 std::string cameraIdStr = cameraIdIntToStr(api1CameraId, deviceId, devicePolicy);
2320 if (cameraIdStr.empty()) {
2321 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
2322 api1CameraId, deviceId);
2323 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2324 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2325 }
malikakashedb38962023-09-06 00:03:35 +00002326
Ruben Brunkcc776712015-02-17 20:18:47 -08002327 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002328 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
2329 clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002330 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002331 overrideToPortrait, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002332
Biswarup Pal37a75182024-01-16 15:53:35 +00002333 if (!ret.isOk()) {
2334 logRejected(cameraIdStr, getCallingPid(), clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002335 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002336 }
2337
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002338 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002339
2340 const sp<IServiceManager> sm(defaultServiceManager());
2341 const auto& mActivityManager = getActivityManager();
2342 if (mActivityManager) {
2343 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002344 getCallingUid(),
2345 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002346 }
2347
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002348 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002349}
2350
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002351bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2352 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002353 // If the client is not a vendor client, don't add listener if
2354 // a) the camera is a publicly hidden secure camera OR
2355 // b) the camera is a system only camera and the client doesn't
2356 // have android.permission.SYSTEM_CAMERA permissions.
2357 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2358 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002359 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002360 return true;
2361 }
2362 return false;
2363}
2364
Austin Borgered99f642023-06-01 16:51:35 -07002365bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002366 // Rules for rejection:
2367 // 1) If cameraserver tries to access this camera device, accept the
2368 // connection.
2369 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002370 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002371 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2372 // and the serving thread is a non hwbinder thread, the client must have
2373 // android.permission.SYSTEM_CAMERA permissions to connect.
2374
Austin Borger22c5c852024-03-08 13:31:36 -08002375 int cPid = getCallingPid();
2376 int cUid = getCallingUid();
2377 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002378 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2379 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002380 // This isn't a known camera ID, so it's not a system camera
2381 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2382 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002383 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002384
2385 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002386 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002387 return false;
2388 }
2389 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002390 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002391 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2392 return true;
2393 }
2394 // (3) Here we only check for permissions if it is a system only camera device. This is since
2395 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2396 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2397 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002398 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002399 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002400 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2401 cameraId.c_str());
2402 return true;
2403 }
2404
2405 return false;
2406}
2407
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002408Status CameraService::connectDevice(
2409 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002410 const std::string& unresolvedCameraId,
2411 const std::string& clientPackageName,
2412 const std::optional<std::string>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002413 int clientUid, int oomScoreOffset, int targetSdkVersion,
Biswarup Pal37a75182024-01-16 15:53:35 +00002414 bool overrideToPortrait, int32_t deviceId, int32_t devicePolicy,
Ruben Brunkcc776712015-02-17 20:18:47 -08002415 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002416 sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002417 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002418 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002419 sp<CameraDeviceClient> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002420 std::string clientPackageNameAdj = clientPackageName;
Austin Borger22c5c852024-03-08 13:31:36 -08002421 int callingPid = getCallingPid();
2422 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002423 bool systemNativeClient = false;
Austin Borger22c5c852024-03-08 13:31:36 -08002424 if (callerHasSystemUid() && (clientPackageNameAdj.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002425 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borgered99f642023-06-01 16:51:35 -07002426 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002427 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002428 }
Austin Borger249e6592024-03-10 22:28:11 -07002429
Biswarup Pal37a75182024-01-16 15:53:35 +00002430 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
2431 devicePolicy, callingUid, clientPackageNameAdj);
2432 if (!cameraIdOptional.has_value()) {
2433 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
2434 unresolvedCameraId.c_str(), deviceId);
2435 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2436 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2437 }
2438 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002439
2440 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002441 std::string msg =
2442 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
2443 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
2444 cameraId.c_str());
2445 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2446 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002447 }
2448
Austin Borger9bfa0a72022-08-03 17:50:40 -07002449 userid_t clientUserId = multiuser_get_user_id(clientUid);
Austin Borger9bfa0a72022-08-03 17:50:40 -07002450 if (clientUid == USE_CALLING_UID) {
2451 clientUserId = multiuser_get_user_id(callingUid);
2452 }
2453
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002454 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2455 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002456 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2457 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002458 std::string msg = "Camera disabled by device policy";
2459 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2460 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002461 }
2462
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002463 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002464 if (oomScoreOffset > 0
2465 && !hasPermissionsForSystemCamera(cameraId, callingPid,
Austin Borger249e6592024-03-10 22:28:11 -07002466 callingUid)
2467 && !isTrustedCallingUid(callingUid)) {
Austin Borgered99f642023-06-01 16:51:35 -07002468 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002469 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07002470 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2471 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2472 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002473 }
2474
Austin Borgered99f642023-06-01 16:51:35 -07002475 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
2476 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002477 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
malikakash73125c62023-07-21 22:44:34 +00002478 targetSdkVersion, overrideToPortrait, /*forceSlowJpegMode*/false, unresolvedCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002479 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002480
Biswarup Pal37a75182024-01-16 15:53:35 +00002481 if (!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002482 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002483 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002484 }
2485
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002486 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002487 Mutex::Autolock lock(mServiceLock);
2488
2489 // Clear the previous cached logs and reposition the
2490 // file offset to beginning of the file to log new data.
2491 // If either truncate or lseek fails, close the previous file and create a new one.
2492 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2493 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2494 // Close the previous memfd.
2495 close(mMemFd);
2496 // If failure to wipe the data, then create a new file and
2497 // assign the new value to mMemFd.
2498 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2499 if (mMemFd == -1) {
2500 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2501 }
2502 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002503 const sp<IServiceManager> sm(defaultServiceManager());
2504 const auto& mActivityManager = getActivityManager();
2505 if (mActivityManager) {
2506 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002507 callingUid,
2508 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002509 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002510 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002511}
2512
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002513bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2514 int callingPid, int callingUid) {
2515 if (!isAutomotiveDevice()) {
2516 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2517 }
2518
2519 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2520 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2521 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2522 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2523 "using camera %s", callingUid, cam_id.c_str());
2524 return false;
2525 }
2526
2527 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2528 return true;
2529 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2530 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002531 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2532 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002533 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2534 return false;
2535 } else {
2536 return true;
2537 }
2538 }
2539 return false;
2540}
2541
Austin Borgered99f642023-06-01 16:51:35 -07002542std::string CameraService::getPackageNameFromUid(int clientUid) {
2543 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002544
Avichal Rakesh5788fec2024-03-15 14:39:20 -07002545 sp<IPermissionController> permCtrl;
2546 if (flags::cache_permission_services()) {
2547 permCtrl = getPermissionController();
2548 } else {
2549 sp<IServiceManager> sm = defaultServiceManager();
2550#pragma clang diagnostic push
2551#pragma clang diagnostic ignored "-Wdeprecated-declarations"
2552 // Using deprecated function to preserve functionality until the
2553 // cache_permission_services flag is removed.
2554 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
2555#pragma clang diagnostic pop
2556 if (binder == 0) {
2557 ALOGE("Cannot get permission service");
2558 permCtrl = nullptr;
2559 } else {
2560 permCtrl = interface_cast<IPermissionController>(binder);
2561 }
2562 }
2563
2564 if (permCtrl == nullptr) {
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002565 // Return empty package name and the further interaction
2566 // with camera will likely fail
2567 return packageName;
2568 }
2569
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002570 Vector<String16> packages;
2571
2572 permCtrl->getPackagesForUid(clientUid, packages);
2573
2574 if (packages.isEmpty()) {
2575 ALOGE("No packages for calling UID %d", clientUid);
2576 // Return empty package name and the further interaction
2577 // with camera will likely fail
2578 return packageName;
2579 }
2580
2581 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002582 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002583
2584 return packageName;
2585}
2586
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002587template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002588Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2589 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2590 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002591 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002592 bool overrideToPortrait, bool forceSlowJpegMode, const std::string& originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002593 /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002594 binder::Status ret = binder::Status::ok();
2595
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002596 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002597 std::string clientPackageName;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002598 int packageUid = (clientUid == USE_CALLING_UID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002599 getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002600 if (clientPackageNameMaybe.size() <= 0) {
2601 // NDK calls don't come with package names, but we need one for various cases.
2602 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2603 // do exist. For all authentication cases, all packages under the same UID get the
2604 // same permissions, so picking any associated package name is sufficient. For some
2605 // other cases, this may give inaccurate names for clients in logs.
2606 isNonSystemNdk = true;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002607 clientPackageName = getPackageNameFromUid(packageUid);
2608 } else {
2609 clientPackageName = clientPackageNameMaybe;
2610 }
2611
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002612 int originalClientPid = 0;
2613
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002614 int packagePid = (clientPid == USE_CALLING_PID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002615 getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002616 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002617 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002618 static_cast<int>(effectiveApiLevel));
2619
Shuzhen Wang316781a2020-08-18 18:11:01 -07002620 nsecs_t openTimeNs = systemTime();
2621
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002622 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002623 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002624 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002625
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002626 {
2627 // Acquire mServiceLock and prevent other clients from connecting
2628 std::unique_ptr<AutoConditionLock> lock =
2629 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2630
2631 if (lock == nullptr) {
2632 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2633 , clientPid);
2634 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2635 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002636 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002637 }
2638
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002639 // Enforce client permissions and do basic validity checks
Biswarup Pal37a75182024-01-16 15:53:35 +00002640 if (!(ret = validateConnectLocked(cameraId, clientPackageName,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002641 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2642 return ret;
2643 }
2644
2645 // Check the shim parameters after acquiring lock, if they have already been updated and
2646 // we were doing a shim update, return immediately
2647 if (shimUpdateOnly) {
2648 auto cameraState = getCameraState(cameraId);
2649 if (cameraState != nullptr) {
2650 if (!cameraState->getShimParams().isEmpty()) return ret;
2651 }
2652 }
2653
2654 status_t err;
2655
2656 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002657 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002658 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002659 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2660 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002661 switch (err) {
2662 case -ENODEV:
2663 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2664 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002665 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002666 case -EBUSY:
2667 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2668 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002669 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002670 case -EUSERS:
2671 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2672 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002673 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002674 default:
2675 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2676 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002677 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002678 }
2679 }
2680
2681 if (clientTmp.get() != nullptr) {
2682 // Handle special case for API1 MediaRecorder where the existing client is returned
2683 device = static_cast<CLIENT*>(clientTmp.get());
2684 return ret;
2685 }
2686
2687 // give flashlight a chance to close devices if necessary.
2688 mFlashlight->prepareDeviceOpen(cameraId);
2689
Austin Borger18b30a72022-10-27 12:20:29 -07002690 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002691 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07002692 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
2693 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002694 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002695 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002696 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002697 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002698 }
2699
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002700 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002701 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002702 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002703 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002704 clientFeatureId, cameraId, api1CameraId, facing,
2705 orientation, clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002706 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
malikakash82ed4352023-07-21 22:44:34 +00002707 overrideToPortrait, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002708 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002709 return ret;
2710 }
2711 client = static_cast<CLIENT*>(tmp.get());
2712
2713 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2714 __FUNCTION__);
2715
Austin Borgered99f642023-06-01 16:51:35 -07002716 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002717 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002718 if (err != OK) {
2719 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002720 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002721 mServiceLock.unlock();
2722 client->disconnect();
2723 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002724 switch(err) {
2725 case BAD_VALUE:
2726 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002727 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002728 case -EBUSY:
2729 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002730 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002731 case -EUSERS:
2732 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2733 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002734 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002735 case PERMISSION_DENIED:
2736 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002737 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002738 case -EACCES:
2739 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002740 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002741 case -ENODEV:
2742 default:
2743 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002744 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002745 strerror(-err), err);
2746 }
2747 }
2748
2749 // Update shim paremeters for legacy clients
2750 if (effectiveApiLevel == API_1) {
2751 // Assume we have always received a Client subclass for API1
2752 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2753 String8 rawParams = shimClient->getParameters();
2754 CameraParameters params(rawParams);
2755
2756 auto cameraState = getCameraState(cameraId);
2757 if (cameraState != nullptr) {
2758 cameraState->setShimParams(params);
2759 } else {
2760 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002761 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002762 }
2763 }
2764
Ravneetaeb20dc2022-03-30 05:33:03 +00002765 // Enable/disable camera service watchdog
2766 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2767
Emilian Peev6d45db82024-01-18 20:11:54 +00002768 CameraMetadata chars;
2769 bool rotateAndCropSupported = true;
2770 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
2771 &chars, overrideToPortrait);
2772 if (err == OK) {
2773 auto availableRotateCropEntry = chars.find(
2774 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2775 if (availableRotateCropEntry.count <= 1) {
2776 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002777 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002778 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002779 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2780 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002781 }
2782
Emilian Peev6d45db82024-01-18 20:11:54 +00002783 if (rotateAndCropSupported) {
2784 // Set rotate-and-crop override behavior
2785 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2786 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
2787 } else if (overrideToPortrait && portraitRotation != 0) {
2788 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2789 switch (portraitRotation) {
2790 case 90:
2791 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2792 break;
2793 case 180:
2794 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2795 break;
2796 case 270:
2797 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2798 break;
2799 default:
2800 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2801 break;
2802 }
2803 client->setRotateAndCropOverride(rotateAndCropMode);
2804 } else {
2805 client->setRotateAndCropOverride(
2806 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2807 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2808 }
2809 }
2810
2811 bool autoframingSupported = true;
2812 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2813 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2814 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2815 autoframingSupported = false;
2816 }
2817
2818 if (autoframingSupported) {
2819 // Set autoframing override behaviour
2820 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2821 client->setAutoframingOverride(mOverrideAutoframingMode);
2822 } else {
2823 client->setAutoframingOverride(
2824 mCameraServiceProxyWrapper->getAutoframingOverride(
2825 clientPackageName));
2826 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002827 }
2828
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002829 bool isCameraPrivacyEnabled;
2830 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002831 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002832 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2833 toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2834 } else {
2835 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002836 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002837 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002838
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002839 if (client->supportsCameraMute()) {
2840 client->setCameraMute(
2841 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2842 } else if (isCameraPrivacyEnabled) {
2843 // no camera mute supported, but privacy is on! => disconnect
2844 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2845 client->getPackageName().c_str(), cameraId.c_str());
2846 // Do not hold mServiceLock while disconnecting clients, but
2847 // retain the condition blocking other clients from connecting
2848 // in mServiceLockWrapper if held.
2849 mServiceLock.unlock();
2850 // Clear caller identity temporarily so client disconnect PID
2851 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002852 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002853 // Note AppOp to trigger the "Unblock" dialog
2854 client->noteAppOp();
2855 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002856 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002857 // Reacquire mServiceLock
2858 mServiceLock.lock();
2859
2860 return STATUS_ERROR_FMT(ERROR_DISABLED,
2861 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002862 }
2863
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002864 if (shimUpdateOnly) {
2865 // If only updating legacy shim parameters, immediately disconnect client
2866 mServiceLock.unlock();
2867 client->disconnect();
2868 mServiceLock.lock();
2869 } else {
2870 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002871 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002872 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002873
2874 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002875 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002876 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002877 } // lock is destroyed, allow further connect calls
2878
2879 // Important: release the mutex here so the client can call back into the service from its
2880 // destructor (can be at the end of the call)
2881 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002882
2883 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002884 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002885 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002886
Cliff Wud3a05312021-04-26 23:07:31 +08002887 {
2888 Mutex::Autolock lock(mInjectionParametersLock);
2889 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2890 mInjectionInitPending = false;
2891 status_t res = NO_ERROR;
2892 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2893 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002894 sp<BasicClient> clientSp = clientDescriptor->getValue();
2895 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2896 if(res != OK) {
2897 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2898 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002899 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002900 }
2901 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002902 if (res != OK) {
2903 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2904 }
2905 } else {
2906 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002907 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002908 res = NO_INIT;
2909 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2910 }
2911 }
2912 }
2913
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002914 return ret;
2915}
2916
Austin Borgered99f642023-06-01 16:51:35 -07002917status_t CameraService::addOfflineClient(const std::string &cameraId,
2918 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002919 if (offlineClient.get() == nullptr) {
2920 return BAD_VALUE;
2921 }
2922
2923 {
2924 // Acquire mServiceLock and prevent other clients from connecting
2925 std::unique_ptr<AutoConditionLock> lock =
2926 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2927
2928 if (lock == nullptr) {
2929 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2930 , __FUNCTION__, offlineClient->getClientPid());
2931 return TIMED_OUT;
2932 }
2933
2934 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2935 if (onlineClientDesc.get() == nullptr) {
2936 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2937 cameraId.c_str());
2938 return BAD_VALUE;
2939 }
2940
2941 // Offline clients do not evict or conflict with other online devices. Resource sharing
2942 // conflicts are handled by the camera provider which will either succeed or fail before
2943 // reaching this method.
2944 const auto& onlinePriority = onlineClientDesc->getPriority();
2945 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2946 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002947 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002948 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002949 // native clients don't have offline processing support.
2950 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002951 if (offlineClientDesc == nullptr) {
2952 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2953 return BAD_VALUE;
2954 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002955
2956 // Allow only one offline device per camera
2957 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2958 if (!incompatibleClients.empty()) {
2959 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2960 return BAD_VALUE;
2961 }
2962
Austin Borgered99f642023-06-01 16:51:35 -07002963 std::string monitorTags = isClientWatched(offlineClient.get())
2964 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002965 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002966 if (err != OK) {
2967 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2968 return err;
2969 }
2970
2971 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2972 if (evicted.size() > 0) {
2973 for (auto& i : evicted) {
2974 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002975 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002976 }
2977
2978 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2979 "properly", __FUNCTION__);
2980
2981 return BAD_VALUE;
2982 }
2983
2984 logConnectedOffline(offlineClientDesc->getKey(),
2985 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002986 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002987
2988 sp<IBinder> remoteCallback = offlineClient->getRemote();
2989 if (remoteCallback != nullptr) {
2990 remoteCallback->linkToDeath(this);
2991 }
2992 } // lock is destroyed, allow further connect calls
2993
2994 return OK;
2995}
2996
Austin Borgered99f642023-06-01 16:51:35 -07002997Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +00002998 int32_t torchStrength, const sp<IBinder>& clientBinder, int32_t deviceId,
2999 int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08003000 Mutex::Autolock lock(mServiceLock);
3001
3002 ATRACE_CALL();
3003 if (clientBinder == nullptr) {
3004 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
3005 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
3006 "Torch client binder in null.");
3007 }
3008
Austin Borger22c5c852024-03-08 13:31:36 -08003009 int uid = getCallingUid();
Biswarup Pal37a75182024-01-16 15:53:35 +00003010 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
3011 devicePolicy, uid);
3012 if (!cameraIdOptional.has_value()) {
3013 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
3014 unresolvedCameraId.c_str(), deviceId);
3015 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3016 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3017 }
3018 std::string cameraId = cameraIdOptional.value();
3019
Austin Borgered99f642023-06-01 16:51:35 -07003020 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08003021 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07003022 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003023 }
3024
3025 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07003026 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08003027 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07003028 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003029 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003030 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003031 }
3032
3033 StatusInternal cameraStatus = state->getStatus();
3034 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
3035 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07003036 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08003037 (int)cameraStatus);
3038 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003039 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003040 }
3041
3042 {
3043 Mutex::Autolock al(mTorchStatusMutex);
3044 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003045 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08003046 if (err != OK) {
3047 if (err == NAME_NOT_FOUND) {
3048 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003049 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003050 }
3051 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003052 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003053 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
3054 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003055 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08003056 }
3057
3058 if (status == TorchModeStatus::NOT_AVAILABLE) {
3059 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
3060 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003061 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003062 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3063 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003064 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003065 } else {
3066 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003067 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003068 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3069 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003070 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003071 }
3072 }
3073 }
3074
3075 {
3076 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003077 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08003078 }
3079 // Check if the current torch strength level is same as the new one.
3080 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07003081 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003082
Austin Borgered99f642023-06-01 16:51:35 -07003083 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003084
3085 if (err != OK) {
3086 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003087 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08003088 switch (err) {
3089 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003090 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
3091 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003092 errorCode = ERROR_ILLEGAL_ARGUMENT;
3093 break;
3094 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003095 msg = fmt::sprintf("Camera \"%s\" is in use",
3096 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003097 errorCode = ERROR_CAMERA_IN_USE;
3098 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08003099 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07003100 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08003101 "valid range.", torchStrength);
3102 errorCode = ERROR_ILLEGAL_ARGUMENT;
3103 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08003104 default:
Austin Borgered99f642023-06-01 16:51:35 -07003105 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08003106 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08003107 }
Austin Borgered99f642023-06-01 16:51:35 -07003108 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3109 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003110 }
3111
3112 {
3113 // update the link to client's death
3114 // Store the last client that turns on each camera's torch mode.
3115 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003116 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08003117 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003118 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08003119 } else {
3120 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
3121 mTorchClientMap.replaceValueAt(index, clientBinder);
3122 }
3123 clientBinder->linkToDeath(this);
3124 }
3125
Austin Borger22c5c852024-03-08 13:31:36 -08003126 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08003127 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07003128 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08003129 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07003130 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003131 }
3132 return Status::ok();
3133}
3134
malikakash73125c62023-07-21 22:44:34 +00003135Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Biswarup Pal37a75182024-01-16 15:53:35 +00003136 const sp<IBinder>& clientBinder, int32_t deviceId, int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003137 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003138
3139 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07003140 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003141 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003142 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
3143 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003144 }
3145
Austin Borger22c5c852024-03-08 13:31:36 -08003146 int uid = getCallingUid();
Biswarup Pal37a75182024-01-16 15:53:35 +00003147 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
3148 devicePolicy, uid);
3149 if (!cameraIdOptional.has_value()) {
3150 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
3151 unresolvedCameraId.c_str(), deviceId);
3152 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3153 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3154 }
3155 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003156
Austin Borgered99f642023-06-01 16:51:35 -07003157 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003158 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07003159 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003160 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003161 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07003162 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003163 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07003164 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003165 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003166 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003167 }
3168
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003169 StatusInternal cameraStatus = state->getStatus();
3170 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003171 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07003172 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
3173 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003174 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003175 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003176 }
3177
3178 {
3179 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003180 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003181 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003182 if (err != OK) {
3183 if (err == NAME_NOT_FOUND) {
3184 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003185 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003186 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003187 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003188 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003189 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07003190 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003191 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003192 }
3193
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003194 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003195 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003196 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003197 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003198 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3199 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003200 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003201 } else {
3202 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003203 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003204 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3205 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003206 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003207 }
3208 }
3209 }
3210
Ruben Brunk99e69712015-05-26 17:25:07 -07003211 {
3212 // Update UID map - this is used in the torch status changed callbacks, so must be done
3213 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003214 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003215 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003216 }
3217
Austin Borgered99f642023-06-01 16:51:35 -07003218 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003219
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003220 if (err != OK) {
3221 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003222 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003223 switch (err) {
3224 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003225 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3226 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003227 errorCode = ERROR_ILLEGAL_ARGUMENT;
3228 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003229 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003230 msg = fmt::sprintf("Camera \"%s\" is in use",
3231 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003232 errorCode = ERROR_CAMERA_IN_USE;
3233 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003234 default:
Austin Borgered99f642023-06-01 16:51:35 -07003235 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003236 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003237 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003238 errorCode = ERROR_INVALID_OPERATION;
3239 }
Austin Borgered99f642023-06-01 16:51:35 -07003240 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3241 logServiceError(msg, errorCode);
3242 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003243 }
3244
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003245 {
3246 // update the link to client's death
3247 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003248 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003249 if (enabled) {
3250 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003251 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003252 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003253 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003254 mTorchClientMap.replaceValueAt(index, clientBinder);
3255 }
3256 clientBinder->linkToDeath(this);
3257 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003258 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003259 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003260 }
3261
Austin Borger22c5c852024-03-08 13:31:36 -08003262 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003263 std::string torchState = enabled ? "on" : "off";
3264 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3265 torchState.c_str(), clientPid);
3266 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003267 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003268}
3269
Austin Borgered99f642023-06-01 16:51:35 -07003270void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3271 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3272 mTorchUidMap[cameraId].first = uid;
3273 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003274 } else {
3275 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003276 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003277 }
3278}
3279
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003280Status CameraService::notifySystemEvent(int32_t eventId,
3281 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003282 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003283 const int selfPid = getpid();
3284
3285 // Permission checks
3286 if (pid != selfPid) {
3287 // Ensure we're being called by system_server, or similar process with
3288 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003289 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003290 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003291 ALOGE("Permission Denial: cannot send updates to camera service about system"
3292 " events from pid=%d, uid=%d", pid, uid);
3293 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003294 "No permission to send updates to camera service about system events"
3295 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003296 }
3297 }
3298
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003299 ATRACE_CALL();
3300
Ruben Brunk36597b22015-03-20 22:15:57 -07003301 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003302 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003303 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003304 // from a system server crash
3305 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003306 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003307 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003308 break;
3309 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003310 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3311 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003312 if (args.size() != 1) {
3313 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3314 "USB Device Event requires 1 argument");
3315 }
3316
Valentin Iftime29e2e152021-08-13 15:17:33 +02003317 // Notify CameraProviderManager for lazy HALs
3318 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3319 std::to_string(args[0]));
3320 break;
3321 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003322 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003323 default: {
3324 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3325 eventId);
3326 break;
3327 }
3328 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003329 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003330}
3331
Emilian Peev53722fa2019-02-22 17:47:20 -08003332void CameraService::notifyMonitoredUids() {
3333 Mutex::Autolock lock(mStatusListenerLock);
3334
3335 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003336 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003337 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3338 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003339 }
3340}
3341
Austin Borgerdddb7552023-03-30 17:53:01 -07003342void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3343 Mutex::Autolock lock(mStatusListenerLock);
3344
3345 for (const auto& it : mListenerList) {
3346 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3347 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3348 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3349 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3350 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3351 }
3352 }
3353}
3354
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003355Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003356 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003357 const int selfPid = getpid();
3358
3359 // Permission checks
3360 if (pid != selfPid) {
3361 // Ensure we're being called by system_server, or similar process with
3362 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003363 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003364 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003365 ALOGE("Permission Denial: cannot send updates to camera service about device"
3366 " state changes from pid=%d, uid=%d", pid, uid);
3367 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3368 "No permission to send updates to camera service about device state"
3369 " changes from pid=%d, uid=%d", pid, uid);
3370 }
3371 }
3372
3373 ATRACE_CALL();
3374
Austin Borger18b30a72022-10-27 12:20:29 -07003375 {
3376 Mutex::Autolock lock(mServiceLock);
3377 mDeviceState = newState;
3378 }
3379
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003380 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003381
3382 return Status::ok();
3383}
3384
Emilian Peev8b64f282021-03-25 16:49:57 -07003385Status CameraService::notifyDisplayConfigurationChange() {
3386 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003387 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003388 const int selfPid = getpid();
3389
3390 // Permission checks
3391 if (callingPid != selfPid) {
3392 // Ensure we're being called by system_server, or similar process with
3393 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003394 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003395 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003396 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3397 " changes from pid=%d, uid=%d", callingPid, uid);
3398 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3399 "No permission to send updates to camera service about orientation"
3400 " changes from pid=%d, uid=%d", callingPid, uid);
3401 }
3402 }
3403
3404 Mutex::Autolock lock(mServiceLock);
3405
3406 // Don't do anything if rotate-and-crop override via cmd is active
3407 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3408
3409 const auto clients = mActiveClientManager.getAll();
3410 for (auto& current : clients) {
3411 if (current != nullptr) {
3412 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003413 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3414 basicClient->setRotateAndCropOverride(
3415 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3416 basicClient->getPackageName(),
3417 basicClient->getCameraFacing(),
3418 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003419 }
3420 }
3421 }
3422
3423 return Status::ok();
3424}
3425
Biswarup Pal37a75182024-01-16 15:53:35 +00003426// TODO(b/291736219): This to be made device-aware.
Emilian Peev8b64f282021-03-25 16:49:57 -07003427Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003428 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3429 ATRACE_CALL();
3430 if (!concurrentCameraIds) {
3431 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3432 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3433 }
3434
3435 if (!mInitialized) {
3436 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003437 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003438 return STATUS_ERROR(ERROR_DISCONNECTED,
3439 "Camera subsystem is not available");
3440 }
3441 // First call into the provider and get the set of concurrent camera
3442 // combinations
3443 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003444 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003445 for (auto &combination : concurrentCameraCombinations) {
3446 std::vector<std::string> validCombination;
3447 for (auto &cameraId : combination) {
3448 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003449 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003450 if (state == nullptr) {
3451 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3452 continue;
3453 }
3454 StatusInternal status = state->getStatus();
3455 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3456 continue;
3457 }
Austin Borgered99f642023-06-01 16:51:35 -07003458 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003459 continue;
3460 }
3461 validCombination.push_back(cameraId);
3462 }
3463 if (validCombination.size() != 0) {
3464 concurrentCameraIds->push_back(std::move(validCombination));
3465 }
3466 }
3467 return Status::ok();
3468}
3469
3470Status CameraService::isConcurrentSessionConfigurationSupported(
3471 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003472 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003473 if (!isSupported) {
3474 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3475 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3476 }
3477
3478 if (!mInitialized) {
3479 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3480 return STATUS_ERROR(ERROR_DISCONNECTED,
3481 "Camera subsystem is not available");
3482 }
3483
3484 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003485 int callingPid = getCallingPid();
3486 int callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003487 bool hasCameraPermission = ((callingPid == getpid()) ||
3488 hasPermissionsForCamera(callingPid, callingUid));
3489 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003490 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3491 "android.permission.CAMERA needed to call"
3492 "isConcurrentSessionConfigurationSupported");
3493 }
3494
3495 status_t res =
3496 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003497 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3498 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003499 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003500 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003501 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003502 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3503 "support %s (%d)", strerror(-res), res);
3504 }
3505 return Status::ok();
3506}
3507
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003508Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3509 /*out*/
3510 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003511 return addListenerHelper(listener, cameraStatuses);
3512}
3513
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003514binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3515 std::vector<hardware::CameraStatus>* cameraStatuses) {
3516 return addListenerHelper(listener, cameraStatuses, false, true);
3517}
3518
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003519Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3520 /*out*/
3521 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003522 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003523 ATRACE_CALL();
3524
Igor Murashkinbfc99152013-02-27 12:55:20 -08003525 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003526
Ruben Brunk3450ba72015-06-16 11:00:37 -07003527 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003528 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003529 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003530 }
3531
Austin Borger22c5c852024-03-08 13:31:36 -08003532 auto clientPid = getCallingPid();
3533 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003534 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003535
Igor Murashkinbfc99152013-02-27 12:55:20 -08003536 Mutex::Autolock lock(mServiceLock);
3537
Ruben Brunkcc776712015-02-17 20:18:47 -08003538 {
3539 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003540 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003541 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003542 ALOGW("%s: Tried to add listener %p which was already subscribed",
3543 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003544 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003545 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003546 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003547
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003548 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003549 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3550 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003551 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003552 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003553 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003554 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003555 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3556 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3557 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003558 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003559 // The listener still needs to be added to the list of listeners, regardless of what
3560 // permissions the listener process has / whether it is a vendor listener. Since it might be
3561 // eligible to listen to other camera ids.
3562 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003563 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003564 }
3565
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003566 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003567 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003568 Mutex::Autolock lock(mCameraStatesLock);
3569 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003570 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3571 auto [deviceId, mappedCameraId] =
3572 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3573
3574 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003575 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003576 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3577 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003578 }
3579 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003580 // Remove the camera statuses that should be hidden from the client, we do
3581 // this after collecting the states in order to avoid holding
3582 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3583 // the same time.
3584 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3585 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003586 std::string cameraId = s.cameraId;
3587 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
3588 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM,
3589 clientUid);
3590 if (!cameraIdOptional.has_value()) {
3591 std::string msg =
3592 fmt::sprintf(
3593 "Camera %s: Invalid camera id for device id %d",
3594 s.cameraId.c_str(), s.deviceId);
3595 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3596 return true;
3597 }
3598 cameraId = cameraIdOptional.value();
3599 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3600 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3601 ALOGE("%s: Invalid camera id %s, skipping status update",
3602 __FUNCTION__, s.cameraId.c_str());
3603 return true;
3604 }
3605 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3606 clientUid);
3607 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003608
Biswarup Pal37a75182024-01-16 15:53:35 +00003609 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003610 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003611 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003612 // Add only default device cameras here, as virtual cameras currently don't support torch
3613 // anyway. Note that this is a simplification of the implementation here, and we should
3614 // change this when virtual cameras support torch.
3615 if (s.deviceId == kDefaultDeviceId) {
3616 idsChosenForCallback.insert(s.cameraId);
3617 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003618 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003619
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003620 /*
3621 * Immediately signal current torch status to this listener only
3622 * This may be a subset of all the devices, so don't include it in the response directly
3623 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003624 {
3625 Mutex::Autolock al(mTorchStatusMutex);
3626 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003627 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003628 // The camera id is visible to the client. Fine to send torch
3629 // callback.
3630 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003631 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3632 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003633 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003634 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003635 }
3636
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003637 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003638}
Ruben Brunkcc776712015-02-17 20:18:47 -08003639
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003640Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003641 ATRACE_CALL();
3642
Igor Murashkinbfc99152013-02-27 12:55:20 -08003643 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3644
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003645 if (listener == 0) {
3646 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003647 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003648 }
3649
Igor Murashkinbfc99152013-02-27 12:55:20 -08003650 Mutex::Autolock lock(mServiceLock);
3651
Ruben Brunkcc776712015-02-17 20:18:47 -08003652 {
3653 Mutex::Autolock lock(mStatusListenerLock);
3654 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003655 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003656 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003657 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003658 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003659 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003660 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003661 }
3662 }
3663
3664 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3665 __FUNCTION__, listener.get());
3666
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003667 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003668}
3669
Austin Borgered99f642023-06-01 16:51:35 -07003670Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003671
3672 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003673 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3674
3675 if (parameters == NULL) {
3676 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003677 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003678 }
3679
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003680 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003681
3682 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003683 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003684 // Error logged by caller
3685 return ret;
3686 }
3687
3688 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003689
Austin Borgered99f642023-06-01 16:51:35 -07003690 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003691
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003692 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003693}
3694
Austin Borgered99f642023-06-01 16:51:35 -07003695Status CameraService::supportsCameraApi(const std::string& unresolvedCameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003696 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003697 ATRACE_CALL();
3698
malikakashedb38962023-09-06 00:03:35 +00003699 const std::string cameraId = resolveCameraId(
Austin Borger22c5c852024-03-08 13:31:36 -08003700 unresolvedCameraId, getCallingUid());
malikakash82ed4352023-07-21 22:44:34 +00003701
Austin Borgered99f642023-06-01 16:51:35 -07003702 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003703
3704 switch (apiVersion) {
3705 case API_VERSION_1:
3706 case API_VERSION_2:
3707 break;
3708 default:
Austin Borgered99f642023-06-01 16:51:35 -07003709 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3710 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3711 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003712 }
3713
Austin Borger18b30a72022-10-27 12:20:29 -07003714 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -07003715 auto deviceVersionAndTransport = getDeviceVersion(cameraId, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003716 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003717 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3718 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3719 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003720 }
3721 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3722 int deviceVersion = deviceVersionAndTransport.first;
3723 switch (deviceVersion) {
3724 case CAMERA_DEVICE_API_VERSION_1_0:
3725 case CAMERA_DEVICE_API_VERSION_3_0:
3726 case CAMERA_DEVICE_API_VERSION_3_1:
3727 if (apiVersion == API_VERSION_2) {
3728 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003729 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003730 *isSupported = false;
3731 } else { // if (apiVersion == API_VERSION_1) {
3732 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003733 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003734 *isSupported = true;
3735 }
3736 break;
3737 case CAMERA_DEVICE_API_VERSION_3_2:
3738 case CAMERA_DEVICE_API_VERSION_3_3:
3739 case CAMERA_DEVICE_API_VERSION_3_4:
3740 case CAMERA_DEVICE_API_VERSION_3_5:
3741 case CAMERA_DEVICE_API_VERSION_3_6:
3742 case CAMERA_DEVICE_API_VERSION_3_7:
3743 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003744 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003745 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003746 break;
3747 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003748 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3749 deviceVersion, cameraId.c_str());
3750 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3751 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003752 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003753 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003754 } else {
3755 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003756 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003757 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003758}
3759
Austin Borgered99f642023-06-01 16:51:35 -07003760Status CameraService::isHiddenPhysicalCamera(const std::string& unresolvedCameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003761 /*out*/ bool *isSupported) {
3762 ATRACE_CALL();
3763
malikakashedb38962023-09-06 00:03:35 +00003764 const std::string cameraId = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08003765 getCallingUid());
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003766
Austin Borgered99f642023-06-01 16:51:35 -07003767 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3768 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003769
3770 return Status::ok();
3771}
3772
Cliff Wud8cae102021-03-11 01:37:42 +08003773Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003774 const std::string& packageName, const std::string& internalCamId,
3775 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003776 const sp<ICameraInjectionCallback>& callback,
3777 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003778 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003779 ATRACE_CALL();
3780
Austin Borgered99f642023-06-01 16:51:35 -07003781 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003782 const int pid = getCallingPid();
3783 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003784 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3785 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003786 "Permission Denial: no permission to inject camera");
3787 }
3788
3789 // Do not allow any camera injection that injects or replaces a virtual camera.
3790 auto [deviceIdForInternalCamera, _] =
3791 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3792 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3793 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3794 "Cannot replace a virtual camera");
3795 }
3796 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3797 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3798 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3799 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3800 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003801 }
3802
3803 ALOGV(
3804 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3805 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003806 __FUNCTION__, packageName.c_str(),
3807 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003808
Cliff Wud3a05312021-04-26 23:07:31 +08003809 {
3810 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003811 mInjectionInternalCamId = internalCamId;
3812 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003813 mInjectionStatusListener->addListener(callback);
3814 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003815 status_t res = NO_ERROR;
3816 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3817 // If the client already exists, we can directly connect to the camera device through the
3818 // client's injectCamera(), otherwise we need to wait until the client is established
3819 // (execute connectHelper()) before injecting the camera to the camera device.
3820 if (clientDescriptor != nullptr) {
3821 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003822 sp<BasicClient> clientSp = clientDescriptor->getValue();
3823 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3824 if(res != OK) {
3825 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3826 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003827 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003828 }
3829 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003830 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003831 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3832 }
3833 } else {
3834 mInjectionInitPending = true;
3835 }
3836 }
Cliff Wud8cae102021-03-11 01:37:42 +08003837
Cliff Wud3a05312021-04-26 23:07:31 +08003838 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003839}
3840
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003841Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003842 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003843 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3844 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3845 return Status::ok();
3846}
3847
Ruben Brunkcc776712015-02-17 20:18:47 -08003848void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003849 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003850 for (auto& i : mActiveClientManager.getAll()) {
3851 auto clientSp = i->getValue();
3852 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003853 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003854 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003855 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003856 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003857 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003858}
3859
Ruben Brunkcc776712015-02-17 20:18:47 -08003860bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003861 bool ret = false;
3862 {
3863 // Acquire mServiceLock and prevent other clients from connecting
3864 std::unique_ptr<AutoConditionLock> lock =
3865 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003866
Ruben Brunkcc776712015-02-17 20:18:47 -08003867 std::vector<sp<BasicClient>> evicted;
3868 for (auto& i : mActiveClientManager.getAll()) {
3869 auto clientSp = i->getValue();
3870 if (clientSp.get() == nullptr) {
3871 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3872 mActiveClientManager.remove(i);
3873 continue;
3874 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003875 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003876 mActiveClientManager.remove(i);
3877 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003878
Ruben Brunkcc776712015-02-17 20:18:47 -08003879 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003880 clientSp->notifyError(
3881 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003882 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003883 }
3884 }
3885
Ruben Brunkcc776712015-02-17 20:18:47 -08003886 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3887 // other clients from connecting in mServiceLockWrapper if held
3888 mServiceLock.unlock();
3889
Ruben Brunk36597b22015-03-20 22:15:57 -07003890 // Do not clear caller identity, remote caller should be client proccess
3891
Ruben Brunkcc776712015-02-17 20:18:47 -08003892 for (auto& i : evicted) {
3893 if (i.get() != nullptr) {
3894 i->disconnect();
3895 ret = true;
3896 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003897 }
3898
Ruben Brunkcc776712015-02-17 20:18:47 -08003899 // Reacquire mServiceLock
3900 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003901
Ruben Brunkcc776712015-02-17 20:18:47 -08003902 } // lock is destroyed, allow further connect calls
3903
3904 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003905}
3906
Ruben Brunkcc776712015-02-17 20:18:47 -08003907std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003908 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003909 std::shared_ptr<CameraState> state;
3910 {
3911 Mutex::Autolock lock(mCameraStatesLock);
3912 auto iter = mCameraStates.find(cameraId);
3913 if (iter != mCameraStates.end()) {
3914 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003915 }
3916 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003917 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003918}
3919
Austin Borgered99f642023-06-01 16:51:35 -07003920sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003921 // Remove from active clients list
3922 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3923 if (clientDescriptorPtr == nullptr) {
3924 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003925 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003926 return sp<BasicClient>{nullptr};
3927 }
3928
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003929 sp<BasicClient> client = clientDescriptorPtr->getValue();
3930 if (client.get() != nullptr) {
3931 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3932 }
3933 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003934}
3935
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003936void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003937 // Acquire mServiceLock and prevent other clients from connecting
3938 std::unique_ptr<AutoConditionLock> lock =
3939 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3940
Ruben Brunk6267b532015-04-30 17:44:07 -07003941 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003942 for (size_t i = 0; i < newUserIds.size(); i++) {
3943 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003944 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003945 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003946 return;
3947 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003948 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003949 }
3950
Ruben Brunka8ca9152015-04-07 14:23:40 -07003951
Ruben Brunk6267b532015-04-30 17:44:07 -07003952 if (newAllowedUsers == mAllowedUsers) {
3953 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3954 return;
3955 }
3956
3957 logUserSwitch(mAllowedUsers, newAllowedUsers);
3958
3959 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003960
3961 // Current user has switched, evict all current clients.
3962 std::vector<sp<BasicClient>> evicted;
3963 for (auto& i : mActiveClientManager.getAll()) {
3964 auto clientSp = i->getValue();
3965
3966 if (clientSp.get() == nullptr) {
3967 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3968 continue;
3969 }
3970
Ruben Brunk6267b532015-04-30 17:44:07 -07003971 // Don't evict clients that are still allowed.
3972 uid_t clientUid = clientSp->getClientUid();
3973 userid_t clientUserId = multiuser_get_user_id(clientUid);
3974 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3975 continue;
3976 }
3977
Ruben Brunk36597b22015-03-20 22:15:57 -07003978 evicted.push_back(clientSp);
3979
Ruben Brunk36597b22015-03-20 22:15:57 -07003980 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003981 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003982
Ruben Brunk36597b22015-03-20 22:15:57 -07003983 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003984 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003985 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003986 " to user switch.", i->getKey().c_str(),
3987 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003988 i->getOwnerId(), i->getPriority().getScore(),
3989 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003990
3991 }
3992
3993 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3994 // blocking other clients from connecting in mServiceLockWrapper if held.
3995 mServiceLock.unlock();
3996
3997 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08003998 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003999
4000 for (auto& i : evicted) {
4001 i->disconnect();
4002 }
4003
Austin Borger22c5c852024-03-08 13:31:36 -08004004 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07004005
4006 // Reacquire mServiceLock
4007 mServiceLock.lock();
4008}
Ruben Brunkcc776712015-02-17 20:18:47 -08004009
Austin Borgered99f642023-06-01 16:51:35 -07004010void CameraService::logEvent(const std::string &event) {
4011 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07004012 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07004013 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07004014 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07004015 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07004016 mEventLog.add(msg);
4017 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
4018 // Error event not added to the dumpsys log before
4019 mEventLog.add(msg);
4020 sServiceErrorEventSet.insert(msg);
4021 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004022}
4023
Austin Borgered99f642023-06-01 16:51:35 -07004024void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
4025 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004026 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004027 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
4028 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004029}
4030
Austin Borgered99f642023-06-01 16:51:35 -07004031void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
4032 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004033 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004034 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
4035 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004036}
4037
Austin Borgered99f642023-06-01 16:51:35 -07004038void CameraService::logConnected(const std::string &cameraId, int clientPid,
4039 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004040 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004041 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
4042 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004043}
4044
Austin Borgered99f642023-06-01 16:51:35 -07004045void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
4046 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004047 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004048 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
4049 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004050}
4051
Austin Borgered99f642023-06-01 16:51:35 -07004052void CameraService::logRejected(const std::string &cameraId, int clientPid,
4053 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004054 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07004055 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
4056 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004057}
4058
Austin Borgered99f642023-06-01 16:51:35 -07004059void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
4060 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07004061 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07004062 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
4063 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07004064}
4065
Ruben Brunk6267b532015-04-30 17:44:07 -07004066void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
4067 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07004068 std::string newUsers = toString(newUserIds);
4069 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004070 if (oldUsers.size() == 0) {
4071 oldUsers = "<None>";
4072 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07004073 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07004074 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
4075 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004076}
4077
Austin Borgered99f642023-06-01 16:51:35 -07004078void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004079 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004080 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004081}
4082
Austin Borgered99f642023-06-01 16:51:35 -07004083void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004084 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004085 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004086}
4087
Austin Borgered99f642023-06-01 16:51:35 -07004088void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004089 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004090 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07004091}
4092
Austin Borgered99f642023-06-01 16:51:35 -07004093void CameraService::logServiceError(const std::string &msg, int errorCode) {
4094 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
4095 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004096}
4097
Ruben Brunk36597b22015-03-20 22:15:57 -07004098status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4099 uint32_t flags) {
4100
Mathias Agopian65ab4712010-07-14 17:59:35 -07004101 // Permission checks
4102 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004103 case SHELL_COMMAND_TRANSACTION: {
4104 int in = data.readFileDescriptor();
4105 int out = data.readFileDescriptor();
4106 int err = data.readFileDescriptor();
4107 int argc = data.readInt32();
4108 Vector<String16> args;
4109 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
4110 args.add(data.readString16());
4111 }
4112 sp<IBinder> unusedCallback;
4113 sp<IResultReceiver> resultReceiver;
4114 status_t status;
4115 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
4116 return status;
4117 }
4118 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
4119 return status;
4120 }
4121 status = shellCommand(in, out, err, args);
4122 if (resultReceiver != nullptr) {
4123 resultReceiver->send(status);
4124 }
4125 return NO_ERROR;
4126 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004127 }
4128
4129 return BnCameraService::onTransact(code, data, reply, flags);
4130}
4131
Mathias Agopian65ab4712010-07-14 17:59:35 -07004132// We share the media players for shutter and recording sound for all clients.
4133// A reference count is kept to determine when we will actually release the
4134// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09004135sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
4136 sp<MediaPlayer> mp = new MediaPlayer();
4137 status_t error;
4138 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08004139 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09004140 error = mp->prepare();
4141 }
4142 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004143 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09004144 mp->disconnect();
4145 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004146 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004147 }
4148 return mp;
4149}
4150
username5755fea2018-12-27 09:48:08 +08004151void CameraService::increaseSoundRef() {
4152 Mutex::Autolock lock(mSoundLock);
4153 mSoundRef++;
4154}
4155
4156void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004157 ATRACE_CALL();
4158
username5755fea2018-12-27 09:48:08 +08004159 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
4160 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
4161 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
4162 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
4163 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4164 }
4165 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
4166 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4167 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4168 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004169 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08004170 }
4171 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4172 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4173 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4174 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4175 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004176 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004177}
4178
username5755fea2018-12-27 09:48:08 +08004179void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004180 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004181 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004182 if (--mSoundRef) return;
4183
4184 for (int i = 0; i < NUM_SOUNDS; i++) {
4185 if (mSoundPlayer[i] != 0) {
4186 mSoundPlayer[i]->disconnect();
4187 mSoundPlayer[i].clear();
4188 }
4189 }
4190}
4191
4192void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004193 ATRACE_CALL();
4194
Mathias Agopian65ab4712010-07-14 17:59:35 -07004195 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004196 if (kind < 0 || kind >= NUM_SOUNDS) {
4197 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4198 return;
4199 }
4200
Mathias Agopian65ab4712010-07-14 17:59:35 -07004201 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004202 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004203 sp<MediaPlayer> player = mSoundPlayer[kind];
4204 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004205 player->seekTo(0);
4206 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004207 }
4208}
4209
4210// ----------------------------------------------------------------------------
4211
4212CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004213 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004214 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004215 const std::string& clientPackageName, bool systemNativeClient,
4216 const std::optional<std::string>& clientFeatureId,
4217 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004218 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004219 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004220 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004221 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004222 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07004223 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004224 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004225 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004226 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004227 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004228 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004229{
Austin Borger22c5c852024-03-08 13:31:36 -08004230 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004231 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004232
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004233 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004234
username5755fea2018-12-27 09:48:08 +08004235 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004236
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004237 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004238}
4239
Mathias Agopian65ab4712010-07-14 17:59:35 -07004240// tear down the client
4241CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004242 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004243 mDestructionStarted = true;
4244
username5755fea2018-12-27 09:48:08 +08004245 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004246 // unconditionally disconnect. function is idempotent
4247 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004248}
4249
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004250sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4251
Igor Murashkin634a5152013-02-20 17:15:11 -08004252CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004253 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004254 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004255 const std::string& clientPackageName, bool nativeClient,
4256 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004257 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004258 int servicePid, bool overrideToPortrait):
Austin Borger249e6592024-03-10 22:28:11 -07004259 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004260 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004261 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004262 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4263 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004264 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004265 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004266 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07004267 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004268 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004269 mRemoteBinder(remoteCallback),
4270 mOpsActive(false),
4271 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004272{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004273 if (sCameraService == nullptr) {
4274 sCameraService = cameraService;
4275 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004276
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004277 // There are 2 scenarios in which a client won't have AppOps operations
4278 // (both scenarios : native clients)
4279 // 1) It's an system native client*, the package name will be empty
4280 // and it will return from this function in the previous if condition
4281 // (This is the same as the previously existing behavior).
4282 // 2) It is a system native client, but its package name has been
4283 // modified for debugging, however it still must not use AppOps since
4284 // the package name is not a real one.
4285 //
4286 // * system native client - native client with UID < AID_APP_START. It
4287 // doesn't exclude clients not on the system partition.
4288 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004289 mAppOpsManager = std::make_unique<AppOpsManager>();
4290 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004291
Charles Chenf075f082024-03-04 23:32:55 +00004292 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004293}
4294
4295CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004296 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004297 mDestructionStarted = true;
4298}
4299
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004300binder::Status CameraService::BasicClient::disconnect() {
4301 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004302 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004303 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004304 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004305 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004306
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004307 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004308 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004309 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004310 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004311
4312 sp<IBinder> remote = getRemote();
4313 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004314 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004315 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004316
4317 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004318 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004319 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004320 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004321 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004322
Igor Murashkincba2c162013-03-20 15:56:31 -07004323 // client shouldn't be able to call into us anymore
4324 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004325
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004326 const auto& mActivityManager = getActivityManager();
4327 if (mActivityManager) {
4328 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004329 getCallingUid(),
4330 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004331 }
4332
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004333 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004334}
4335
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004336status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4337 // No dumping of clients directly over Binder,
4338 // must go through CameraService::dump
4339 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004340 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004341 return OK;
4342}
4343
Austin Borgered99f642023-06-01 16:51:35 -07004344status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004345 // Can't watch tags directly, must go through CameraService::startWatchingTags
4346 return OK;
4347}
4348
4349status_t CameraService::BasicClient::stopWatchingTags(int) {
4350 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4351 return OK;
4352}
4353
4354status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4355 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4356 return OK;
4357}
4358
Austin Borgered99f642023-06-01 16:51:35 -07004359std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004360 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004361}
4362
Emilian Peev8b64f282021-03-25 16:49:57 -07004363int CameraService::BasicClient::getCameraFacing() const {
4364 return mCameraFacing;
4365}
4366
4367int CameraService::BasicClient::getCameraOrientation() const {
4368 return mOrientation;
4369}
Ruben Brunkcc776712015-02-17 20:18:47 -08004370
4371int CameraService::BasicClient::getClientPid() const {
4372 return mClientPid;
4373}
4374
Ruben Brunk6267b532015-04-30 17:44:07 -07004375uid_t CameraService::BasicClient::getClientUid() const {
4376 return mClientUid;
4377}
4378
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004379bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4380 // Defaults to API2.
4381 return level == API_2;
4382}
4383
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004384status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004385 {
4386 Mutex::Autolock l(mAudioRestrictionLock);
4387 mAudioRestriction = mode;
4388 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004389 sCameraService->updateAudioRestriction();
4390 return OK;
4391}
4392
4393int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004394 return sCameraService->updateAudioRestriction();
4395}
4396
4397int32_t CameraService::BasicClient::getAudioRestriction() const {
4398 Mutex::Autolock l(mAudioRestrictionLock);
4399 return mAudioRestriction;
4400}
4401
4402bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4403 switch (mode) {
4404 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4405 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4406 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4407 return true;
4408 default:
4409 return false;
4410 }
4411}
4412
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004413status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4414 if (mode == AppOpsManager::MODE_ERRORED) {
4415 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004416 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004417 return PERMISSION_DENIED;
4418 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4419 // If the calling Uid is trusted (a native service), the AppOpsManager could
4420 // return MODE_IGNORED. Do not treat such case as error.
4421 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4422 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004423
4424 bool isCameraPrivacyEnabled;
4425 if (flags::camera_privacy_allowlist()) {
4426 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4427 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4428 } else {
4429 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004430 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004431 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004432 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4433 // We prefer to successfully open the camera and perform camera muting
4434 // or blocking in connectHelper as handleAppOpMode can be called before the
4435 // connection has been fully established and at that time camera muting
4436 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004437 if (!isUidActive || !isCameraPrivacyEnabled) {
4438 ALOGI("Camera %s: Access for \"%s\" has been restricted",
Austin Borgered99f642023-06-01 16:51:35 -07004439 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004440 // Return the same error as for device policy manager rejection
4441 return -EACCES;
4442 }
4443 }
4444 return OK;
4445}
4446
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004447status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004448 ATRACE_CALL();
4449
Igor Murashkine6800ce2013-03-04 17:25:57 -08004450 {
4451 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004452 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004453 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004454 if (mAppOpsManager != nullptr) {
4455 // Notify app ops that the camera is not available
4456 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004457
4458 if (flags::watch_foreground_changes()) {
4459 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4460 toString16(mClientPackageName),
4461 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4462 } else {
4463 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004464 toString16(mClientPackageName), mOpsCallback);
Austin Borgerca1e0062023-06-28 11:32:55 -07004465 }
Igor Murashkine6800ce2013-03-04 17:25:57 -08004466
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004467 // Just check for camera acccess here on open - delay startOp until
4468 // camera frames start streaming in startCameraStreamingOps
4469 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004470 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004471 status_t res = handleAppOpMode(mode);
4472 if (res != OK) {
4473 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004474 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004475 }
4476
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004477 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004478
4479 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004480 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004481
Austin Borgerdddb7552023-03-30 17:53:01 -07004482 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004483
Shuzhen Wang695044d2020-03-06 09:02:23 -08004484 // Notify listeners of camera open/close status
4485 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4486
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004487 return OK;
4488}
4489
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004490status_t CameraService::BasicClient::startCameraStreamingOps() {
4491 ATRACE_CALL();
4492
4493 if (!mOpsActive) {
4494 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4495 return INVALID_OPERATION;
4496 }
4497 if (mOpsStreaming) {
4498 ALOGV("%s: Streaming already active!", __FUNCTION__);
4499 return OK;
4500 }
4501
4502 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004503 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004504
4505 if (mAppOpsManager != nullptr) {
4506 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004507 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4508 toString16(mClientFeatureId),
4509 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004510 status_t res = handleAppOpMode(mode);
4511 if (res != OK) {
4512 return res;
4513 }
4514 }
4515
4516 mOpsStreaming = true;
4517
4518 return OK;
4519}
4520
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004521status_t CameraService::BasicClient::noteAppOp() {
4522 ATRACE_CALL();
4523
4524 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004525 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004526
4527 // noteAppOp is only used for when camera mute is not supported, in order
4528 // to trigger the sensor privacy "Unblock" dialog
4529 if (mAppOpsManager != nullptr) {
4530 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004531 toString16(mClientPackageName), toString16(mClientFeatureId),
4532 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004533 status_t res = handleAppOpMode(mode);
4534 if (res != OK) {
4535 return res;
4536 }
4537 }
4538
4539 return OK;
4540}
4541
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004542status_t CameraService::BasicClient::finishCameraStreamingOps() {
4543 ATRACE_CALL();
4544
4545 if (!mOpsActive) {
4546 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4547 return INVALID_OPERATION;
4548 }
4549 if (!mOpsStreaming) {
4550 ALOGV("%s: Streaming not active!", __FUNCTION__);
4551 return OK;
4552 }
4553
4554 if (mAppOpsManager != nullptr) {
4555 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004556 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004557 mOpsStreaming = false;
4558 }
4559
4560 return OK;
4561}
4562
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004563status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004564 ATRACE_CALL();
4565
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004566 if (mOpsStreaming) {
4567 // Make sure we've notified everyone about camera stopping
4568 finishCameraStreamingOps();
4569 }
4570
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004571 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004572 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004573 mOpsActive = false;
4574
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004575 // This function is called when a client disconnects. This should
4576 // release the camera, but actually only if it was in a proper
4577 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004578 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004579 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004580
Ruben Brunkcc776712015-02-17 20:18:47 -08004581 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004582 sCameraService->updateStatus(StatusInternal::PRESENT,
4583 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004584 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004585 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004586 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4587 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004588 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004589 mOpsCallback.clear();
4590
Austin Borgerdddb7552023-03-30 17:53:01 -07004591 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004592
Shuzhen Wang695044d2020-03-06 09:02:23 -08004593 // Notify listeners of camera open/close status
4594 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4595
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004596 return OK;
4597}
4598
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004599void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004600 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004601 if (mAppOpsManager == nullptr) {
4602 return;
4603 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004604 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004605 if (op != AppOpsManager::OP_CAMERA) {
4606 ALOGW("Unexpected app ops notification received: %d", op);
4607 return;
4608 }
4609
4610 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004611 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004612 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004613 ALOGV("checkOp returns: %d, %s ", res,
4614 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4615 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4616 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4617 "UNKNOWN");
4618
Shuzhen Wang64900852021-02-05 09:03:29 -08004619 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004620 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4621 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004622 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004623 } else if (res == AppOpsManager::MODE_IGNORED) {
4624 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004625
Austin Borgerca1e0062023-06-28 11:32:55 -07004626 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4627 // If not visible, but still active, then we want to block instead of muting the camera.
4628 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4629 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4630
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004631 bool isCameraPrivacyEnabled;
4632 if (flags::camera_privacy_allowlist()) {
4633 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4634 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4635 } else {
4636 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004637 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004638 }
4639
4640 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004641 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4642 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4643 isCameraPrivacyEnabled);
4644 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4645 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4646 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004647 if (!mUidIsTrusted) {
Austin Borgerca1e0062023-06-28 11:32:55 -07004648 if (flags::watch_foreground_changes()) {
4649 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4650 setCameraMute(true);
4651 } else {
4652 block();
4653 }
4654 } else {
4655 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4656 setCameraMute(true);
4657 } else if (!isUidActive
4658 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4659 block();
4660 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004661 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004662 }
Evan Severson09ab4002021-02-10 14:15:19 -08004663 } else if (res == AppOpsManager::MODE_ALLOWED) {
4664 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004665 }
4666}
4667
Svet Ganova453d0d2018-01-11 15:37:58 -08004668void CameraService::BasicClient::block() {
4669 ATRACE_CALL();
4670
4671 // Reset the client PID to allow server-initiated disconnect,
4672 // and to prevent further calls by client.
Austin Borger22c5c852024-03-08 13:31:36 -08004673 mClientPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004674 CaptureResultExtras resultExtras; // a dummy result (invalid)
4675 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4676 disconnect();
4677}
4678
Mathias Agopian65ab4712010-07-14 17:59:35 -07004679// ----------------------------------------------------------------------------
4680
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004681void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004682 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004683 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004684 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4685 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4686 api1ErrorCode = CAMERA_ERROR_DISABLED;
4687 }
4688 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004689 } else {
4690 ALOGE("mRemoteCallback is NULL!!");
4691 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004692}
4693
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004694// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004695binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004696 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004697 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004698}
4699
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004700bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4701 return level == API_1;
4702}
4703
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004704CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4705 mClient(client) {
4706}
4707
4708void CameraService::Client::OpsCallback::opChanged(int32_t op,
4709 const String16& packageName) {
4710 sp<BasicClient> client = mClient.promote();
4711 if (client != NULL) {
4712 client->opChanged(op, packageName);
4713 }
4714}
4715
Mathias Agopian65ab4712010-07-14 17:59:35 -07004716// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004717// UidPolicy
4718// ----------------------------------------------------------------------------
4719
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004720void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004721 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004722 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004723
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004724 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004725 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004726 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004727 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004728 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4729 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004730 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004731 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004732 if (res == OK) {
4733 mRegistered = true;
4734 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004735 } else {
4736 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004737 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004738}
4739
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004740void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004741 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004742 return;
4743 }
4744
4745 registerWithActivityManager();
4746}
4747
4748void CameraService::UidPolicy::registerSelf() {
4749 // Use check service to see if the activity service is available
4750 // If not available then register for notifications, instead of blocking
4751 // till the service is ready
4752 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004753 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004754 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004755 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004756 } else {
4757 registerWithActivityManager();
4758 }
4759}
4760
Svet Ganova453d0d2018-01-11 15:37:58 -08004761void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004762 Mutex::Autolock _l(mUidLock);
4763
Steven Moreland2f348142019-07-02 15:59:07 -07004764 mAm.unregisterUidObserver(this);
4765 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004766 mRegistered = false;
4767 mActiveUids.clear();
4768 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004769}
4770
4771void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4772 onUidIdle(uid, disabled);
4773}
4774
4775void CameraService::UidPolicy::onUidActive(uid_t uid) {
4776 Mutex::Autolock _l(mUidLock);
4777 mActiveUids.insert(uid);
4778}
4779
4780void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4781 bool deleted = false;
4782 {
4783 Mutex::Autolock _l(mUidLock);
4784 if (mActiveUids.erase(uid) > 0) {
4785 deleted = true;
4786 }
4787 }
4788 if (deleted) {
4789 sp<CameraService> service = mService.promote();
4790 if (service != nullptr) {
4791 service->blockClientsForUid(uid);
4792 }
4793 }
4794}
4795
Emilian Peev53722fa2019-02-22 17:47:20 -08004796void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004797 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004798 bool procStateChange = false;
4799 {
4800 Mutex::Autolock _l(mUidLock);
4801 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4802 mMonitoredUids[uid].procState != procState) {
4803 mMonitoredUids[uid].procState = procState;
4804 procStateChange = true;
4805 }
4806 }
4807
4808 if (procStateChange) {
4809 sp<CameraService> service = mService.promote();
4810 if (service != nullptr) {
4811 service->notifyMonitoredUids();
4812 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004813 }
4814}
4815
Austin Borgerdddb7552023-03-30 17:53:01 -07004816/**
4817 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4818 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4819 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4820 * monitoredUids. If it is revised above some other monitoredUid, signal
4821 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4822 * foreground apps in split screen - state changes will capture all other cases.
4823 */
4824void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4825 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004826 {
4827 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004828 auto it = mMonitoredUids.find(uid);
4829
4830 if (it != mMonitoredUids.end()) {
4831 if (it->second.hasCamera) {
4832 for (auto &monitoredUid : mMonitoredUids) {
4833 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004834 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004835 notifyUidSet.emplace(monitoredUid.first);
4836 }
4837 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004838 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004839 notifyUidSet.emplace(uid);
4840 } else {
4841 for (auto &monitoredUid : mMonitoredUids) {
4842 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004843 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004844 notifyUidSet.emplace(uid);
4845 }
4846 }
4847 }
4848 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004849 }
4850 }
4851
Austin Borgerdddb7552023-03-30 17:53:01 -07004852 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004853 sp<CameraService> service = mService.promote();
4854 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004855 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004856 }
4857 }
4858}
4859
Austin Borgerdddb7552023-03-30 17:53:01 -07004860/**
4861 * Register a uid for monitoring, and note whether it owns a camera.
4862 */
4863void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004864 Mutex::Autolock _l(mUidLock);
4865 auto it = mMonitoredUids.find(uid);
4866 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004867 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004868 } else {
Austin Borger65577682022-02-17 00:25:43 +00004869 MonitoredUid monitoredUid;
4870 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004871 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004872 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004873 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004874 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004875 if (res != OK) {
4876 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4877 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004878 }
4879
4880 if (openCamera) {
4881 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004882 }
4883}
4884
Austin Borgerdddb7552023-03-30 17:53:01 -07004885/**
4886 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4887 */
4888void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004889 Mutex::Autolock _l(mUidLock);
4890 auto it = mMonitoredUids.find(uid);
4891 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004892 it->second.refCount--;
4893 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004894 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004895 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004896 if (res != OK) {
4897 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4898 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004899 } else if (closeCamera) {
4900 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004901 }
4902 } else {
4903 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4904 }
4905}
4906
Austin Borgered99f642023-06-01 16:51:35 -07004907bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004908 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004909 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004910}
4911
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004912static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4913static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004914
Austin Borgered99f642023-06-01 16:51:35 -07004915bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004916 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004917 // If activity manager is unreachable, assume everything is active
4918 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004919 return true;
4920 }
4921 auto it = mOverrideUids.find(uid);
4922 if (it != mOverrideUids.end()) {
4923 return it->second;
4924 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004925 bool active = mActiveUids.find(uid) != mActiveUids.end();
4926 if (!active) {
4927 // We want active UIDs to always access camera with their first attempt since
4928 // there is no guarantee the app is robustly written and would retry getting
4929 // the camera on failure. The inverse case is not a problem as we would take
4930 // camera away soon once we get the callback that the uid is no longer active.
4931 ActivityManager am;
4932 // Okay to access with a lock held as UID changes are dispatched without
4933 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004934 int64_t startTimeMillis = 0;
4935 do {
4936 // TODO: Fix this b/109950150!
4937 // Okay this is a hack. There is a race between the UID turning active and
4938 // activity being resumed. The proper fix is very risky, so we temporary add
4939 // some polling which should happen pretty rarely anyway as the race is hard
4940 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004941 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004942 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004943 if (active) {
4944 break;
4945 }
4946 if (startTimeMillis <= 0) {
4947 startTimeMillis = uptimeMillis();
4948 }
4949 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004950 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004951 if (remainingTimeMillis <= 0) {
4952 break;
4953 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004954 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4955
4956 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004957 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004958 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004959 } while (true);
4960
Svet Ganov7b4ab782018-03-25 12:48:10 -07004961 if (active) {
4962 // Now that we found out the UID is actually active, cache that
4963 mActiveUids.insert(uid);
4964 }
4965 }
4966 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004967}
4968
Varun Shahb42f1eb2019-04-16 14:45:13 -07004969int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4970 Mutex::Autolock _l(mUidLock);
4971 return getProcStateLocked(uid);
4972}
4973
4974int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4975 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4976 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004977 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004978 }
4979 return procState;
4980}
4981
Austin Borgered99f642023-06-01 16:51:35 -07004982void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4983 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004984 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004985}
4986
Austin Borgered99f642023-06-01 16:51:35 -07004987void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004988 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004989}
4990
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004991void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4992 Mutex::Autolock _l(mUidLock);
4993 ALOGV("UidPolicy: ActivityManager has died");
4994 mRegistered = false;
4995 mActiveUids.clear();
4996}
4997
Austin Borgered99f642023-06-01 16:51:35 -07004998void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004999 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005000 bool wasActive = false;
5001 bool isActive = false;
5002 {
5003 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07005004 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08005005 mOverrideUids.erase(uid);
5006 if (insert) {
5007 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
5008 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07005009 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08005010 }
5011 if (wasActive != isActive && !isActive) {
5012 sp<CameraService> service = mService.promote();
5013 if (service != nullptr) {
5014 service->blockClientsForUid(uid);
5015 }
5016 }
5017}
5018
5019// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08005020// SensorPrivacyPolicy
5021// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005022
5023void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
5024{
Michael Grooverd1d435a2018-12-18 17:39:42 -08005025 Mutex::Autolock _l(mSensorPrivacyLock);
5026 if (mRegistered) {
5027 return;
5028 }
Evan Severson09ab4002021-02-10 14:15:19 -08005029 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08005030 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00005031 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005032 mSpm.addToggleSensorPrivacyListener(this);
5033 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005034 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005035 if (flags::camera_privacy_allowlist()) {
5036 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
5037 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
5038 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5039 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005040 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005041 if (res == OK) {
5042 mRegistered = true;
5043 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
5044 }
5045}
5046
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005047void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
5048 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07005049 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005050 return;
5051 }
5052
5053 registerWithSensorPrivacyManager();
5054}
5055
5056void CameraService::SensorPrivacyPolicy::registerSelf() {
5057 // Use checkservice to see if the sensor_privacy service is available
5058 // If service is not available then register for notification
5059 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07005060 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005061 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07005062 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005063 } else {
5064 registerWithSensorPrivacyManager();
5065 }
5066}
5067
Michael Grooverd1d435a2018-12-18 17:39:42 -08005068void CameraService::SensorPrivacyPolicy::unregisterSelf() {
5069 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08005070 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00005071 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005072 mSpm.removeToggleSensorPrivacyListener(this);
5073 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005074 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005075 mRegistered = false;
5076 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
5077}
5078
5079bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005080 if (!mRegistered) {
5081 registerWithSensorPrivacyManager();
5082 }
5083
Michael Grooverd1d435a2018-12-18 17:39:42 -08005084 Mutex::Autolock _l(mSensorPrivacyLock);
5085 return mSensorPrivacyEnabled;
5086}
5087
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005088int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
5089 if (!mRegistered) {
5090 registerWithSensorPrivacyManager();
5091 }
5092
5093 Mutex::Autolock _l(mSensorPrivacyLock);
5094 return mCameraPrivacyState;
5095}
5096
Evan Seversond0b69922022-01-27 10:47:34 -08005097bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08005098 if (!hasCameraPrivacyFeature()) {
5099 return false;
5100 }
Evan Seversond0b69922022-01-27 10:47:34 -08005101 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08005102}
5103
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005104bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
5105 if (!hasCameraPrivacyFeature()) {
5106 return SensorPrivacyManager::DISABLED;
5107 }
5108 return mSpm.isCameraPrivacyEnabled(packageName);
5109}
5110
Evan Seversond0b69922022-01-27 10:47:34 -08005111binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005112 int toggleType, int sensor, bool enabled) {
5113 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
5114 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
5115 {
5116 Mutex::Autolock _l(mSensorPrivacyLock);
5117 mSensorPrivacyEnabled = enabled;
5118 }
5119 // if sensor privacy is enabled then block all clients from accessing the camera
5120 if (enabled) {
5121 sp<CameraService> service = mService.promote();
5122 if (service != nullptr) {
5123 service->blockAllClients();
5124 }
5125 }
5126 }
5127 return binder::Status::ok();
5128}
5129
5130binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
5131 int, int sensor, int state) {
5132 if (!flags::camera_privacy_allowlist()
5133 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
5134 return binder::Status::ok();
5135 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08005136 {
5137 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005138 mCameraPrivacyState = state;
5139 }
5140 sp<CameraService> service = mService.promote();
5141 if (!service) {
5142 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005143 }
5144 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005145 if (state == SensorPrivacyManager::ENABLED) {
5146 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08005147 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005148 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005149 }
5150 return binder::Status::ok();
5151}
5152
5153void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
5154 Mutex::Autolock _l(mSensorPrivacyLock);
5155 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
5156 mRegistered = false;
5157}
5158
Evan Severson09ab4002021-02-10 14:15:19 -08005159bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08005160 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
5161 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5162 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
5163 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5164 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08005165}
5166
Michael Grooverd1d435a2018-12-18 17:39:42 -08005167// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005168// CameraState
5169// ----------------------------------------------------------------------------
5170
Austin Borgered99f642023-06-01 16:51:35 -07005171CameraService::CameraState::CameraState(const std::string& id, int cost,
5172 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005173 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005174 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005175 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005176
5177CameraService::CameraState::~CameraState() {}
5178
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005179CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005180 Mutex::Autolock lock(mStatusLock);
5181 return mStatus;
5182}
5183
Austin Borgered99f642023-06-01 16:51:35 -07005184std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005185 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005186 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005187 return res;
5188}
5189
Ruben Brunkcc776712015-02-17 20:18:47 -08005190CameraParameters CameraService::CameraState::getShimParams() const {
5191 return mShimParams;
5192}
5193
5194void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5195 mShimParams = params;
5196}
5197
5198int CameraService::CameraState::getCost() const {
5199 return mCost;
5200}
5201
Austin Borgered99f642023-06-01 16:51:35 -07005202std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005203 return mConflicting;
5204}
5205
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005206SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5207 return mSystemCameraKind;
5208}
5209
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005210bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5211 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5212 != mPhysicalCameras.end();
5213}
5214
Austin Borgered99f642023-06-01 16:51:35 -07005215bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005216 Mutex::Autolock lock(mStatusLock);
5217 auto result = mUnavailablePhysicalIds.insert(physicalId);
5218 return result.second;
5219}
5220
Austin Borgered99f642023-06-01 16:51:35 -07005221bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005222 Mutex::Autolock lock(mStatusLock);
5223 auto count = mUnavailablePhysicalIds.erase(physicalId);
5224 return count > 0;
5225}
5226
Austin Borgered99f642023-06-01 16:51:35 -07005227void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005228 Mutex::Autolock lock(mStatusLock);
5229 mClientPackage = clientPackage;
5230}
5231
Austin Borgered99f642023-06-01 16:51:35 -07005232std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005233 Mutex::Autolock lock(mStatusLock);
5234 return mClientPackage;
5235}
5236
Ruben Brunkcc776712015-02-17 20:18:47 -08005237// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005238// ClientEventListener
5239// ----------------------------------------------------------------------------
5240
5241void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005242 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005243 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005244 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005245 if (basicClient.get() != nullptr) {
5246 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005247 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005248 static_cast<int>(basicClient->getClientUid()));
5249 }
5250}
5251
5252void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005253 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005254 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005255 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005256 if (basicClient.get() != nullptr) {
5257 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005258 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005259 static_cast<int>(basicClient->getClientUid()));
5260 }
5261}
5262
Ruben Brunk99e69712015-05-26 17:25:07 -07005263// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005264// CameraClientManager
5265// ----------------------------------------------------------------------------
5266
Ruben Brunk99e69712015-05-26 17:25:07 -07005267CameraService::CameraClientManager::CameraClientManager() {
5268 setListener(std::make_shared<ClientEventListener>());
5269}
5270
Ruben Brunkcc776712015-02-17 20:18:47 -08005271CameraService::CameraClientManager::~CameraClientManager() {}
5272
5273sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005274 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005275 auto descriptor = get(id);
5276 if (descriptor == nullptr) {
5277 return sp<BasicClient>{nullptr};
5278 }
5279 return descriptor->getValue();
5280}
5281
Austin Borgered99f642023-06-01 16:51:35 -07005282std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005283 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005284 std::ostringstream ret;
5285 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005286 bool hasAny = false;
5287 for (auto& i : all) {
5288 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005289 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005290 int32_t cost = i->getCost();
5291 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005292 int32_t score = i->getPriority().getScore();
5293 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005294 auto conflicting = i->getConflicting();
5295 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005296 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005297 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005298 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005299 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005300 uid_t clientUid = clientSp->getClientUid();
5301 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005302 }
Austin Borgered99f642023-06-01 16:51:35 -07005303 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5304 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005305
Ruben Brunk6267b532015-04-30 17:44:07 -07005306 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005307 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005308 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005309 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005310 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005311 }
5312
Austin Borgered99f642023-06-01 16:51:35 -07005313 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005314 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005315 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005316 }
Austin Borgered99f642023-06-01 16:51:35 -07005317 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005318 }
Austin Borgered99f642023-06-01 16:51:35 -07005319 if (hasAny) ret << "\n";
5320 ret << "]\n";
5321 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005322}
5323
5324CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005325 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5326 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005327 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005328
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005329 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005330 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005331
Austin Borgered99f642023-06-01 16:51:35 -07005332 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005333 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5334 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005335}
5336
5337CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005338 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005339 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005340 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005341 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005342 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5343 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005344}
5345
5346// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005347// InjectionStatusListener
5348// ----------------------------------------------------------------------------
5349
5350void CameraService::InjectionStatusListener::addListener(
5351 const sp<ICameraInjectionCallback>& callback) {
5352 Mutex::Autolock lock(mListenerLock);
5353 if (mCameraInjectionCallback) return;
5354 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5355 if (res == OK) {
5356 mCameraInjectionCallback = callback;
5357 }
5358}
5359
5360void CameraService::InjectionStatusListener::removeListener() {
5361 Mutex::Autolock lock(mListenerLock);
5362 if (mCameraInjectionCallback == nullptr) {
5363 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5364 return;
5365 }
5366 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5367 mCameraInjectionCallback = nullptr;
5368}
5369
5370void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005371 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005372 if (mCameraInjectionCallback == nullptr) {
5373 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5374 return;
5375 }
Cliff Wud3a05312021-04-26 23:07:31 +08005376
5377 switch (err) {
5378 case -ENODEV:
5379 mCameraInjectionCallback->onInjectionError(
5380 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5381 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005382 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005383 break;
5384 case -EBUSY:
5385 mCameraInjectionCallback->onInjectionError(
5386 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5387 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005388 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005389 break;
5390 case DEAD_OBJECT:
5391 mCameraInjectionCallback->onInjectionError(
5392 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5393 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005394 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005395 break;
5396 case INVALID_OPERATION:
5397 mCameraInjectionCallback->onInjectionError(
5398 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5399 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005400 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005401 break;
5402 case UNKNOWN_TRANSACTION:
5403 mCameraInjectionCallback->onInjectionError(
5404 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5405 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005406 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005407 break;
5408 default:
5409 mCameraInjectionCallback->onInjectionError(
5410 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5411 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005412 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005413 }
Cliff Wud8cae102021-03-11 01:37:42 +08005414}
5415
5416void CameraService::InjectionStatusListener::binderDied(
5417 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005418 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5419 auto parent = mParent.promote();
5420 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005421 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5422 if (clientDescriptor != nullptr) {
5423 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5424 baseClientPtr->stopInjection();
5425 }
Cliff Wu3b268182021-07-06 15:44:43 +08005426 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005427 }
5428}
5429
5430// ----------------------------------------------------------------------------
5431// CameraInjectionSession
5432// ----------------------------------------------------------------------------
5433
5434binder::Status CameraService::CameraInjectionSession::stopInjection() {
5435 Mutex::Autolock lock(mInjectionSessionLock);
5436 auto parent = mParent.promote();
5437 if (parent == nullptr) {
5438 ALOGE("CameraInjectionSession: Parent is gone");
5439 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5440 "Camera service encountered error");
5441 }
Cliff Wud3a05312021-04-26 23:07:31 +08005442
5443 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005444 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5445 if (clientDescriptor != nullptr) {
5446 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5447 res = baseClientPtr->stopInjection();
5448 if (res != OK) {
5449 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5450 " ret != NO_ERROR: %d", res);
5451 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5452 "Camera session encountered error");
5453 }
5454 }
Cliff Wu3b268182021-07-06 15:44:43 +08005455 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005456 return binder::Status::ok();
5457}
5458
5459// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005460
5461static const int kDumpLockRetries = 50;
5462static const int kDumpLockSleep = 60000;
5463
5464static bool tryLock(Mutex& mutex)
5465{
5466 bool locked = false;
5467 for (int i = 0; i < kDumpLockRetries; ++i) {
5468 if (mutex.tryLock() == NO_ERROR) {
5469 locked = true;
5470 break;
5471 }
5472 usleep(kDumpLockSleep);
5473 }
5474 return locked;
5475}
5476
Rucha Katakwardf223072021-06-15 10:21:00 -07005477void CameraService::cacheDump() {
5478 if (mMemFd != -1) {
5479 const Vector<String16> args;
5480 ATRACE_CALL();
5481 // Acquiring service lock here will avoid the deadlock since
5482 // cacheDump will not be called during the second disconnect.
5483 Mutex::Autolock lock(mServiceLock);
5484
5485 Mutex::Autolock l(mCameraStatesLock);
5486 // Start collecting the info for open sessions and store it in temp file.
5487 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005488 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005489 auto clientDescriptor = mActiveClientManager.get(cameraId);
5490 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005491 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005492 // Log the current open session info before device is disconnected.
5493 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5494 }
5495 }
5496 }
5497}
5498
Mathias Agopian65ab4712010-07-14 17:59:35 -07005499status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005500 ATRACE_CALL();
5501
Austin Borgered99f642023-06-01 16:51:35 -07005502 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005503 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005504 getCallingPid(),
5505 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005506 return NO_ERROR;
5507 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005508 bool locked = tryLock(mServiceLock);
5509 // failed to lock - CameraService is probably deadlocked
5510 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005511 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005512 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005513
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005514 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005515 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005516
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005517 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005518 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005519
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005520 if (locked) mServiceLock.unlock();
5521 return NO_ERROR;
5522 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005523 dprintf(fd, "\n== Service global info: ==\n\n");
5524 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005525 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005526 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5527 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005528 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5529 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5530 }
Austin Borgered99f642023-06-01 16:51:35 -07005531 std::string activeClientString = mActiveClientManager.toString();
5532 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5533 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005534 if (mStreamUseCaseOverrides.size() > 0) {
5535 dprintf(fd, "Active stream use case overrides:");
5536 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5537 dprintf(fd, " %" PRId64, useCaseOverride);
5538 }
5539 dprintf(fd, "\n");
5540 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005541
5542 dumpEventLog(fd);
5543
5544 bool stateLocked = tryLock(mCameraStatesLock);
5545 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005546 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005547 }
5548
Emilian Peevbd8c5032018-02-14 23:05:40 +00005549 int argSize = args.size();
5550 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005551 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005552 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005553 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005554 }
5555 break;
5556 }
5557 }
5558
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005559 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005560 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005561
Austin Borgered99f642023-06-01 16:51:35 -07005562 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005563
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005564 CameraParameters p = state.second->getShimParams();
5565 if (!p.isEmpty()) {
5566 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5567 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005568 }
5569
5570 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005571 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005572 // log the current open session info
5573 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005574 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005575 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005576 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005577
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005578 }
5579
5580 if (stateLocked) mCameraStatesLock.unlock();
5581
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005582 if (locked) mServiceLock.unlock();
5583
Emilian Peevf53f66e2017-04-11 14:29:43 +01005584 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005585
5586 dprintf(fd, "\n== Vendor tags: ==\n\n");
5587
5588 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5589 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005590 sp<VendorTagDescriptorCache> cache =
5591 VendorTagDescriptorCache::getGlobalVendorTagCache();
5592 if (cache == NULL) {
5593 dprintf(fd, "No vendor tags.\n");
5594 } else {
5595 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5596 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005597 } else {
5598 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5599 }
5600
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005601 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005602 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005603 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005604
5605 // Process dump arguments, if any
5606 int n = args.size();
5607 String16 verboseOption("-v");
5608 String16 unreachableOption("--unreachable");
5609 for (int i = 0; i < n; i++) {
5610 if (args[i] == verboseOption) {
5611 // change logging level
5612 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005613 std::string levelStr = toStdString(args[i+1]);
5614 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005615 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005616 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005617 } else if (args[i] == unreachableOption) {
5618 // Dump memory analysis
5619 // TODO - should limit be an argument parameter?
5620 UnreachableMemoryInfo info;
5621 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5622 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005623 dprintf(fd, "\n== Unable to dump unreachable memory. "
5624 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005625 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005626 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005627 std::string s = info.ToString(/*log_contents*/ true);
5628 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005629 }
5630 }
5631 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005632
5633 bool serviceLocked = tryLock(mServiceLock);
5634
5635 // Dump info from previous open sessions.
5636 // Reposition the offset to beginning of the file before reading
5637
5638 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5639 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5640 ssize_t size_read;
5641 char buf[4096];
5642 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5643 // Read data from file to a small buffer and write it to fd.
5644 write(fd, buf, size_read);
5645 if (size_read == -1) {
5646 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5647 break;
5648 }
5649 }
5650 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5651 } else {
5652 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5653 }
5654
5655 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005656 return NO_ERROR;
5657}
5658
Rucha Katakwardf223072021-06-15 10:21:00 -07005659void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005660 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005661 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005662 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005663 getFormattedCurrentTime().c_str(),
5664 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005665 dprintf(fd, " Client priority score: %d state: %d\n",
5666 clientDescriptor->getPriority().getScore(),
5667 clientDescriptor->getPriority().getState());
5668 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5669
5670 auto client = clientDescriptor->getValue();
5671 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005672 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005673
5674 client->dumpClient(fd, args);
5675}
5676
Austin Borgered99f642023-06-01 16:51:35 -07005677void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005678 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005679 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005680}
5681
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005682void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005683 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005684
5685 Mutex::Autolock l(mLogLock);
5686 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005687 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005688 }
5689
5690 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005691 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005692 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005693 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005694 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005695 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005696}
5697
Austin Borgered99f642023-06-01 16:51:35 -07005698void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005699 Mutex::Autolock lock(mLogLock);
5700 if (!isClientWatchedLocked(client)) { return; }
5701
5702 std::vector<std::string> dumpVector;
5703 client->dumpWatchedEventsToVector(dumpVector);
5704
5705 if (dumpVector.empty()) { return; }
5706
Austin Borgered99f642023-06-01 16:51:35 -07005707 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005708
Austin Borgered99f642023-06-01 16:51:35 -07005709 std::string currentTime = getFormattedCurrentTime();
5710 dumpString << "Cached @ ";
5711 dumpString << currentTime;
5712 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005713
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005714 size_t i = dumpVector.size();
5715
5716 // Store the string in reverse order (latest last)
5717 while (i > 0) {
5718 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005719 dumpString << cameraId;
5720 dumpString << ":";
5721 dumpString << client->getPackageName();
5722 dumpString << " ";
5723 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005724 }
5725
Austin Borgered99f642023-06-01 16:51:35 -07005726 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005727}
5728
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005729void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005730 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005731 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5732 if (mTorchClientMap[i] == who) {
5733 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005734 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005735 status_t res = mFlashlight->setTorchMode(cameraId, false);
5736 if (res) {
5737 ALOGE("%s: torch client died but couldn't turn off torch: "
5738 "%s (%d)", __FUNCTION__, strerror(-res), res);
5739 return;
5740 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005741 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005742 break;
5743 }
5744 }
5745}
5746
Ruben Brunkcc776712015-02-17 20:18:47 -08005747/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005748
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005749 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005750 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5751 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005752 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005753 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005754 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005755
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005756 // check torch client
5757 handleTorchClientBinderDied(who);
5758
5759 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005760 if(!evictClientIdByRemote(who)) {
5761 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005762 return;
5763 }
5764
Ruben Brunkcc776712015-02-17 20:18:47 -08005765 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5766 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005767}
5768
Austin Borgered99f642023-06-01 16:51:35 -07005769void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005770 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005771}
5772
Austin Borgered99f642023-06-01 16:51:35 -07005773void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005774 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005775 // Do not lock mServiceLock here or can get into a deadlock from
5776 // connect() -> disconnect -> updateStatus
5777
5778 auto state = getCameraState(cameraId);
5779
5780 if (state == nullptr) {
5781 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005782 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005783 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005784 }
5785
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005786 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5787 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5788 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005789 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005790 return;
5791 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005792
Biswarup Pal37a75182024-01-16 15:53:35 +00005793 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5794 CameraMetadata cameraInfo;
5795 status_t res = mCameraProviderManager->getCameraCharacteristics(
5796 cameraId, false, &cameraInfo, false);
5797 if (res != OK) {
5798 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5799 __FUNCTION__, cameraId.c_str());
5800 } else {
5801 int32_t deviceId = getDeviceId(cameraInfo);
5802 if (deviceId != kDefaultDeviceId) {
5803 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5804 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5805 static_cast<camera_metadata_enum_android_lens_facing_t>(
5806 lensFacingEntry.data.u8[0]);
5807 std::string mappedCameraId;
5808 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5809 mappedCameraId = kVirtualDeviceBackCameraId;
5810 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5811 mappedCameraId = kVirtualDeviceFrontCameraId;
5812 } else {
5813 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5814 __func__);
5815 }
5816 if (!mappedCameraId.empty()) {
5817 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5818 }
5819 }
5820 }
5821 }
5822
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005823 // Collect the logical cameras without holding mStatusLock in updateStatus
5824 // as that can lead to a deadlock(b/162192331).
5825 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005826 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005827 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005828 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005829 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005830 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005831 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5832 auto [deviceId, mappedCameraId] =
5833 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005834
Biswarup Pal37a75182024-01-16 15:53:35 +00005835 if (status != StatusInternal::ENUMERATING) {
5836 // Update torch status if it has a flash unit.
5837 Mutex::Autolock al(mTorchStatusMutex);
5838 TorchModeStatus torchStatus;
5839 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5840 NAME_NOT_FOUND) {
5841 TorchModeStatus newTorchStatus =
5842 status == StatusInternal::PRESENT ?
5843 TorchModeStatus::AVAILABLE_OFF :
5844 TorchModeStatus::NOT_AVAILABLE;
5845 if (torchStatus != newTorchStatus) {
5846 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5847 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005848 }
5849 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005850
Biswarup Pal37a75182024-01-16 15:53:35 +00005851 Mutex::Autolock lock(mStatusListenerLock);
5852 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5853 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005854
Biswarup Pal37a75182024-01-16 15:53:35 +00005855 for (auto& listener : mListenerList) {
5856 bool isVendorListener = listener->isVendorListener();
5857 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5858 listener->getListenerPid(), listener->getListenerUid())) {
5859 ALOGV("Skipping discovery callback for system-only camera device %s",
5860 cameraId.c_str());
5861 continue;
5862 }
5863
5864 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5865 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005866 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005867 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005868 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5869 ret.exceptionCode());
Biswarup Pal37a75182024-01-16 15:53:35 +00005870
5871 // Only cameras of the default device can be remapped to a different camera
5872 // (using remapCameraIds method), so do the following only if the camera is
5873 // associated with the default device.
5874 if (deviceId == kDefaultDeviceId) {
5875 // For the default device, also trigger the callbacks for cameras that were
5876 // remapped to the current cameraId for the specific package that this
5877 // listener belongs to.
5878 std::vector<std::string> remappedCameraIds =
5879 findOriginalIdsForRemappedCameraId(cameraId,
5880 listener->getListenerUid());
5881 for (auto &remappedCameraId: remappedCameraIds) {
5882 ret = listener->getListener()->onStatusChanged(
5883 mapToInterface(status), remappedCameraId, kDefaultDeviceId);
5884 listener->handleBinderStatus(ret,
5885 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
5886 __FUNCTION__, listener->getListenerUid(),
5887 listener->getListenerPid(), ret.exceptionCode());
5888 }
5889 }
malikakash82ed4352023-07-21 22:44:34 +00005890 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005891 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005892}
5893
Austin Borgered99f642023-06-01 16:51:35 -07005894void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5895 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005896 auto state = getCameraState(cameraId);
5897 if (state == nullptr) {
5898 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005899 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005900 return;
5901 }
5902 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005903 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005904 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005905 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005906 }
5907
Biswarup Pal37a75182024-01-16 15:53:35 +00005908 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5909 auto [deviceId, mappedCameraId] =
5910 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5911
Shuzhen Wang695044d2020-03-06 09:02:23 -08005912 Mutex::Autolock lock(mStatusListenerLock);
5913
5914 for (const auto& it : mListenerList) {
5915 if (!it->isOpenCloseCallbackAllowed()) {
5916 continue;
5917 }
5918
5919 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005920 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005921 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5922 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005923 } else {
Biswarup Pal37a75182024-01-16 15:53:35 +00005924 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005925 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005926
5927 it->handleBinderStatus(ret,
5928 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5929 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005930 }
5931}
5932
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005933template<class Func>
5934void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005935 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005936 std::initializer_list<StatusInternal> rejectSourceStates,
5937 Func onStatusUpdatedLocked) {
5938 Mutex::Autolock lock(mStatusLock);
5939 StatusInternal oldStatus = mStatus;
5940 mStatus = status;
5941
5942 if (oldStatus == status) {
5943 return;
5944 }
5945
5946 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005947 cameraId.c_str(), oldStatus, status);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005948
5949 if (oldStatus == StatusInternal::NOT_PRESENT &&
5950 (status != StatusInternal::PRESENT &&
5951 status != StatusInternal::ENUMERATING)) {
5952
5953 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5954 __FUNCTION__);
5955 mStatus = oldStatus;
5956 return;
5957 }
5958
5959 /**
5960 * Sometimes we want to conditionally do a transition.
5961 * For example if a client disconnects, we want to go to PRESENT
5962 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5963 */
5964 for (auto& rejectStatus : rejectSourceStates) {
5965 if (oldStatus == rejectStatus) {
5966 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005967 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005968 mStatus = oldStatus;
5969 return;
5970 }
5971 }
5972
5973 onStatusUpdatedLocked(cameraId, status);
5974}
5975
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005976status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005977 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005978 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005979 if (!status) {
5980 return BAD_VALUE;
5981 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005982 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5983 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005984 // invalid camera ID or the camera doesn't have a flash unit
5985 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005986 }
5987
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005988 *status = mTorchStatusMap.valueAt(index);
5989 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005990}
5991
Austin Borgered99f642023-06-01 16:51:35 -07005992status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005993 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005994 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5995 if (index == NAME_NOT_FOUND) {
5996 return BAD_VALUE;
5997 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005998 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005999
6000 return OK;
6001}
6002
Austin Borgered99f642023-06-01 16:51:35 -07006003std::list<std::string> CameraService::getLogicalCameras(
6004 const std::string& physicalCameraId) {
6005 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08006006 Mutex::Autolock lock(mCameraStatesLock);
6007 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07006008 if (state.second->containsPhysicalCamera(physicalCameraId)) {
6009 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08006010 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006011 }
6012 return retList;
6013}
6014
6015void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07006016 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00006017 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006018 // mStatusListenerLock is expected to be locked
6019 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08006020 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006021 // Note: we check only the deviceKind of the physical camera id
6022 // since, logical camera ids and their physical camera ids are
6023 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07006024 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
6025 listener->getListenerPid(), listener->getListenerUid())) {
6026 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07006027 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07006028 continue;
6029 }
Austin Borgere8e2c422022-05-12 13:45:24 -07006030 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00006031 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07006032 listener->handleBinderStatus(ret,
6033 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
6034 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
6035 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08006036 }
6037 }
6038}
6039
Svet Ganova453d0d2018-01-11 15:37:58 -08006040void CameraService::blockClientsForUid(uid_t uid) {
6041 const auto clients = mActiveClientManager.getAll();
6042 for (auto& current : clients) {
6043 if (current != nullptr) {
6044 const auto basicClient = current->getValue();
6045 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
6046 basicClient->block();
6047 }
6048 }
6049 }
6050}
6051
Michael Grooverd1d435a2018-12-18 17:39:42 -08006052void CameraService::blockAllClients() {
6053 const auto clients = mActiveClientManager.getAll();
6054 for (auto& current : clients) {
6055 if (current != nullptr) {
6056 const auto basicClient = current->getValue();
6057 if (basicClient.get() != nullptr) {
6058 basicClient->block();
6059 }
6060 }
6061 }
6062}
6063
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00006064void CameraService::blockPrivacyEnabledClients() {
6065 const auto clients = mActiveClientManager.getAll();
6066 for (auto& current : clients) {
6067 if (current != nullptr) {
6068 const auto basicClient = current->getValue();
6069 if (basicClient.get() != nullptr) {
6070 std::string pkgName = basicClient->getPackageName();
6071 bool cameraPrivacyEnabled =
6072 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
6073 if (cameraPrivacyEnabled) {
6074 basicClient->block();
6075 }
6076 }
6077 }
6078 }
6079}
6080
Svet Ganova453d0d2018-01-11 15:37:58 -08006081// NOTE: This is a remote API - make sure all args are validated
6082status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006083 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006084 return PERMISSION_DENIED;
6085 }
6086 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
6087 return BAD_VALUE;
6088 }
Austin Borgered99f642023-06-01 16:51:35 -07006089 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006090 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006091 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006092 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006093 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006094 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07006095 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006096 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07006097 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006098 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07006099 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006100 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07006101 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006102 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07006103 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006104 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07006105 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006106 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07006107 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006108 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07006109 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006110 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07006111 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006112 handleClearStreamUseCaseOverrides();
6113 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07006114 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006115 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07006116 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006117 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07006118 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00006119 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07006120 } else if (args.size() >= 4 && args[0] == toString16("remap-camera-id")) {
malikakash82ed4352023-07-21 22:44:34 +00006121 return handleCameraIdRemapping(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006122 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006123 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006124 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08006125 }
6126 printHelp(err);
6127 return BAD_VALUE;
6128}
6129
malikakash82ed4352023-07-21 22:44:34 +00006130status_t CameraService::handleCameraIdRemapping(const Vector<String16>& args, int err) {
6131 uid_t uid = IPCThreadState::self()->getCallingUid();
6132 if (uid != AID_ROOT) {
6133 dprintf(err, "Must be adb root\n");
6134 return PERMISSION_DENIED;
6135 }
6136 if (args.size() != 4) {
6137 dprintf(err, "Expected format: remap-camera-id <PACKAGE> <Id0> <Id1>\n");
6138 return BAD_VALUE;
6139 }
Austin Borgered99f642023-06-01 16:51:35 -07006140 std::string packageName = toStdString(args[1]);
6141 std::string cameraIdToReplace = toStdString(args[2]);
6142 std::string cameraIdNew = toStdString(args[3]);
malikakash82ed4352023-07-21 22:44:34 +00006143 remapCameraIds({{packageName, {{cameraIdToReplace, cameraIdNew}}}});
6144 return OK;
6145}
6146
Svet Ganova453d0d2018-01-11 15:37:58 -08006147status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006148 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006149
Svet Ganova453d0d2018-01-11 15:37:58 -08006150 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07006151 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006152 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07006153 } else if ((args[2] != toString16("idle"))) {
6154 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08006155 return BAD_VALUE;
6156 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006157
6158 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006159 if (args.size() >= 5 && args[3] == toString16("--user")) {
6160 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006161 }
6162
6163 uid_t uid;
6164 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
6165 return BAD_VALUE;
6166 }
6167
6168 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08006169 return NO_ERROR;
6170}
6171
6172status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006173 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006174
6175 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006176 if (args.size() >= 4 && args[2] == toString16("--user")) {
6177 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006178 }
6179
6180 uid_t uid;
6181 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006182 return BAD_VALUE;
6183 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006184
6185 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08006186 return NO_ERROR;
6187}
6188
6189status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006190 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006191
6192 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006193 if (args.size() >= 4 && args[2] == toString16("--user")) {
6194 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006195 }
6196
6197 uid_t uid;
6198 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006199 return BAD_VALUE;
6200 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006201
6202 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006203 return dprintf(out, "active\n");
6204 } else {
6205 return dprintf(out, "idle\n");
6206 }
6207}
6208
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006209status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006210 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006211 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
6212 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
6213 Mutex::Autolock lock(mServiceLock);
6214
6215 mOverrideRotateAndCropMode = rotateValue;
6216
6217 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6218
6219 const auto clients = mActiveClientManager.getAll();
6220 for (auto& current : clients) {
6221 if (current != nullptr) {
6222 const auto basicClient = current->getValue();
6223 if (basicClient.get() != nullptr) {
6224 basicClient->setRotateAndCropOverride(rotateValue);
6225 }
6226 }
6227 }
6228
6229 return OK;
6230}
6231
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006232status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6233 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006234 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006235 if ((*end != '\0') ||
6236 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6237 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6238 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6239 return BAD_VALUE;
6240 }
6241
6242 Mutex::Autolock lock(mServiceLock);
6243 mOverrideAutoframingMode = autoframingValue;
6244
6245 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6246
6247 const auto clients = mActiveClientManager.getAll();
6248 for (auto& current : clients) {
6249 if (current != nullptr) {
6250 const auto basicClient = current->getValue();
6251 if (basicClient.get() != nullptr) {
6252 basicClient->setAutoframingOverride(autoframingValue);
6253 }
6254 }
6255 }
6256
6257 return OK;
6258}
6259
Ravneetaeb20dc2022-03-30 05:33:03 +00006260status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006261 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006262
6263 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6264
6265 Mutex::Autolock lock(mServiceLock);
6266
6267 mCameraServiceWatchdogEnabled = enableWatchdog;
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->setCameraServiceWatchdog(enableWatchdog);
6275 }
6276 }
6277 }
6278
6279 return OK;
6280}
6281
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006282status_t CameraService::handleGetRotateAndCrop(int out) {
6283 Mutex::Autolock lock(mServiceLock);
6284
6285 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6286}
6287
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006288status_t CameraService::handleGetAutoframing(int out) {
6289 Mutex::Autolock lock(mServiceLock);
6290
6291 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6292}
6293
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006294status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6295 char *endPtr;
6296 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006297 std::string maskString = toStdString(args[1]);
6298 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006299
6300 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006301 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006302 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6303
6304 Mutex::Autolock lock(mServiceLock);
6305
6306 mImageDumpMask = maskValue;
6307
6308 return OK;
6309}
6310
6311status_t CameraService::handleGetImageDumpMask(int out) {
6312 Mutex::Autolock lock(mServiceLock);
6313
6314 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6315}
6316
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006317status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006318 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006319 if (errno != 0) return BAD_VALUE;
6320
6321 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6322 Mutex::Autolock lock(mServiceLock);
6323
6324 mOverrideCameraMuteMode = (muteValue == 1);
6325
6326 const auto clients = mActiveClientManager.getAll();
6327 for (auto& current : clients) {
6328 if (current != nullptr) {
6329 const auto basicClient = current->getValue();
6330 if (basicClient.get() != nullptr) {
6331 if (basicClient->supportsCameraMute()) {
6332 basicClient->setCameraMute(mOverrideCameraMuteMode);
6333 }
6334 }
6335 }
6336 }
6337
6338 return OK;
6339}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006340
Shuzhen Wang16610a62022-12-15 22:38:07 -08006341status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6342 std::vector<int64_t> useCasesOverride;
6343 for (size_t i = 1; i < args.size(); i++) {
6344 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006345 std::string arg = toStdString(args[i]);
6346 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006347 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006348 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006349 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006350 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006351 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006352 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006353 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006354 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006355 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006356 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006357 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006358 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006359 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6360 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006361 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006362 return BAD_VALUE;
6363 }
6364 useCasesOverride.push_back(useCase);
6365 }
6366
6367 Mutex::Autolock lock(mServiceLock);
6368 mStreamUseCaseOverrides = std::move(useCasesOverride);
6369
6370 return OK;
6371}
6372
6373void CameraService::handleClearStreamUseCaseOverrides() {
6374 Mutex::Autolock lock(mServiceLock);
6375 mStreamUseCaseOverrides.clear();
6376}
6377
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006378status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6379 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006380 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006381 if ((*end != '\0') ||
6382 (zoomOverrideValue != -1 &&
6383 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6384 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6385 return BAD_VALUE;
6386 }
6387
6388 Mutex::Autolock lock(mServiceLock);
6389 mZoomOverrideValue = zoomOverrideValue;
6390
6391 const auto clients = mActiveClientManager.getAll();
6392 for (auto& current : clients) {
6393 if (current != nullptr) {
6394 const auto basicClient = current->getValue();
6395 if (basicClient.get() != nullptr) {
6396 if (basicClient->supportsZoomOverride()) {
6397 basicClient->setZoomOverride(mZoomOverrideValue);
6398 }
6399 }
6400 }
6401 }
6402
6403 return OK;
6404}
6405
Avichal Rakesh84147132021-11-11 17:47:11 -08006406status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006407 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006408 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006409 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006410 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006411 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006412 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006413 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006414 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006415 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006416 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006417 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006418 dprintf(outFd, "Camera service watch commands:\n"
6419 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6420 " starts watching the provided tags for clients with provided package\n"
6421 " recognizes tag shorthands like '3a'\n"
6422 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006423 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006424 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006425 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006426 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006427 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006428 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006429 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006430}
6431
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006432status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6433 Mutex::Autolock lock(mLogLock);
6434 size_t tagsIdx; // index of '-m'
6435 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006436 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006437 if (tagsIdx < args.size() - 1) {
6438 tags = args[tagsIdx + 1];
6439 } else {
6440 dprintf(outFd, "No tags provided.\n");
6441 return BAD_VALUE;
6442 }
6443
6444 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006445 // watch all clients if no clients are provided
6446 String16 clients = toString16(kWatchAllClientsFlag);
6447 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006448 clientsIdx++);
6449 if (clientsIdx < args.size() - 1) {
6450 clients = args[clientsIdx + 1];
6451 }
Austin Borgered99f642023-06-01 16:51:35 -07006452 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006453
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006454 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006455 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006456
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006457 bool serviceLock = tryLock(mServiceLock);
6458 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006459 auto cameraClients = mActiveClientManager.getAll();
6460 for (const auto &clientDescriptor: cameraClients) {
6461 if (clientDescriptor == nullptr) { continue; }
6462 sp<BasicClient> client = clientDescriptor->getValue();
6463 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006464
6465 if (isClientWatchedLocked(client.get())) {
6466 client->startWatchingTags(mMonitorTags, outFd);
6467 numWatchedClients++;
6468 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006469 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006470 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6471
6472 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006473 return OK;
6474}
6475
6476status_t CameraService::stopWatchingTags(int outFd) {
6477 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006478 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006479 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006480
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006481 mWatchedClientPackages.clear();
6482 mWatchedClientsDumpCache.clear();
6483
6484 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006485 auto cameraClients = mActiveClientManager.getAll();
6486 for (const auto &clientDescriptor : cameraClients) {
6487 if (clientDescriptor == nullptr) { continue; }
6488 sp<BasicClient> client = clientDescriptor->getValue();
6489 if (client.get() == nullptr) { continue; }
6490 client->stopWatchingTags(outFd);
6491 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006492 dprintf(outFd, "Stopped watching all clients.\n");
6493 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006494 return OK;
6495}
6496
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006497status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6498 Mutex::Autolock lock(mLogLock);
6499 size_t clearedSize = mWatchedClientsDumpCache.size();
6500 mWatchedClientsDumpCache.clear();
6501 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6502 return OK;
6503}
6504
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006505status_t CameraService::printWatchedTags(int outFd) {
6506 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006507 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006508
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006509 bool printedSomething = false; // tracks if any monitoring information was printed
6510 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006511
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006512 bool serviceLock = tryLock(mServiceLock);
6513 // get all watched clients that are currently connected
6514 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6515 if (clientDescriptor == nullptr) { continue; }
6516
6517 sp<BasicClient> client = clientDescriptor->getValue();
6518 if (client.get() == nullptr) { continue; }
6519 if (!isClientWatchedLocked(client.get())) { continue; }
6520
6521 std::vector<std::string> dumpVector;
6522 client->dumpWatchedEventsToVector(dumpVector);
6523
6524 size_t printIdx = dumpVector.size();
6525 if (printIdx == 0) {
6526 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006527 }
6528
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006529 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006530 const std::string &cameraId = clientDescriptor->getKey();
6531 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006532 while(printIdx > 0) {
6533 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006534 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006535 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006536 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006537 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006538 printedSomething = true;
6539
6540 connectedMonitoredClients.emplace(client->getPackageName());
6541 }
6542 if (serviceLock) { mServiceLock.unlock(); }
6543
6544 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6545 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006546 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006547 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6548 continue;
6549 }
6550
Austin Borgered99f642023-06-01 16:51:35 -07006551 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006552 dprintf(outFd, "%s\n", kv.second.c_str());
6553 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006554 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006555
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006556 if (!printedSomething) {
6557 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006558 }
6559
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006560 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006561}
6562
Avichal Rakesh84147132021-11-11 17:47:11 -08006563// Print all events in vector `events' that came after lastPrintedEvent
6564void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006565 const std::string &cameraId,
6566 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006567 const std::vector<std::string> &events,
6568 const std::string &lastPrintedEvent) {
6569 if (events.empty()) { return; }
6570
6571 // index of lastPrintedEvent in events.
6572 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6573 size_t lastPrintedIdx;
6574 for (lastPrintedIdx = 0;
6575 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6576 lastPrintedIdx++);
6577
6578 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6579
Avichal Rakesh84147132021-11-11 17:47:11 -08006580 // print events in chronological order (latest event last)
6581 size_t idxToPrint = lastPrintedIdx;
6582 do {
6583 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006584 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6585 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006586 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006587}
6588
6589// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6590// command should be interrupted if the user presses the return key, or if user loses any way to
6591// signal interrupt.
6592// If timeoutMs == 0, this function will always return false
6593bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6594 struct timeval startTime;
6595 int startTimeError = gettimeofday(&startTime, nullptr);
6596 if (startTimeError) {
6597 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6598 return true;
6599 }
6600
6601 const nfds_t numFds = 1;
6602 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6603
6604 struct timeval currTime;
6605 char buffer[2];
6606 while(true) {
6607 int currTimeError = gettimeofday(&currTime, nullptr);
6608 if (currTimeError) {
6609 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6610 return true;
6611 }
6612
6613 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6614 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6615 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6616
6617 if (remainingTimeMs <= 0) {
6618 // No user interrupt within timeoutMs, don't interrupt watch command
6619 return false;
6620 }
6621
6622 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6623 if (numFdsUpdated < 0) {
6624 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6625 return true;
6626 }
6627
6628 if (numFdsUpdated == 0) {
6629 // No user input within timeoutMs, don't interrupt watch command
6630 return false;
6631 }
6632
6633 if (!(pollFd.revents & POLLIN)) {
6634 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6635 return true;
6636 }
6637
6638 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6639 if (sizeRead < 0) {
6640 dprintf(outFd, "Error reading user input. Exiting.\n");
6641 return true;
6642 }
6643
6644 if (sizeRead == 0) {
6645 // Reached end of input fd (can happen if input is piped)
6646 // User has no way to signal an interrupt, so interrupt here
6647 return true;
6648 }
6649
6650 if (buffer[0] == '\n') {
6651 // User pressed return, interrupt watch command.
6652 return true;
6653 }
6654 }
6655}
6656
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006657status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6658 int inFd, int outFd) {
6659 // Figure out refresh interval, if present in args
6660 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006661 if (args.size() > 2) {
6662 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006663 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006664 intervalIdx++);
6665
6666 size_t intervalValIdx = intervalIdx + 1;
6667 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006668 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006669 if (errno) { return BAD_VALUE; }
6670 }
6671 }
6672
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006673 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6674 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006675
Avichal Rakesh84147132021-11-11 17:47:11 -08006676 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006677 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006678
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006679 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006680 bool serviceLock = tryLock(mServiceLock);
6681 auto cameraClients = mActiveClientManager.getAll();
6682 if (serviceLock) { mServiceLock.unlock(); }
6683
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006684 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006685 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006686 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006687
6688 sp<BasicClient> client = clientDescriptor->getValue();
6689 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006690 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006691
Austin Borgered99f642023-06-01 16:51:35 -07006692 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006693 // This also initializes the map entries with an empty string
6694 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6695
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006696 std::vector<std::string> latestEvents;
6697 client->dumpWatchedEventsToVector(latestEvents);
6698
6699 if (!latestEvents.empty()) {
6700 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006701 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006702 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006703 latestEvents,
6704 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006705 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006706 }
6707 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006708 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006709 break;
6710 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006711 }
6712 return OK;
6713}
6714
Austin Borgered99f642023-06-01 16:51:35 -07006715void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006716 mWatchedClientPackages.clear();
6717
Austin Borgered99f642023-06-01 16:51:35 -07006718 std::istringstream iss(clients);
6719 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006720
Austin Borgered99f642023-06-01 16:51:35 -07006721 while (std::getline(iss, nextClient, ',')) {
6722 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006723 // Don't need to track any other package if 'all' is present
6724 mWatchedClientPackages.clear();
6725 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6726 break;
6727 }
6728
6729 // track package names
6730 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006731 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006732}
6733
Svet Ganova453d0d2018-01-11 15:37:58 -08006734status_t CameraService::printHelp(int out) {
6735 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006736 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6737 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6738 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006739 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6740 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6741 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006742 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6743 " Valid values 0=false, 1=true, 2=auto\n"
6744 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006745 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6746 " Valid values 0=OFF, 1=ON for JPEG\n"
6747 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006748 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006749 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6750 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6751 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6752 " on. In case the number of usecases is smaller than the number of streams, the\n"
6753 " last use case is assigned to all the remaining streams. In case of multiple\n"
6754 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6755 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6756 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6757 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006758 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6759 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006760 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6761 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006762 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
malikakash73125c62023-07-21 22:44:34 +00006763 " remap-camera-id <PACKAGE> <Id0> <Id1> remaps camera ids. Must use adb root\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006764 " help print this message\n");
6765}
6766
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006767bool CameraService::isClientWatched(const BasicClient *client) {
6768 Mutex::Autolock lock(mLogLock);
6769 return isClientWatchedLocked(client);
6770}
6771
6772bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6773 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6774 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6775}
6776
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006777int32_t CameraService::updateAudioRestriction() {
6778 Mutex::Autolock lock(mServiceLock);
6779 return updateAudioRestrictionLocked();
6780}
6781
6782int32_t CameraService::updateAudioRestrictionLocked() {
6783 int32_t mode = 0;
6784 // iterate through all active client
6785 for (const auto& i : mActiveClientManager.getAll()) {
6786 const auto clientSp = i->getValue();
6787 mode |= clientSp->getAudioRestriction();
6788 }
6789
6790 bool modeChanged = (mAudioRestriction != mode);
6791 mAudioRestriction = mode;
6792 if (modeChanged) {
6793 mAppOps.setCameraAudioRestriction(mode);
6794 }
6795 return mode;
6796}
6797
Austin Borgered99f642023-06-01 16:51:35 -07006798status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006799 sp<BasicClient> clientSp) {
6800 std::unique_ptr<AutoConditionLock> lock =
6801 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6802 status_t res = NO_ERROR;
6803 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006804 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006805 mInjectionStatusListener->notifyInjectionError(
6806 externalCamId, UNKNOWN_TRANSACTION);
6807 clientSp->notifyError(
6808 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6809 CaptureResultExtras());
6810
6811 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6812 // other clients from connecting in mServiceLockWrapper if held
6813 mServiceLock.unlock();
6814
6815 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006816 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006817 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006818 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006819
6820 // Reacquire mServiceLock
6821 mServiceLock.lock();
6822 }
6823
6824 return res;
6825}
6826
Cliff Wud3a05312021-04-26 23:07:31 +08006827void CameraService::clearInjectionParameters() {
6828 {
6829 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006830 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006831 mInjectionInternalCamId = "";
6832 }
6833 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006834 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006835}
6836
Biswarup Pal37a75182024-01-16 15:53:35 +00006837} // namespace android