blob: d65fa8bd8f050ba667e2c203aad65ee4e0029f94 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080024#include <cstdlib>
Ruben Brunkcc776712015-02-17 20:18:47 -080025#include <cstring>
26#include <ctime>
Austin Borgered99f642023-06-01 16:51:35 -070027#include <iostream>
28#include <sstream>
Ruben Brunkcc776712015-02-17 20:18:47 -080029#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080031#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <pthread.h>
Avichal Rakesh84147132021-11-11 17:47:11 -080033#include <poll.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070034
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080035#include <android/hardware/ICamera.h>
36#include <android/hardware/ICameraClient.h>
37
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -070038#include <aidl/AidlCameraService.h>
Alex Deymo9c2a2c22016-08-25 11:59:14 -070039#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080040#include <android-base/parseint.h>
Biswarup Pal37a75182024-01-16 15:53:35 +000041#include <android_companion_virtualdevice_flags.h>
42#include <android/companion/virtualnative/IVirtualDeviceManagerNative.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080043#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080044#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046#include <binder/MemoryBase.h>
47#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080048#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080049#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080050#include <binderthreadstate/CallerUtils.h>
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -070051#include <com_android_internal_camera_flags.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070052#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070053#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080054#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080055#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070057#include "hidl/HidlCameraService.h"
58#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080059#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070060#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080062#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070063#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070064#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000065#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070066#include <utils/Errors.h>
67#include <utils/Log.h>
68#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070069#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080070#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080071#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080072#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080073#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070074#include <system/camera_metadata.h>
Kunal Malhotrabfc96052023-02-28 23:25:34 +000075#include <binder/IServiceManager.h>
76#include <binder/IActivityManager.h>
Biswarup Pal37a75182024-01-16 15:53:35 +000077#include <camera/CameraUtils.h>
Austin Borgered99f642023-06-01 16:51:35 -070078#include <camera/StringUtils.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080079
Ruben Brunkb2119af2014-05-09 19:57:56 -070080#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070081
82#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070083#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070084#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070085#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000086#include "utils/TagMonitor.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070087#include "utils/CameraServiceProxyWrapper.h"
Shuzhen Wang045be6c2023-10-12 10:01:10 -070088#include "utils/SessionConfigurationUtils.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080090namespace {
91 const char* kPermissionServiceName = "permission";
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080092 const char* kActivityServiceName = "activity";
93 const char* kSensorPrivacyServiceName = "sensor_privacy";
94 const char* kAppopsServiceName = "appops";
Jyoti Bhayanada519ab2023-05-15 15:49:15 -070095 const char* kProcessInfoServiceName = "processinfo";
Biswarup Pal37a75182024-01-16 15:53:35 +000096 const char* kVirtualDeviceBackCameraId = "0";
97 const char* kVirtualDeviceFrontCameraId = "1";
98
99 int32_t getDeviceId(const android::CameraMetadata& cameraInfo) {
100 if (!cameraInfo.exists(ANDROID_INFO_DEVICE_ID)) {
101 return android::kDefaultDeviceId;
102 }
103
104 const auto &deviceIdEntry = cameraInfo.find(ANDROID_INFO_DEVICE_ID);
105 return deviceIdEntry.data.i32[0];
106 }
107} // namespace anonymous
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -0800108
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109namespace android {
110
Austin Borgerea931242021-12-13 23:10:41 +0000111using namespace camera3;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700112using namespace camera3::SessionConfigurationUtils;
113
114using binder::Status;
Biswarup Pal37a75182024-01-16 15:53:35 +0000115using companion::virtualnative::IVirtualDeviceManagerNative;
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700116using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700117using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800118using hardware::ICamera;
119using hardware::ICameraClient;
120using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800121using hardware::camera2::ICameraInjectionCallback;
122using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800123using hardware::camera2::utils::CameraIdAndSessionConfiguration;
124using hardware::camera2::utils::ConcurrentCameraIdCombination;
Biswarup Pal37a75182024-01-16 15:53:35 +0000125
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -0700126namespace flags = com::android::internal::camera::flags;
Biswarup Pal37a75182024-01-16 15:53:35 +0000127namespace vd_flags = android::companion::virtualdevice::flags;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800128
Mathias Agopian65ab4712010-07-14 17:59:35 -0700129// ----------------------------------------------------------------------------
130// Logging support -- this is for debugging only
131// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700132volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700133
Steve Blockb8a80522011-12-20 16:23:08 +0000134#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
135#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700136
137static void setLogLevel(int level) {
138 android_atomic_write(level, &gLogLevel);
139}
140
Henri Chataingbcb99452023-11-01 17:40:30 +0000141int32_t format_as(CameraService::StatusInternal s) {
142 return fmt::underlying(s);
143}
144
Mathias Agopian65ab4712010-07-14 17:59:35 -0700145// ----------------------------------------------------------------------------
146
Austin Borger249e6592024-03-10 22:28:11 -0700147// Permission strings (references to AttributionAndPermissionUtils for brevity)
148static const std::string &sDumpPermission =
149 AttributionAndPermissionUtils::sDumpPermission;
150static const std::string &sManageCameraPermission =
151 AttributionAndPermissionUtils::sManageCameraPermission;
152static const std::string &sCameraSendSystemEventsPermission =
153 AttributionAndPermissionUtils::sCameraSendSystemEventsPermission;
154static const std::string &sCameraInjectExternalCameraPermission =
155 AttributionAndPermissionUtils::sCameraInjectExternalCameraPermission;
156
Kunal Malhotrabfc96052023-02-28 23:25:34 +0000157// Constant integer for FGS Logging, used to denote the API type for logger
158static const int LOG_FGS_CAMERA_API = 1;
Rucha Katakwardf223072021-06-15 10:21:00 -0700159const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800160static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
161static constexpr int32_t kSystemNativeClientState =
162 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Austin Borgered99f642023-06-01 16:51:35 -0700163static const std::string kServiceName("cameraserver");
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700164
Austin Borgered99f642023-06-01 16:51:35 -0700165const std::string CameraService::kOfflineDevice("offline-");
166const std::string CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700167
Rucha Katakward9ea6452021-05-06 11:57:16 -0700168// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700169static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700170
Austin Borger74fca042022-05-23 12:41:21 -0700171CameraService::CameraService(
Austin Borger249e6592024-03-10 22:28:11 -0700172 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,
173 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils) :
174 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils == nullptr ?
175 std::make_shared<AttributionAndPermissionUtils>()\
176 : attributionAndPermissionUtils),
Austin Borger74fca042022-05-23 12:41:21 -0700177 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
178 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800179 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800180 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700181 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700182 mSoundRef(0), mInitialized(false),
183 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000184 ALOGI("CameraService started (pid=%d)", getpid());
Austin Borger249e6592024-03-10 22:28:11 -0700185 mAttributionAndPermissionUtils->setCameraService(this);
Ruben Brunkcc776712015-02-17 20:18:47 -0800186 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700187 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
188 if (mMemFd == -1) {
189 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
190 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700191}
192
Charles Chena7b613c2023-01-24 21:57:33 +0000193// Enable processes with isolated AID to request the binder
194void CameraService::instantiate() {
195 CameraService::publish(true);
196}
197
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800198void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700199 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800200 return;
201 }
202
203 ALOGV("appops service registered. setting camera audio restriction");
204 mAppOps.setCameraAudioRestriction(mAudioRestriction);
205}
206
Iliyan Malchev8951a972011-04-14 16:55:59 -0700207void CameraService::onFirstRef()
208{
Ruben Brunkcc776712015-02-17 20:18:47 -0800209 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800210
Iliyan Malchev8951a972011-04-14 16:55:59 -0700211 BnCameraService::onFirstRef();
212
Ruben Brunk99e69712015-05-26 17:25:07 -0700213 // Update battery life tracking if service is restarting
214 BatteryNotifier& notifier(BatteryNotifier::getInstance());
215 notifier.noteResetCamera();
216 notifier.noteResetFlashlight();
217
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800218 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800219
Emilian Peevf53f66e2017-04-11 14:29:43 +0100220 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800221 if (res == OK) {
222 mInitialized = true;
223 }
224
Svet Ganova453d0d2018-01-11 15:37:58 -0800225 mUidPolicy = new UidPolicy(this);
226 mUidPolicy->registerSelf();
Austin Borger249e6592024-03-10 22:28:11 -0700227 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this, mAttributionAndPermissionUtils);
Michael Grooverd1d435a2018-12-18 17:39:42 -0800228 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800229 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800230
231 // appops function setCamerAudioRestriction uses getService which
232 // is blocking till the appops service is ready. To enable early
233 // boot availability for cameraservice, use checkService which is
234 // non blocking and register for notifications
235 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700236 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800237 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700238 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800239 } else {
240 mAppOps.setCameraAudioRestriction(mAudioRestriction);
241 }
242
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700243 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
244 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000245 // Deprecated, so it will fail to register on newer devices
246 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700247 __FUNCTION__);
248 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700249
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700250 if (!AidlCameraService::registerService(this)) {
251 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
252 }
253
Shuzhen Wang24b44152019-09-20 10:38:11 -0700254 // This needs to be last call in this function, so that it's as close to
255 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700256 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700257 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800258}
259
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800260status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800261 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100262
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800263 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000264 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800265 {
266 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800267
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800268 if (nullptr == mCameraProviderManager.get()) {
269 mCameraProviderManager = new CameraProviderManager();
270 res = mCameraProviderManager->initialize(this);
271 if (res != OK) {
272 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
273 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700274 logServiceError("Unable to initialize camera provider manager",
275 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800276 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100277 }
278 }
279
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800280 // Setup vendor tags before we call get_camera_info the first time
281 // because HAL might need to setup static vendor keys in get_camera_info
282 // TODO: maybe put this into CameraProviderManager::initialize()?
283 mCameraProviderManager->setUpVendorTags();
284
285 if (nullptr == mFlashlight.get()) {
286 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700287 }
288
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800289 res = mFlashlight->findFlashUnits();
290 if (res != OK) {
291 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
292 }
293
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000294 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800295 }
296
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800297 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700298 if (getCameraState(cameraId) == nullptr) {
299 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800300 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000301 if (unavailPhysicalIds.count(cameraId) > 0) {
302 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700303 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000304 }
305 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800306 }
307
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700308 // Derive primary rear/front cameras, and filter their charactierstics.
309 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700310 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700311 // Assume internal cameras are advertised from the same
312 // provider. If multiple providers are registered at different time,
313 // and each provider contains multiple internal color cameras, the current
314 // logic may filter the characteristics of more than one front/rear color
315 // cameras.
316 Mutex::Autolock l(mServiceLock);
317 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700318 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700319
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800320 return OK;
321}
322
Austin Borgered99f642023-06-01 16:51:35 -0700323void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700324 SystemCameraKind systemCameraKind) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000325 // Get the device id and app-visible camera id for the given HAL-visible camera id.
326 auto [deviceId, mappedCameraId] =
327 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
328
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800329 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800330 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700331 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
332 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000333 ALOGV("%s: Skipping torch callback for system-only camera device %s",
334 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700335 continue;
336 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000337
Austin Borgere8e2c422022-05-12 13:45:24 -0700338 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Biswarup Pal37a75182024-01-16 15:53:35 +0000339 mappedCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700340 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
341 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Biswarup Pal37a75182024-01-16 15:53:35 +0000342
343 // Only cameras of the default device can be remapped to a different camera (using
344 // remapCameraIds method), so do the following only if the camera is associated with the
345 // default device.
346 if (deviceId == kDefaultDeviceId) {
347 // For the default device, also trigger the torch callbacks for cameras that were
348 // remapped to the current cameraId for the specific package that this listener belongs
349 // to.
350 std::vector<std::string> remappedCameraIds =
351 findOriginalIdsForRemappedCameraId(cameraId, i->getListenerUid());
352 for (auto &remappedCameraId: remappedCameraIds) {
353 ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
354 remappedCameraId, kDefaultDeviceId);
355 i->handleBinderStatus(ret,
356 "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
357 __FUNCTION__, i->getListenerUid(), i->getListenerPid(),
358 ret.exceptionCode());
359 }
malikakash82ed4352023-07-21 22:44:34 +0000360 }
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800361 }
362}
363
Mathias Agopian65ab4712010-07-14 17:59:35 -0700364CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800365 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800366 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800367 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800368 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700369}
370
Emilian Peevaee727d2017-05-04 16:35:48 +0100371void CameraService::onNewProviderRegistered() {
372 enumerateProviders();
373}
374
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700375void CameraService::filterAPI1SystemCameraLocked(
376 const std::vector<std::string> &normalDeviceIds) {
377 mNormalDeviceIdsWithoutSystemCamera.clear();
Biswarup Pal37a75182024-01-16 15:53:35 +0000378 for (auto &cameraId : normalDeviceIds) {
379 if (vd_flags::camera_device_awareness()) {
380 CameraMetadata cameraInfo;
381 status_t res = mCameraProviderManager->getCameraCharacteristics(
382 cameraId, false, &cameraInfo, false);
383 int32_t deviceId = kDefaultDeviceId;
384 if (res != OK) {
385 ALOGW("%s: Not able to get camera characteristics for camera id %s",
386 __FUNCTION__, cameraId.c_str());
387 } else {
388 deviceId = getDeviceId(cameraInfo);
389 }
390 // Cameras associated with non-default device id's (i.e., virtual cameras) can never be
391 // system cameras, so skip for non-default device id's.
392 if (deviceId != kDefaultDeviceId) {
393 continue;
394 }
395 }
396
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700397 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Biswarup Pal37a75182024-01-16 15:53:35 +0000398 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
399 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700400 continue;
401 }
402 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700403 // All system camera ids will necessarily come after public camera
404 // device ids as per the HAL interface contract.
405 break;
406 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000407 mNormalDeviceIdsWithoutSystemCamera.push_back(cameraId);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700408 }
409 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
410 mNormalDeviceIdsWithoutSystemCamera.size());
411}
412
Austin Borgered99f642023-06-01 16:51:35 -0700413status_t CameraService::getSystemCameraKind(const std::string& cameraId,
414 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700415 auto state = getCameraState(cameraId);
416 if (state != nullptr) {
417 *kind = state->getSystemCameraKind();
418 return OK;
419 }
420 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700421 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700422}
423
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800424void CameraService::updateCameraNumAndIds() {
425 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700426 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
427 // Excludes hidden secure cameras
428 mNumberOfCameras =
429 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
430 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800431 mNormalDeviceIds =
432 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700433 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800434}
435
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700436void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700437 // To claim to be S Performance primary cameras, the cameras must be
438 // backward compatible. So performance class primary camera Ids must be API1
439 // compatible.
440 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
441 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
442 int facing = -1;
443 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800444 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -0700445 getDeviceVersion(cameraId, /*overrideToPortrait*/false, /*out*/&portraitRotation,
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800446 /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700447 if (facing == -1) {
448 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
449 return;
450 }
451
452 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
453 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700454 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
455 if (res == OK) {
456 mPerfClassPrimaryCameraIds.insert(cameraId);
457 } else {
458 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
459 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
460 break;
461 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700462
463 if (facing == hardware::CAMERA_FACING_BACK) {
464 firstRearCameraSeen = true;
465 }
466 if (facing == hardware::CAMERA_FACING_FRONT) {
467 firstFrontCameraSeen = true;
468 }
469 }
470
471 if (firstRearCameraSeen && firstFrontCameraSeen) {
472 break;
473 }
474 }
475}
476
Austin Borgered99f642023-06-01 16:51:35 -0700477void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700478 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100479 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
480 if (res != OK) {
481 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
482 return;
483 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000484 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700485 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
486 if (res != OK) {
487 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
488 return;
489 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000490 std::vector<std::string> physicalCameraIds;
491 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700492 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100493 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700494 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100495 }
496
497 {
498 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700499 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000500 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100501 }
502
Austin Borgered99f642023-06-01 16:51:35 -0700503 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100504 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700505 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800506
Austin Borgered99f642023-06-01 16:51:35 -0700507 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100508 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800509
510 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700511 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100512}
513
Austin Borgered99f642023-06-01 16:51:35 -0700514void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800515 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700516 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100517 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700518 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100519 }
520
521 {
522 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700523 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100524 }
525}
526
Austin Borgered99f642023-06-01 16:51:35 -0700527void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800528 CameraDeviceStatus newHalStatus) {
529 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700530 cameraId.c_str(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700531
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800532 StatusInternal newStatus = mapToInternal(newHalStatus);
533
Austin Borgered99f642023-06-01 16:51:35 -0700534 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800535
536 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700537 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100538 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700539 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100540
541 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700542 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100543
Austin Borgered99f642023-06-01 16:51:35 -0700544 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700545 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700546 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700547 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700548 return;
549 }
550
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800551 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800552
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800553 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800554 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700555 return;
556 }
557
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800558 if (newStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000559 logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
560 oldStatus, newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800561 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
562 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700563 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000564 mVirtualDeviceCameraIdMapper.removeCamera(cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800565
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800566 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700567 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800568 // Don't do this in updateStatus to avoid deadlock over mServiceLock
569 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700570
Ruben Brunkcc776712015-02-17 20:18:47 -0800571 // Remove cached shim parameters
572 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700573
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800574 // Remove online as well as offline client from the list of active clients,
575 // if they are present
Austin Borgered99f642023-06-01 16:51:35 -0700576 clientToDisconnectOnline = removeClientLocked(cameraId);
577 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700578 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800579
Austin Borgered99f642023-06-01 16:51:35 -0700580 disconnectClient(cameraId, clientToDisconnectOnline);
581 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700582
Austin Borgered99f642023-06-01 16:51:35 -0700583 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800584 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800585 if (oldStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000586 logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
587 oldStatus, newStatus));
Ruben Brunka8ca9152015-04-07 14:23:40 -0700588 }
Austin Borgered99f642023-06-01 16:51:35 -0700589 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700590 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800591}
Igor Murashkincba2c162013-03-20 15:56:31 -0700592
Austin Borgered99f642023-06-01 16:51:35 -0700593void CameraService::onDeviceStatusChanged(const std::string& id,
594 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800595 CameraDeviceStatus newHalStatus) {
596 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700597 __FUNCTION__, id.c_str(), physicalId.c_str(), newHalStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800598
599 StatusInternal newStatus = mapToInternal(newHalStatus);
600
601 std::shared_ptr<CameraState> state = getCameraState(id);
602
603 if (state == nullptr) {
604 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700605 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800606 return;
607 }
608
609 StatusInternal logicalCameraStatus = state->getStatus();
610 if (logicalCameraStatus != StatusInternal::PRESENT &&
611 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
612 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Austin Borgered99f642023-06-01 16:51:35 -0700613 __FUNCTION__, physicalId.c_str(), newHalStatus, logicalCameraStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800614 return;
615 }
616
617 bool updated = false;
618 if (newStatus == StatusInternal::PRESENT) {
619 updated = state->removeUnavailablePhysicalId(physicalId);
620 } else {
621 updated = state->addUnavailablePhysicalId(physicalId);
622 }
623
624 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700625 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800626 if (newStatus == StatusInternal::PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000627 logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800628 } else {
Henri Chataingbcb99452023-11-01 17:40:30 +0000629 logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800630 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700631 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
632 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
633 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700634 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700635 return;
636 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800637 Mutex::Autolock lock(mStatusListenerLock);
638 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700639 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
640 listener->getListenerPid(), listener->getListenerUid())) {
641 ALOGV("Skipping discovery callback for system-only camera device %s",
642 id.c_str());
643 continue;
644 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700645 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Biswarup Pal37a75182024-01-16 15:53:35 +0000646 mapToInterface(newStatus), id, physicalId, kDefaultDeviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700647 listener->handleBinderStatus(ret,
648 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
649 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
650 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800651 }
652 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700653}
654
Austin Borgered99f642023-06-01 16:51:35 -0700655void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800656 if (clientToDisconnect.get() != nullptr) {
657 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700658 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800659 // Notify the client of disconnection
660 clientToDisconnect->notifyError(
661 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
662 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800663 clientToDisconnect->disconnect();
664 }
665}
666
Austin Borgered99f642023-06-01 16:51:35 -0700667void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800668 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700669 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
670 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
671 if (res != OK) {
672 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700673 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700674 return;
675 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800676 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700677 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800678}
679
Austin Borgered99f642023-06-01 16:51:35 -0700680void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700681 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
682 Mutex::Autolock al(mTorchStatusMutex);
683 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
684}
685
Austin Borgered99f642023-06-01 16:51:35 -0700686void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800687 int32_t newStrengthLevel) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000688 // Get the device id and app-visible camera id for the given HAL-visible camera id.
689 auto [deviceId, mappedCameraId] =
690 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
691
Rucha Katakwar38284522021-11-10 11:25:21 -0800692 Mutex::Autolock lock(mStatusListenerLock);
693 for (auto& i : mListenerList) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000694 auto ret = i->getListener()->onTorchStrengthLevelChanged(mappedCameraId,
695 newStrengthLevel, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700696 i->handleBinderStatus(ret,
697 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
698 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800699 }
700}
701
Austin Borgered99f642023-06-01 16:51:35 -0700702void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700703 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800704 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700705 __FUNCTION__, cameraId.c_str(), newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800706
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800707 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800708 status_t res = getTorchStatusLocked(cameraId, &status);
709 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700710 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700711 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800712 return;
713 }
714 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800715 return;
716 }
717
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800718 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800719 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800720 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
721 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800722 return;
723 }
724
Ruben Brunkcc776712015-02-17 20:18:47 -0800725 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700726 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700727 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700728 auto iter = mTorchUidMap.find(cameraId);
729 if (iter != mTorchUidMap.end()) {
730 int oldUid = iter->second.second;
731 int newUid = iter->second.first;
732 BatteryNotifier& notifier(BatteryNotifier::getInstance());
733 if (oldUid != newUid) {
734 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800735 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700736 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700737 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800738 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700739 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700740 }
741 iter->second.second = newUid;
742 } else {
743 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800744 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700745 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700746 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700747 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700748 }
749 }
750 }
751 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700752 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800753}
754
Austin Borger249e6592024-03-10 22:28:11 -0700755bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700756 // Returns false if this is not an automotive device type.
757 if (!isAutomotiveDevice())
758 return false;
759
760 // Returns false if no camera id is provided.
Austin Borger1c1bee02023-06-01 16:51:35 -0700761 if (cam_id.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700762 return false;
763
764 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
765 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
766 // This isn't a known camera ID, so it's not a system camera.
767 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
768 return false;
769 }
770
771 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
772 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
773 return false;
774 }
775
776 CameraMetadata cameraInfo;
777 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borger1c1bee02023-06-01 16:51:35 -0700778 cam_id, false, &cameraInfo, false);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700779 if (res != OK){
780 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
781 cam_id.c_str());
782 return false;
783 }
784
785 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
786 if (auto_location.count != 1)
787 return false;
788
789 uint8_t location = auto_location.data.u8[0];
790 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
791 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
792 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
793 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
794 return false;
795 }
796
797 return true;
798}
799
Biswarup Pal37a75182024-01-16 15:53:35 +0000800Status CameraService::getNumberOfCameras(int32_t type, int32_t deviceId, int32_t devicePolicy,
801 int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700802 ATRACE_CALL();
Biswarup Pal37a75182024-01-16 15:53:35 +0000803 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
804 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
805 *numCameras = mVirtualDeviceCameraIdMapper.getNumberOfCameras(deviceId);
806 return Status::ok();
807 }
808
Emilian Peevaee727d2017-05-04 16:35:48 +0100809 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700810 bool hasSystemCameraPermissions =
Austin Borger22c5c852024-03-08 13:31:36 -0800811 hasPermissionsForSystemCamera(std::string(), getCallingPid(),
812 getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700813 switch (type) {
814 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700815 if (hasSystemCameraPermissions) {
816 *numCameras = static_cast<int>(mNormalDeviceIds.size());
817 } else {
818 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
819 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800820 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700821 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700822 if (hasSystemCameraPermissions) {
823 *numCameras = mNumberOfCameras;
824 } else {
825 *numCameras = mNumberOfCamerasWithoutSystemCamera;
826 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800827 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700828 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800829 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700830 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800831 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
832 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700833 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800834 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700835}
836
malikakash73125c62023-07-21 22:44:34 +0000837Status CameraService::remapCameraIds(const hardware::CameraIdRemapping& cameraIdRemapping) {
Austin Borgered99f642023-06-01 16:51:35 -0700838 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -0800839 const int pid = getCallingPid();
840 const int uid = getCallingUid();
malikakash82ed4352023-07-21 22:44:34 +0000841 ALOGE("%s: Permission Denial: can't configure camera ID mapping pid=%d, uid=%d",
842 __FUNCTION__, pid, uid);
843 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
844 "Permission Denial: no permission to configure camera id mapping");
845 }
846 TCameraIdRemapping cameraIdRemappingMap{};
malikakash214f6e62023-08-10 23:50:56 +0000847 binder::Status parseStatus = parseCameraIdRemapping(cameraIdRemapping, &cameraIdRemappingMap);
malikakash82ed4352023-07-21 22:44:34 +0000848 if (!parseStatus.isOk()) {
849 return parseStatus;
850 }
851 remapCameraIds(cameraIdRemappingMap);
852 return Status::ok();
853}
854
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700855Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
Biswarup Pal37a75182024-01-16 15:53:35 +0000856 int32_t deviceId, int32_t devicePolicy,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700857 /* out */
858 hardware::camera2::impl::CameraMetadataNative* request) {
859 ATRACE_CALL();
860
861 if (!flags::feature_combination_query()) {
862 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
863 "Camera subsystem doesn't support this method!");
864 }
865 if (!mInitialized) {
866 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
867 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
868 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
869 }
870
Biswarup Pal37a75182024-01-16 15:53:35 +0000871 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
872 devicePolicy, getCallingUid());
873 if (!cameraIdOptional.has_value()) {
874 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
875 unresolvedCameraId.c_str(), deviceId);
876 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
877 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
878 }
879 std::string cameraId = cameraIdOptional.value();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700880
881 binder::Status res;
882 if (request == nullptr) {
883 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
884 "Camera %s: Error creating default request", cameraId.c_str());
885 return res;
886 }
887 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
888 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
889 cameraId, templateId, &tempId);
890 if (!res.isOk()) {
891 ALOGE("%s: Camera %s: failed to map request Template %d",
892 __FUNCTION__, cameraId.c_str(), templateId);
893 return res;
894 }
895
896 if (shouldRejectSystemCameraConnection(cameraId)) {
897 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
898 "request for system only device %s: ", cameraId.c_str());
899 }
900
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700901 CameraMetadata metadata;
902 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
903 if (err == OK) {
904 request->swap(metadata);
905 } else if (err == BAD_VALUE) {
906 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
907 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
908 cameraId.c_str(), templateId, strerror(-err), err);
909 } else {
910 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
911 "Camera %s: Error creating default request for template %d: %s (%d)",
912 cameraId.c_str(), templateId, strerror(-err), err);
913 }
914 return res;
915}
916
917Status CameraService::isSessionConfigurationWithParametersSupported(
918 const std::string& unresolvedCameraId,
919 const SessionConfiguration& sessionConfiguration,
Biswarup Pal37a75182024-01-16 15:53:35 +0000920 int32_t deviceId, int32_t devicePolicy,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700921 /*out*/
922 bool* supported) {
923 ATRACE_CALL();
924
925 if (!flags::feature_combination_query()) {
926 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
927 "Camera subsystem doesn't support this method!");
928 }
929 if (!mInitialized) {
930 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
931 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
932 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
933 }
934
Biswarup Pal37a75182024-01-16 15:53:35 +0000935 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
936 devicePolicy, getCallingUid());
937 if (!cameraIdOptional.has_value()) {
938 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
939 unresolvedCameraId.c_str(), deviceId);
940 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
941 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
942 }
943 std::string cameraId = cameraIdOptional.value();
944
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700945 if (supported == nullptr) {
946 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
947 unresolvedCameraId.c_str());
948 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
949 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
950 }
951
952 if (shouldRejectSystemCameraConnection(cameraId)) {
953 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
954 "session configuration with parameters support for system only device %s: ",
955 cameraId.c_str());
956 }
957
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700958 *supported = false;
959 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(cameraId.c_str(),
960 sessionConfiguration, /*mOverrideForPerfClass*/false, /*checkSessionParams*/true,
961 supported);
962 binder::Status res;
963 switch (ret) {
964 case OK:
965 // Expected, do nothing.
966 break;
967 case INVALID_OPERATION: {
968 std::string msg = fmt::sprintf(
969 "Camera %s: Session configuration query not supported!",
970 cameraId.c_str());
971 ALOGD("%s: %s", __FUNCTION__, msg.c_str());
972 res = STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
973 }
974
975 break;
976 default: {
977 std::string msg = fmt::sprintf( "Camera %s: Error: %s (%d)", cameraId.c_str(),
978 strerror(-ret), ret);
979 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
980 res = STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT,
981 msg.c_str());
982 }
983 }
984
985 return res;
986}
987
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800988Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +0000989 int targetSdkVersion, bool overrideToPortrait,
990 const SessionConfiguration& sessionConfiguration, int32_t deviceId, int32_t devicePolicy,
991 /*out*/ CameraMetadata* outMetadata) {
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800992 ATRACE_CALL();
993
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800994 if (outMetadata == nullptr) {
995 std::string msg =
996 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
997 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
998 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
999 }
1000
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001001 if (!mInitialized) {
1002 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1003 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
1004 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
1005 }
1006
Biswarup Pal37a75182024-01-16 15:53:35 +00001007 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001008 devicePolicy, getCallingUid());
Biswarup Pal37a75182024-01-16 15:53:35 +00001009 if (!cameraIdOptional.has_value()) {
1010 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001011 unresolvedCameraId.c_str(), deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001012 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1013 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1014 }
1015 std::string cameraId = cameraIdOptional.value();
1016
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001017 if (shouldRejectSystemCameraConnection(cameraId)) {
1018 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1019 "Unable to retrieve camera"
1020 "characteristics for system only device %s: ",
1021 cameraId.c_str());
1022 }
1023
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001024 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1025 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
1026
1027 status_t ret = mCameraProviderManager->getSessionCharacteristics(
1028 cameraId, sessionConfiguration, overrideForPerfClass, overrideToPortrait, outMetadata);
1029
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001030 switch (ret) {
1031 case OK:
1032 // Expected, no handling needed.
1033 break;
1034 case INVALID_OPERATION: {
1035 std::string msg = fmt::sprintf(
1036 "Camera %s: Session characteristics query not supported!",
1037 cameraId.c_str());
1038 ALOGD("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001039 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1040 outMetadata->clear();
1041 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1042 }
1043 break;
1044 case NAME_NOT_FOUND: {
1045 std::string msg = fmt::sprintf(
1046 "Camera %s: Unknown camera ID.",
1047 cameraId.c_str());
1048 ALOGD("%s: %s", __FUNCTION__, msg.c_str());
1049 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1050 outMetadata->clear();
1051 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001052 }
1053 break;
1054 default: {
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001055 std::string msg = fmt::sprintf(
1056 "Unable to retrieve session characteristics for camera device %s: "
1057 "Error: %s (%d)",
1058 cameraId.c_str(), strerror(-ret), ret);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001059 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001060 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1061 outMetadata->clear();
1062 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001063 }
1064 }
1065
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001066 return filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
1067}
1068
1069Status CameraService::filterSensitiveMetadataIfNeeded(
1070 const std::string& cameraId, CameraMetadata* metadata) {
1071 int callingPid = getCallingPid();
1072 int callingUid = getCallingUid();
1073
1074 if (callingPid == getpid()) {
1075 // Caller is cameraserver; no need to remove keys
1076 return Status::ok();
1077 }
1078
1079 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1080 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1081 ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
1082 metadata->clear();
1083 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1084 "Unable to retrieve camera kind for device %s", cameraId.c_str());
1085 }
1086 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
1087 // Attempting to query system only camera without system camera permission would have
1088 // failed the shouldRejectSystemCameraConnection in the caller. So if we get here
1089 // for a system only camera, then the caller has the required permission.
1090 // No need to remove keys
1091 return Status::ok();
1092 }
1093
1094 std::vector<int32_t> tagsRemoved;
1095 bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid);
1096 if (hasCameraPermission) {
1097 // Caller has camera permission; no need to remove keys
1098 return Status::ok();
1099 }
1100
1101 status_t ret = metadata->removePermissionEntries(
1102 mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1103 if (ret != OK) {
1104 metadata->clear();
1105 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1106 "Failed to remove camera characteristics needing camera permission "
1107 "for device %s:%s (%d)",
1108 cameraId.c_str(), strerror(-ret), ret);
1109 }
1110
1111 if (!tagsRemoved.empty()) {
1112 ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1113 tagsRemoved.data(), tagsRemoved.size());
1114 if (ret != OK) {
1115 metadata->clear();
1116 return STATUS_ERROR_FMT(
1117 ERROR_INVALID_OPERATION,
1118 "Failed to insert camera keys needing permission for device %s: %s (%d)",
1119 cameraId.c_str(), strerror(-ret), ret);
1120 }
1121 }
1122 return Status::ok();
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001123}
1124
malikakash82ed4352023-07-21 22:44:34 +00001125Status CameraService::parseCameraIdRemapping(
1126 const hardware::CameraIdRemapping& cameraIdRemapping,
malikakash214f6e62023-08-10 23:50:56 +00001127 /* out */ TCameraIdRemapping* cameraIdRemappingMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001128 std::string packageName;
1129 std::string cameraIdToReplace, updatedCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001130 for (const auto& packageIdRemapping: cameraIdRemapping.packageIdRemappings) {
malikakash82ed4352023-07-21 22:44:34 +00001131 packageName = packageIdRemapping.packageName;
malikakash0894f5b2023-08-10 22:46:47 +00001132 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001133 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1134 "CameraIdRemapping: Package name cannot be empty");
1135 }
malikakash214f6e62023-08-10 23:50:56 +00001136 if (packageIdRemapping.cameraIdsToReplace.size()
1137 != packageIdRemapping.updatedCameraIds.size()) {
malikakash82ed4352023-07-21 22:44:34 +00001138 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1139 "CameraIdRemapping: Mismatch in CameraId Remapping lists sizes for package %s",
malikakash73125c62023-07-21 22:44:34 +00001140 packageName.c_str());
malikakash82ed4352023-07-21 22:44:34 +00001141 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001142 for (size_t i = 0; i < packageIdRemapping.cameraIdsToReplace.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -07001143 cameraIdToReplace = packageIdRemapping.cameraIdsToReplace[i];
1144 updatedCameraId = packageIdRemapping.updatedCameraIds[i];
malikakash0894f5b2023-08-10 22:46:47 +00001145 if (cameraIdToReplace.empty() || updatedCameraId.empty()) {
malikakash214f6e62023-08-10 23:50:56 +00001146 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1147 "CameraIdRemapping: Camera Id cannot be empty for package %s",
Austin Borgered99f642023-06-01 16:51:35 -07001148 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001149 }
1150 if (cameraIdToReplace == updatedCameraId) {
1151 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1152 "CameraIdRemapping: CameraIdToReplace cannot be the same"
1153 " as updatedCameraId for %s",
Austin Borgered99f642023-06-01 16:51:35 -07001154 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001155 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001156
1157 // Do not allow any camera remapping that involves a virtual camera.
1158 auto [deviceIdForCameraToReplace, _] =
1159 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1160 cameraIdToReplace);
1161 if (deviceIdForCameraToReplace != kDefaultDeviceId) {
1162 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1163 "CameraIdRemapping: CameraIdToReplace cannot be a virtual camera");
1164 }
1165 [[maybe_unused]] auto [deviceIdForUpdatedCamera, unusedMappedCameraId] =
1166 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(updatedCameraId);
1167 if (deviceIdForUpdatedCamera != kDefaultDeviceId) {
1168 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1169 "CameraIdRemapping: UpdatedCameraId cannot be a virtual camera");
1170 }
1171
malikakash214f6e62023-08-10 23:50:56 +00001172 (*cameraIdRemappingMap)[packageName][cameraIdToReplace] = updatedCameraId;
malikakash82ed4352023-07-21 22:44:34 +00001173 }
1174 }
1175 return Status::ok();
1176}
1177
1178void CameraService::remapCameraIds(const TCameraIdRemapping& cameraIdRemapping) {
1179 // Acquire mServiceLock and prevent other clients from connecting
1180 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1181 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1182
malikakashedb38962023-09-06 00:03:35 +00001183 // Collect all existing clients for camera Ids that are being
1184 // remapped in the new cameraIdRemapping, but only if they were being used by a
1185 // targeted packageName.
malikakash82ed4352023-07-21 22:44:34 +00001186 std::vector<sp<BasicClient>> clientsToDisconnect;
Austin Borgered99f642023-06-01 16:51:35 -07001187 std::vector<std::string> cameraIdsToUpdate;
malikakash82ed4352023-07-21 22:44:34 +00001188 for (const auto& [packageName, injectionMap] : cameraIdRemapping) {
1189 for (auto& [id0, id1] : injectionMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001190 ALOGI("%s: UPDATE:= %s: %s: %s", __FUNCTION__, packageName.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001191 id0.c_str(), id1.c_str());
1192 auto clientDescriptor = mActiveClientManager.get(id0);
1193 if (clientDescriptor != nullptr) {
1194 sp<BasicClient> clientSp = clientDescriptor->getValue();
1195 if (clientSp->getPackageName() == packageName) {
malikakashedb38962023-09-06 00:03:35 +00001196 // This camera is being used by a targeted packageName and
1197 // being remapped to a new camera Id. We should disconnect it.
malikakash82ed4352023-07-21 22:44:34 +00001198 clientsToDisconnect.push_back(clientSp);
1199 cameraIdsToUpdate.push_back(id0);
1200 }
1201 }
1202 }
1203 }
1204
malikakashedb38962023-09-06 00:03:35 +00001205 for (auto& clientSp : clientsToDisconnect) {
malikakashf4c80f22023-09-25 21:50:28 +00001206 // Notify the clients about the disconnection.
1207 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
malikakashedb38962023-09-06 00:03:35 +00001208 CaptureResultExtras{});
1209 }
malikakash82ed4352023-07-21 22:44:34 +00001210
1211 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1212 // blocking other clients from connecting in mServiceLockWrapper if held.
1213 mServiceLock.unlock();
1214
malikakashedb38962023-09-06 00:03:35 +00001215 // Clear calling identity for disconnect() PID checks.
Austin Borger22c5c852024-03-08 13:31:36 -08001216 int64_t token = clearCallingIdentity();
malikakashedb38962023-09-06 00:03:35 +00001217
malikakash82ed4352023-07-21 22:44:34 +00001218 // Disconnect clients.
1219 for (auto& clientSp : clientsToDisconnect) {
malikakashedb38962023-09-06 00:03:35 +00001220 // This also triggers a call to updateStatus() which also reads mCameraIdRemapping
1221 // and requires mCameraIdRemappingLock.
malikakash82ed4352023-07-21 22:44:34 +00001222 clientSp->disconnect();
1223 }
1224
malikakashedb38962023-09-06 00:03:35 +00001225 // Invoke destructors (which call disconnect()) now while we don't hold the mServiceLock.
1226 clientsToDisconnect.clear();
1227
Austin Borger22c5c852024-03-08 13:31:36 -08001228 restoreCallingIdentity(token);
malikakash82ed4352023-07-21 22:44:34 +00001229 mServiceLock.lock();
malikakashedb38962023-09-06 00:03:35 +00001230
1231 {
1232 Mutex::Autolock lock(mCameraIdRemappingLock);
1233 // Update mCameraIdRemapping.
1234 mCameraIdRemapping.clear();
1235 mCameraIdRemapping.insert(cameraIdRemapping.begin(), cameraIdRemapping.end());
1236 }
malikakash82ed4352023-07-21 22:44:34 +00001237}
1238
malikakash22af94c2023-12-04 18:13:14 +00001239Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001240 const std::string& cameraId,
1241 const CameraMetadata& sessionParams) {
1242 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001243 const int pid = getCallingPid();
1244 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001245 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1246 __FUNCTION__, pid, uid);
1247 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1248 "Permission Denial: no permission to inject session params");
1249 }
1250
Biswarup Pal37a75182024-01-16 15:53:35 +00001251 // Do not allow session params injection for a virtual camera.
1252 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1253 if (deviceId != kDefaultDeviceId) {
1254 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1255 "Cannot inject session params for a virtual camera");
1256 }
1257
malikakash22af94c2023-12-04 18:13:14 +00001258 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1259 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1260
1261 auto clientDescriptor = mActiveClientManager.get(cameraId);
1262 if (clientDescriptor == nullptr) {
1263 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1264 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1265 "No active client for camera id %s", cameraId.c_str());
1266 }
1267
1268 sp<BasicClient> clientSp = clientDescriptor->getValue();
1269 status_t res = clientSp->injectSessionParams(sessionParams);
1270
1271 if (res != OK) {
1272 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1273 "Error injecting session params into camera \"%s\": %s (%d)",
1274 cameraId.c_str(), strerror(-res), res);
1275 }
1276 return Status::ok();
1277}
1278
Austin Borgered99f642023-06-01 16:51:35 -07001279std::vector<std::string> CameraService::findOriginalIdsForRemappedCameraId(
1280 const std::string& inputCameraId, int clientUid) {
1281 std::string packageName = getPackageNameFromUid(clientUid);
1282 std::vector<std::string> cameraIds;
malikakash82ed4352023-07-21 22:44:34 +00001283 Mutex::Autolock lock(mCameraIdRemappingLock);
1284 if (auto packageMapIter = mCameraIdRemapping.find(packageName);
1285 packageMapIter != mCameraIdRemapping.end()) {
1286 for (auto& [id0, id1]: packageMapIter->second) {
1287 if (id1 == inputCameraId) {
1288 cameraIds.push_back(id0);
1289 }
1290 }
1291 }
1292 return cameraIds;
1293}
1294
Austin Borgered99f642023-06-01 16:51:35 -07001295std::string CameraService::resolveCameraId(
1296 const std::string& inputCameraId,
malikakashedb38962023-09-06 00:03:35 +00001297 int clientUid,
Austin Borgered99f642023-06-01 16:51:35 -07001298 const std::string& packageName) {
1299 std::string packageNameVal = packageName;
malikakashedb38962023-09-06 00:03:35 +00001300 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001301 packageNameVal = getPackageNameFromUid(clientUid);
1302 }
malikakash65d20692023-09-07 01:06:33 +00001303 if (clientUid < AID_APP_START || packageNameVal.empty()) {
malikakashedb38962023-09-06 00:03:35 +00001304 // We shouldn't remap cameras for processes with system/vendor UIDs.
1305 return inputCameraId;
1306 }
malikakash82ed4352023-07-21 22:44:34 +00001307 Mutex::Autolock lock(mCameraIdRemappingLock);
1308 if (auto packageMapIter = mCameraIdRemapping.find(packageNameVal);
1309 packageMapIter != mCameraIdRemapping.end()) {
malikakash82ed4352023-07-21 22:44:34 +00001310 auto packageMap = packageMapIter->second;
1311 if (auto replacementIdIter = packageMap.find(inputCameraId);
1312 replacementIdIter != packageMap.end()) {
malikakashedb38962023-09-06 00:03:35 +00001313 ALOGI("%s: resolveCameraId: remapping cameraId %s for %s to %s",
malikakash82ed4352023-07-21 22:44:34 +00001314 __FUNCTION__, inputCameraId.c_str(),
malikakashedb38962023-09-06 00:03:35 +00001315 packageNameVal.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001316 replacementIdIter->second.c_str());
1317 return replacementIdIter->second;
1318 }
1319 }
1320 return inputCameraId;
1321}
1322
Biswarup Pal37a75182024-01-16 15:53:35 +00001323std::optional<std::string> CameraService::resolveCameraId(
1324 const std::string& inputCameraId,
1325 int32_t deviceId,
1326 int32_t devicePolicy,
1327 int clientUid,
1328 const std::string& packageName) {
1329 if ((deviceId == kDefaultDeviceId)
1330 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1331 auto [storedDeviceId, _] =
1332 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1333 if (storedDeviceId != kDefaultDeviceId) {
1334 // Trying to access a virtual camera from default-policy device context, we should fail.
1335 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1336 inputCameraId.c_str(), deviceId);
1337 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1338 return std::nullopt;
1339 }
1340 return resolveCameraId(inputCameraId, clientUid, packageName);
1341 }
1342
1343 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1344}
1345
1346Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait, int32_t deviceId,
1347 int32_t devicePolicy, CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001348 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001349 Mutex::Autolock l(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001350 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId, deviceId, devicePolicy);
1351 if (cameraIdStr.empty()) {
1352 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
1353 cameraId, deviceId);
1354 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1355 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1356 }
malikakashedb38962023-09-06 00:03:35 +00001357
Austin Borgered99f642023-06-01 16:51:35 -07001358 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001359 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1360 "characteristics for system only device %s: ", cameraIdStr.c_str());
1361 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001362
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001363 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001364 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001365 return STATUS_ERROR(ERROR_DISCONNECTED,
1366 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001367 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001368 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001369 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001370 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1371 if (hasSystemCameraPermissions) {
1372 cameraIdBound = mNumberOfCameras;
1373 }
1374 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001375 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1376 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001377 }
1378
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001379 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001380 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001381 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borgered99f642023-06-01 16:51:35 -07001382 cameraIdStr, overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001383 if (err != OK) {
1384 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1385 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1386 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001387 logServiceError(std::string("Error retrieving camera info from device ")
1388 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001389 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001390
Ruben Brunkcc776712015-02-17 20:18:47 -08001391 return ret;
1392}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001393
Biswarup Pal37a75182024-01-16 15:53:35 +00001394std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1395 int32_t deviceId, int32_t devicePolicy) {
1396 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1397 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1398 std::optional<std::string> cameraIdOptional =
1399 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1400 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1401 }
1402
1403 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001404 auto callingPid = getCallingPid();
1405 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001406 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1407 callingPid, callingUid, /* checkCameraPermissions= */ false);
1408 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001409 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001410 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001411 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1412 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1413 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001414 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001415 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001416
Biswarup Pal37a75182024-01-16 15:53:35 +00001417 std::string unresolvedCameraId = (*cameraIds)[cameraIdInt];
1418 return resolveCameraId(unresolvedCameraId, getCallingUid());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001419}
1420
Biswarup Pal37a75182024-01-16 15:53:35 +00001421std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1422 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001423 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001424 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001425}
1426
Austin Borgered99f642023-06-01 16:51:35 -07001427Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +00001428 int targetSdkVersion, bool overrideToPortrait, int32_t deviceId, int32_t devicePolicy,
1429 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001430 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001431
Zhijun He2b59be82013-09-25 10:14:30 -07001432 if (!cameraInfo) {
1433 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001434 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001435 }
1436
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001437 if (!mInitialized) {
1438 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001439 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001440 return STATUS_ERROR(ERROR_DISCONNECTED,
1441 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001442 }
1443
Biswarup Pal37a75182024-01-16 15:53:35 +00001444 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
1445 devicePolicy, getCallingUid());
1446 if (!cameraIdOptional.has_value()) {
1447 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1448 unresolvedCameraId.c_str(), deviceId);
1449 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1450 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1451 }
1452 std::string cameraId = cameraIdOptional.value();
1453
Austin Borgered99f642023-06-01 16:51:35 -07001454 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001455 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001456 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001457 }
1458
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001459 bool overrideForPerfClass =
1460 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001461 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001462 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borgered99f642023-06-01 16:51:35 -07001463 cameraId, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001464 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001465 if (res == NAME_NOT_FOUND) {
1466 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001467 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001468 strerror(-res), res);
1469 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001470 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1471 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001472 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001473 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001474 strerror(-res), res);
1475 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001476 }
Emilian Peeve20c6372018-08-14 18:45:53 +01001477
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001478 return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -07001479}
1480
Biswarup Pal37a75182024-01-16 15:53:35 +00001481Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId, int32_t deviceId,
1482 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001483 ATRACE_CALL();
1484 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001485
Biswarup Pal37a75182024-01-16 15:53:35 +00001486 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
1487 devicePolicy, getCallingUid());
1488 if (!cameraIdOptional.has_value()) {
1489 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1490 unresolvedCameraId.c_str(), deviceId);
1491 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1492 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1493 }
1494 std::string cameraId = cameraIdOptional.value();
1495
Rucha Katakwar38284522021-11-10 11:25:21 -08001496 if (!mInitialized) {
1497 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1498 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1499 }
1500
Biswarup Pal37a75182024-01-16 15:53:35 +00001501 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001502 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1503 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1504 }
1505
Austin Borgered99f642023-06-01 16:51:35 -07001506 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001507 if (res != OK) {
1508 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001509 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001510 strerror(-res), res);
1511 }
1512 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1513 return Status::ok();
1514}
1515
Austin Borgered99f642023-06-01 16:51:35 -07001516std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001517 time_t now = time(nullptr);
1518 char formattedTime[64];
1519 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001520 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001521}
1522
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001523Status CameraService::getCameraVendorTagDescriptor(
1524 /*out*/
1525 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001526 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001527 if (!mInitialized) {
1528 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001529 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001530 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001531 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1532 if (globalDescriptor != nullptr) {
1533 *desc = *(globalDescriptor.get());
1534 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001535 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001536}
1537
Emilian Peev71c73a22017-03-21 16:35:51 +00001538Status CameraService::getCameraVendorTagCache(
1539 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1540 ATRACE_CALL();
1541 if (!mInitialized) {
1542 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1543 return STATUS_ERROR(ERROR_DISCONNECTED,
1544 "Camera subsystem not available");
1545 }
1546 sp<VendorTagDescriptorCache> globalCache =
1547 VendorTagDescriptorCache::getGlobalVendorTagCache();
1548 if (globalCache != nullptr) {
1549 *cache = *(globalCache.get());
1550 }
1551 return Status::ok();
1552}
1553
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001554void CameraService::clearCachedVariables() {
1555 BasicClient::BasicClient::sCameraService = nullptr;
1556}
1557
Austin Borgered99f642023-06-01 16:51:35 -07001558std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001559 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001560 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001561
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001562 int deviceVersion = 0;
1563
Emilian Peevf53f66e2017-04-11 14:29:43 +01001564 status_t res;
1565 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001566 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001567 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001568 if (res != OK || transport == IPCTransport::INVALID) {
1569 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001570 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001571 return std::make_pair(-1, IPCTransport::INVALID) ;
1572 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001573 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001574
Emilian Peevf53f66e2017-04-11 14:29:43 +01001575 hardware::CameraInfo info;
1576 if (facing) {
Austin Borgered99f642023-06-01 16:51:35 -07001577 res = mCameraProviderManager->getCameraInfo(cameraId, overrideToPortrait,
Austin Borger18b30a72022-10-27 12:20:29 -07001578 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001579 if (res != OK) {
1580 return std::make_pair(-1, IPCTransport::INVALID);
1581 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001582 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001583 if (orientation) {
1584 *orientation = info.orientation;
1585 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001586 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001587
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001588 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001589}
1590
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001591Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001592 switch(err) {
1593 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001594 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001595 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001596 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1597 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001598 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001599 return STATUS_ERROR(ERROR_DISCONNECTED,
1600 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001601 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001602 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1603 "Camera HAL encountered error %d: %s",
1604 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001605 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001606}
1607
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001608Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001609 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1610 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001611 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001612 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001613 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
malikakash73125c62023-07-21 22:44:34 +00001614 bool forceSlowJpegMode, const std::string& originalCameraId,
1615 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001616 // For HIDL devices
1617 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1618 // Create CameraClient based on device version reported by the HAL.
1619 int deviceVersion = deviceVersionAndTransport.first;
1620 switch(deviceVersion) {
1621 case CAMERA_DEVICE_API_VERSION_1_0:
1622 ALOGE("Camera using old HAL version: %d", deviceVersion);
1623 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1624 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001625 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001626 break;
1627 case CAMERA_DEVICE_API_VERSION_3_0:
1628 case CAMERA_DEVICE_API_VERSION_3_1:
1629 case CAMERA_DEVICE_API_VERSION_3_2:
1630 case CAMERA_DEVICE_API_VERSION_3_3:
1631 case CAMERA_DEVICE_API_VERSION_3_4:
1632 case CAMERA_DEVICE_API_VERSION_3_5:
1633 case CAMERA_DEVICE_API_VERSION_3_6:
1634 case CAMERA_DEVICE_API_VERSION_3_7:
1635 break;
1636 default:
1637 // Should not be reachable
1638 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1639 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1640 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001641 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001642 }
1643 }
1644 if (effectiveApiLevel == API_1) { // Camera1 API route
1645 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001646 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001647 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001648 api1CameraId, facing, sensorOrientation,
Chengfei Taobe683db2023-01-31 18:52:49 +00001649 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait,
1650 forceSlowJpegMode);
1651 ALOGI("%s: Camera1 API (legacy), override to portrait %d, forceSlowJpegMode %d",
1652 __FUNCTION__, overrideToPortrait, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001653 } else { // Camera2 API route
1654 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1655 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001656 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001657 cameraService->mCameraServiceProxyWrapper,
1658 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001659 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
malikakash82ed4352023-07-21 22:44:34 +00001660 overrideForPerfClass, overrideToPortrait, originalCameraId);
Austin Borger18b30a72022-10-27 12:20:29 -07001661 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001662 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001663 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001664}
1665
Austin Borgered99f642023-06-01 16:51:35 -07001666std::string CameraService::toString(std::set<userid_t> intSet) {
1667 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001668 bool first = true;
1669 for (userid_t i : intSet) {
1670 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001671 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001672 first = false;
1673 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001674 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001675 }
1676 }
Austin Borgered99f642023-06-01 16:51:35 -07001677 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001678}
1679
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001680int32_t CameraService::mapToInterface(TorchModeStatus status) {
1681 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1682 switch (status) {
1683 case TorchModeStatus::NOT_AVAILABLE:
1684 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1685 break;
1686 case TorchModeStatus::AVAILABLE_OFF:
1687 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1688 break;
1689 case TorchModeStatus::AVAILABLE_ON:
1690 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1691 break;
1692 default:
1693 ALOGW("Unknown new flash status: %d", status);
1694 }
1695 return serviceStatus;
1696}
1697
1698CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1699 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1700 switch (status) {
1701 case CameraDeviceStatus::NOT_PRESENT:
1702 serviceStatus = StatusInternal::NOT_PRESENT;
1703 break;
1704 case CameraDeviceStatus::PRESENT:
1705 serviceStatus = StatusInternal::PRESENT;
1706 break;
1707 case CameraDeviceStatus::ENUMERATING:
1708 serviceStatus = StatusInternal::ENUMERATING;
1709 break;
1710 default:
1711 ALOGW("Unknown new HAL device status: %d", status);
1712 }
1713 return serviceStatus;
1714}
1715
1716int32_t CameraService::mapToInterface(StatusInternal status) {
1717 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1718 switch (status) {
1719 case StatusInternal::NOT_PRESENT:
1720 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1721 break;
1722 case StatusInternal::PRESENT:
1723 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1724 break;
1725 case StatusInternal::ENUMERATING:
1726 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1727 break;
1728 case StatusInternal::NOT_AVAILABLE:
1729 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1730 break;
1731 case StatusInternal::UNKNOWN:
1732 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1733 break;
1734 default:
1735 ALOGW("Unknown new internal device status: %d", status);
1736 }
1737 return serviceStatus;
1738}
1739
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001740Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001741 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001742
Austin Borgered99f642023-06-01 16:51:35 -07001743 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001744 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001745 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001746 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001747 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1748 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001749 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Chengfei Taobe683db2023-01-31 18:52:49 +00001750 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true,
Austin Borgered99f642023-06-01 16:51:35 -07001751 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001752 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001753 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001754 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001755 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001756}
1757
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001758Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001759 /*out*/
1760 CameraParameters* parameters) {
1761
1762 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1763
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001764 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001765
1766 if (parameters == NULL) {
1767 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001768 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001769 }
1770
malikakashedb38962023-09-06 00:03:35 +00001771 std::string unresolvedCameraId = std::to_string(cameraId);
1772 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08001773 getCallingUid());
Ruben Brunkcc776712015-02-17 20:18:47 -08001774
1775 // Check if we already have parameters
1776 {
1777 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001778 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001779 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001780 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001781 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001782 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001783 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001784 }
1785 CameraParameters p = cameraState->getShimParams();
1786 if (!p.isEmpty()) {
1787 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001788 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001789 }
1790 }
1791
Austin Borger22c5c852024-03-08 13:31:36 -08001792 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001793 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001794 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001795 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001796 // Error already logged by callee
1797 return ret;
1798 }
1799
1800 // Check for parameters again
1801 {
1802 // Scope for service lock
1803 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001804 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001805 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001806 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001807 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001808 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001809 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001810 CameraParameters p = cameraState->getShimParams();
1811 if (!p.isEmpty()) {
1812 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001813 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001814 }
1815 }
1816
Ruben Brunkcc776712015-02-17 20:18:47 -08001817 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1818 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001819 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001820}
1821
Austin Borgered99f642023-06-01 16:51:35 -07001822Status CameraService::validateConnectLocked(const std::string& cameraId,
1823 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001824 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001825
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001826#ifdef __BRILLO__
1827 UNUSED(clientName8);
1828 UNUSED(clientUid);
1829 UNUSED(clientPid);
1830 UNUSED(originalClientPid);
1831#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001832 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1833 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001834 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001835 return allowed;
1836 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001837#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001838
Austin Borger22c5c852024-03-08 13:31:36 -08001839 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001840
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001841 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001842 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1843 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001844 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001845 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001846 }
1847
Ruben Brunkcc776712015-02-17 20:18:47 -08001848 if (getCameraState(cameraId) == nullptr) {
1849 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001850 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001851 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001852 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853 }
1854
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001855 status_t err = checkIfDeviceIsUsable(cameraId);
1856 if (err != NO_ERROR) {
1857 switch(err) {
1858 case -ENODEV:
1859 case -EBUSY:
1860 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001861 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001862 default:
1863 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001864 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001865 }
1866 }
1867 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001868}
1869
Austin Borgered99f642023-06-01 16:51:35 -07001870Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1871 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001872 /*out*/int& originalClientPid) const {
Austin Borger22c5c852024-03-08 13:31:36 -08001873 int callingPid = getCallingPid();
1874 int callingUid = getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001875
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001876 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001877 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001878 clientUid = callingUid;
1879 } else if (!isTrustedCallingUid(callingUid)) {
1880 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1881 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001882 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1883 "Untrusted caller (calling PID %d, UID %d) trying to "
1884 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001885 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001886 clientName.c_str(), clientPid, clientUid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001887 }
1888
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001889 // Check if we can trust clientPid
1890 if (clientPid == USE_CALLING_PID) {
1891 clientPid = callingPid;
1892 } else if (!isTrustedCallingUid(callingUid)) {
1893 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1894 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001895 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1896 "Untrusted caller (calling PID %d, UID %d) trying to "
1897 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001898 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001899 clientName.c_str(), clientPid, clientUid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001900 }
1901
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001902 if (shouldRejectSystemCameraConnection(cameraId)) {
1903 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1904 cameraId.c_str());
1905 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001906 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001907 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001908 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1909 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001910 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001911 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001912 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001913
1914 }
1915
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001916 // If it's not calling from cameraserver, check the permission if the
1917 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1918 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001919 bool checkPermissionForCamera =
1920 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001921 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001922 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001923 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001924 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1925 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001926 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001927 }
1928
Svet Ganova453d0d2018-01-11 15:37:58 -08001929 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001930 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001931 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001932 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1933 clientPid, clientUid);
1934 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001935 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1936 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001937 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001938 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001939 }
1940
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001941 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1942 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1943 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1944 if ((!isAutomotivePrivilegedClient(callingUid) ||
1945 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1946 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001947 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1948 return STATUS_ERROR_FMT(ERROR_DISABLED,
1949 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001950 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001951 }
1952
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001953 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1954 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001955 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001956 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001957
Ruben Brunk6267b532015-04-30 17:44:07 -07001958 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001959
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001960 // For non-system clients : Only allow clients who are being used by the current foreground
1961 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08001962 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001963 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001964 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1965 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001966 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001967 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1968 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001969 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001970 }
1971
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001972 if (flags::camera_hsum_permission()) {
1973 // If the System User tries to access the camera when the device is running in
1974 // headless system user mode, ensure that client has the required permission
1975 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07001976 if (isHeadlessSystemUserMode()
1977 && (clientUserId == USER_SYSTEM)
1978 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001979 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
1980 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1981 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1982 User without camera headless system user permission",
Austin Borger249e6592024-03-10 22:28:11 -07001983 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001984 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001985 }
1986
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001987 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001988}
1989
Austin Borgered99f642023-06-01 16:51:35 -07001990status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001991 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001992 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001993 if (cameraState == nullptr) {
1994 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001995 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001996 return -ENODEV;
1997 }
1998
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001999 StatusInternal currentStatus = cameraState->getStatus();
2000 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002001 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07002002 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002003 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002004 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002005 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07002006 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002007 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07002008 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002009
Ruben Brunkcc776712015-02-17 20:18:47 -08002010 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08002011}
2012
Ruben Brunkcc776712015-02-17 20:18:47 -08002013void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002014 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08002015
Ruben Brunkcc776712015-02-17 20:18:47 -08002016 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002017 auto clientDescriptor =
2018 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002019 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08002020 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
2021
2022 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002023 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08002024
2025 if (evicted.size() > 0) {
2026 // This should never happen - clients should already have been removed in disconnect
2027 for (auto& i : evicted) {
2028 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07002029 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002030 }
2031
2032 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
2033 __FUNCTION__);
2034 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002035
2036 // And register a death notification for the client callback. Do
2037 // this last to avoid Binder policy where a nested Binder
2038 // transaction might be pre-empted to service the client death
2039 // notification if the client process dies before linkToDeath is
2040 // invoked.
2041 sp<IBinder> remoteCallback = client->getRemote();
2042 if (remoteCallback != nullptr) {
2043 remoteCallback->linkToDeath(this);
2044 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002045}
2046
Austin Borgered99f642023-06-01 16:51:35 -07002047status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
2048 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
2049 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08002050 /*out*/
2051 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07002052 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002053 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08002054 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002055 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08002056 DescriptorPtr clientDescriptor;
2057 {
2058 if (effectiveApiLevel == API_1) {
2059 // If we are using API1, any existing client for this camera ID with the same remote
2060 // should be returned rather than evicted to allow MediaRecorder to work properly.
2061
2062 auto current = mActiveClientManager.get(cameraId);
2063 if (current != nullptr) {
2064 auto clientSp = current->getValue();
2065 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002066 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07002067 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002068 " API level, evicting prior client...");
2069 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002070 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002071 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002072 *client = clientSp;
2073 return NO_ERROR;
2074 }
2075 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002076 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002077 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08002078
Ruben Brunkcc776712015-02-17 20:18:47 -08002079 // Get state for the given cameraId
2080 auto state = getCameraState(cameraId);
2081 if (state == nullptr) {
2082 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07002083 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002084 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07002085 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002086 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002087
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002088 sp<IServiceManager> sm = defaultServiceManager();
2089 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08002090 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002091 // If processinfo service is not available and the client is automotive privileged
2092 // client used for safety critical uses cases such as rear-view and surround-view which
2093 // needs to be available before android boot completes, then use the hardcoded values
2094 // for the process state and priority score. As this scenario is before android system
2095 // services are up and client is native client, hence using NATIVE_ADJ as the priority
2096 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
2097 // visible on the top.
2098 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2099 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2100 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
2101 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
2102 } else {
2103 // Get current active client PIDs
2104 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
2105 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002106
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002107 std::vector<int> priorityScores(ownerPids.size());
2108 std::vector<int> states(ownerPids.size());
2109
2110 // Get priority scores of all active PIDs
2111 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
2112 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
2113 if (err != OK) {
2114 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
2115 return err;
2116 }
2117
2118 // Update all active clients' priorities
2119 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
2120 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
2121 pidToPriorityMap.emplace(ownerPids[i],
2122 resource_policy::ClientPriority(priorityScores[i], states[i],
2123 /* isVendorClient won't get copied over*/ false,
2124 /* oomScoreOffset won't get copied over*/ 0));
2125 }
2126 mActiveClientManager.updatePriorities(pidToPriorityMap);
2127
2128 int32_t actualScore = priorityScores[priorityScores.size() - 1];
2129 int32_t actualState = states[states.size() - 1];
2130
2131 // Make descriptor for incoming client. We store the oomScoreOffset
2132 // since we might need it later on new handleEvictionsLocked and
2133 // ProcessInfoService would not take that into account.
2134 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2135 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2136 state->getConflicting(), actualScore, clientPid, actualState,
2137 oomScoreOffset, systemNativeClient);
2138 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002139
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002140 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
2141
Ruben Brunkcc776712015-02-17 20:18:47 -08002142 // Find clients that would be evicted
2143 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
2144
2145 // If the incoming client was 'evicted,' higher priority clients have the camera in the
2146 // background, so we cannot do evictions
2147 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2148 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2149 " priority).", clientPid);
2150
2151 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002152 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002153 auto incompatibleClients =
2154 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2155
Austin Borgered99f642023-06-01 16:51:35 -07002156 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2157 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2158 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002159 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002160
2161 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002162 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002163 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002164 i->getKey().c_str(),
2165 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002166 i->getOwnerId(), i->getPriority().getScore(),
2167 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002168 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002169 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2170 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002171 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002172 }
2173
2174 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002175 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002176 mEventLog.add(msg);
2177
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002178 auto current = mActiveClientManager.get(cameraId);
2179 if (current != nullptr) {
2180 return -EBUSY; // CAMERA_IN_USE
2181 } else {
2182 return -EUSERS; // MAX_CAMERAS_IN_USE
2183 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002184 }
2185
2186 for (auto& i : evicted) {
2187 sp<BasicClient> clientSp = i->getValue();
2188 if (clientSp.get() == nullptr) {
2189 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2190
2191 // TODO: Remove this
2192 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2193 __FUNCTION__);
2194 mActiveClientManager.remove(i);
2195 continue;
2196 }
2197
2198 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002199 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002200 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002201
Ruben Brunkcc776712015-02-17 20:18:47 -08002202 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002203 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002204 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2205 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002206 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002207 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002208 i->getPriority().getState(), cameraId.c_str(),
2209 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002210 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002211
2212 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002213 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002214 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002215 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002216 }
2217
Ruben Brunkcc776712015-02-17 20:18:47 -08002218 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2219 // other clients from connecting in mServiceLockWrapper if held
2220 mServiceLock.unlock();
2221
2222 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002223 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002224
2225 // Destroy evicted clients
2226 for (auto& i : evictedClients) {
2227 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002228 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002229 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002230
Austin Borger22c5c852024-03-08 13:31:36 -08002231 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002232
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002233 for (const auto& i : evictedClients) {
2234 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002235 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002236 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2237 if (ret == TIMED_OUT) {
2238 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002239 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2240 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002241 return -EBUSY;
2242 }
2243 if (ret != NO_ERROR) {
2244 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002245 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2246 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002247 return ret;
2248 }
2249 }
2250
2251 evictedClients.clear();
2252
Ruben Brunkcc776712015-02-17 20:18:47 -08002253 // Once clients have been disconnected, relock
2254 mServiceLock.lock();
2255
2256 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2257 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2258 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002259 }
2260
Ruben Brunkcc776712015-02-17 20:18:47 -08002261 *partial = clientDescriptor;
2262 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002263}
2264
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002265Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002266 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002267 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07002268 const std::string& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002269 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08002270 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002271 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07002272 bool overrideToPortrait,
Chengfei Taobe683db2023-01-31 18:52:49 +00002273 bool forceSlowJpegMode,
Biswarup Pal37a75182024-01-16 15:53:35 +00002274 int32_t deviceId,
2275 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002276 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002277 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002278 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002279 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002280
Biswarup Pal37a75182024-01-16 15:53:35 +00002281 std::string cameraIdStr = cameraIdIntToStr(api1CameraId, deviceId, devicePolicy);
2282 if (cameraIdStr.empty()) {
2283 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
2284 api1CameraId, deviceId);
2285 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2286 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2287 }
malikakashedb38962023-09-06 00:03:35 +00002288
Ruben Brunkcc776712015-02-17 20:18:47 -08002289 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002290 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
2291 clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002292 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002293 overrideToPortrait, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002294
Biswarup Pal37a75182024-01-16 15:53:35 +00002295 if (!ret.isOk()) {
2296 logRejected(cameraIdStr, getCallingPid(), clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002297 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002298 }
2299
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002300 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002301
2302 const sp<IServiceManager> sm(defaultServiceManager());
2303 const auto& mActivityManager = getActivityManager();
2304 if (mActivityManager) {
2305 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002306 getCallingUid(),
2307 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002308 }
2309
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002310 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002311}
2312
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002313bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2314 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002315 // If the client is not a vendor client, don't add listener if
2316 // a) the camera is a publicly hidden secure camera OR
2317 // b) the camera is a system only camera and the client doesn't
2318 // have android.permission.SYSTEM_CAMERA permissions.
2319 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2320 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002321 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002322 return true;
2323 }
2324 return false;
2325}
2326
Austin Borgered99f642023-06-01 16:51:35 -07002327bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002328 // Rules for rejection:
2329 // 1) If cameraserver tries to access this camera device, accept the
2330 // connection.
2331 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002332 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002333 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2334 // and the serving thread is a non hwbinder thread, the client must have
2335 // android.permission.SYSTEM_CAMERA permissions to connect.
2336
Austin Borger22c5c852024-03-08 13:31:36 -08002337 int cPid = getCallingPid();
2338 int cUid = getCallingUid();
2339 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002340 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2341 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002342 // This isn't a known camera ID, so it's not a system camera
2343 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2344 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002345 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002346
2347 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002348 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002349 return false;
2350 }
2351 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002352 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002353 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2354 return true;
2355 }
2356 // (3) Here we only check for permissions if it is a system only camera device. This is since
2357 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2358 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2359 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002360 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002361 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002362 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2363 cameraId.c_str());
2364 return true;
2365 }
2366
2367 return false;
2368}
2369
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002370Status CameraService::connectDevice(
2371 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002372 const std::string& unresolvedCameraId,
2373 const std::string& clientPackageName,
2374 const std::optional<std::string>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002375 int clientUid, int oomScoreOffset, int targetSdkVersion,
Biswarup Pal37a75182024-01-16 15:53:35 +00002376 bool overrideToPortrait, int32_t deviceId, int32_t devicePolicy,
Ruben Brunkcc776712015-02-17 20:18:47 -08002377 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002378 sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002379 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002380 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002381 sp<CameraDeviceClient> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002382 std::string clientPackageNameAdj = clientPackageName;
Austin Borger22c5c852024-03-08 13:31:36 -08002383 int callingPid = getCallingPid();
2384 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002385 bool systemNativeClient = false;
Austin Borger22c5c852024-03-08 13:31:36 -08002386 if (callerHasSystemUid() && (clientPackageNameAdj.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002387 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borgered99f642023-06-01 16:51:35 -07002388 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002389 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002390 }
Austin Borger249e6592024-03-10 22:28:11 -07002391
Biswarup Pal37a75182024-01-16 15:53:35 +00002392 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
2393 devicePolicy, callingUid, clientPackageNameAdj);
2394 if (!cameraIdOptional.has_value()) {
2395 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
2396 unresolvedCameraId.c_str(), deviceId);
2397 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2398 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2399 }
2400 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002401
2402 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002403 std::string msg =
2404 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
2405 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
2406 cameraId.c_str());
2407 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2408 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002409 }
2410
Austin Borger9bfa0a72022-08-03 17:50:40 -07002411 userid_t clientUserId = multiuser_get_user_id(clientUid);
Austin Borger9bfa0a72022-08-03 17:50:40 -07002412 if (clientUid == USE_CALLING_UID) {
2413 clientUserId = multiuser_get_user_id(callingUid);
2414 }
2415
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002416 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2417 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002418 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2419 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002420 std::string msg = "Camera disabled by device policy";
2421 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2422 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002423 }
2424
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002425 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002426 if (oomScoreOffset > 0
2427 && !hasPermissionsForSystemCamera(cameraId, callingPid,
Austin Borger249e6592024-03-10 22:28:11 -07002428 callingUid)
2429 && !isTrustedCallingUid(callingUid)) {
Austin Borgered99f642023-06-01 16:51:35 -07002430 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002431 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07002432 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2433 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2434 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002435 }
2436
Austin Borgered99f642023-06-01 16:51:35 -07002437 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
2438 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002439 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
malikakash73125c62023-07-21 22:44:34 +00002440 targetSdkVersion, overrideToPortrait, /*forceSlowJpegMode*/false, unresolvedCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002441 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002442
Biswarup Pal37a75182024-01-16 15:53:35 +00002443 if (!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002444 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002445 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002446 }
2447
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002448 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002449 Mutex::Autolock lock(mServiceLock);
2450
2451 // Clear the previous cached logs and reposition the
2452 // file offset to beginning of the file to log new data.
2453 // If either truncate or lseek fails, close the previous file and create a new one.
2454 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2455 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2456 // Close the previous memfd.
2457 close(mMemFd);
2458 // If failure to wipe the data, then create a new file and
2459 // assign the new value to mMemFd.
2460 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2461 if (mMemFd == -1) {
2462 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2463 }
2464 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002465 const sp<IServiceManager> sm(defaultServiceManager());
2466 const auto& mActivityManager = getActivityManager();
2467 if (mActivityManager) {
2468 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002469 callingUid,
2470 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002471 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002472 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002473}
2474
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002475bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2476 int callingPid, int callingUid) {
2477 if (!isAutomotiveDevice()) {
2478 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2479 }
2480
2481 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2482 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2483 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2484 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2485 "using camera %s", callingUid, cam_id.c_str());
2486 return false;
2487 }
2488
2489 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2490 return true;
2491 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2492 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002493 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2494 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002495 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2496 return false;
2497 } else {
2498 return true;
2499 }
2500 }
2501 return false;
2502}
2503
Austin Borgered99f642023-06-01 16:51:35 -07002504std::string CameraService::getPackageNameFromUid(int clientUid) {
2505 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002506
Avichal Rakesh5788fec2024-03-15 14:39:20 -07002507 sp<IPermissionController> permCtrl;
2508 if (flags::cache_permission_services()) {
2509 permCtrl = getPermissionController();
2510 } else {
2511 sp<IServiceManager> sm = defaultServiceManager();
2512#pragma clang diagnostic push
2513#pragma clang diagnostic ignored "-Wdeprecated-declarations"
2514 // Using deprecated function to preserve functionality until the
2515 // cache_permission_services flag is removed.
2516 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
2517#pragma clang diagnostic pop
2518 if (binder == 0) {
2519 ALOGE("Cannot get permission service");
2520 permCtrl = nullptr;
2521 } else {
2522 permCtrl = interface_cast<IPermissionController>(binder);
2523 }
2524 }
2525
2526 if (permCtrl == nullptr) {
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002527 // Return empty package name and the further interaction
2528 // with camera will likely fail
2529 return packageName;
2530 }
2531
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002532 Vector<String16> packages;
2533
2534 permCtrl->getPackagesForUid(clientUid, packages);
2535
2536 if (packages.isEmpty()) {
2537 ALOGE("No packages for calling UID %d", clientUid);
2538 // Return empty package name and the further interaction
2539 // with camera will likely fail
2540 return packageName;
2541 }
2542
2543 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002544 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002545
2546 return packageName;
2547}
2548
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002549template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002550Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2551 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2552 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002553 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002554 bool overrideToPortrait, bool forceSlowJpegMode, const std::string& originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002555 /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002556 binder::Status ret = binder::Status::ok();
2557
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002558 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002559 std::string clientPackageName;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002560 int packageUid = (clientUid == USE_CALLING_UID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002561 getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002562 if (clientPackageNameMaybe.size() <= 0) {
2563 // NDK calls don't come with package names, but we need one for various cases.
2564 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2565 // do exist. For all authentication cases, all packages under the same UID get the
2566 // same permissions, so picking any associated package name is sufficient. For some
2567 // other cases, this may give inaccurate names for clients in logs.
2568 isNonSystemNdk = true;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002569 clientPackageName = getPackageNameFromUid(packageUid);
2570 } else {
2571 clientPackageName = clientPackageNameMaybe;
2572 }
2573
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002574 int originalClientPid = 0;
2575
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002576 int packagePid = (clientPid == USE_CALLING_PID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002577 getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002578 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002579 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002580 static_cast<int>(effectiveApiLevel));
2581
Shuzhen Wang316781a2020-08-18 18:11:01 -07002582 nsecs_t openTimeNs = systemTime();
2583
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002584 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002585 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002586 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002587
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002588 {
2589 // Acquire mServiceLock and prevent other clients from connecting
2590 std::unique_ptr<AutoConditionLock> lock =
2591 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2592
2593 if (lock == nullptr) {
2594 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2595 , clientPid);
2596 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2597 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002598 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002599 }
2600
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002601 // Enforce client permissions and do basic validity checks
Biswarup Pal37a75182024-01-16 15:53:35 +00002602 if (!(ret = validateConnectLocked(cameraId, clientPackageName,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002603 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2604 return ret;
2605 }
2606
2607 // Check the shim parameters after acquiring lock, if they have already been updated and
2608 // we were doing a shim update, return immediately
2609 if (shimUpdateOnly) {
2610 auto cameraState = getCameraState(cameraId);
2611 if (cameraState != nullptr) {
2612 if (!cameraState->getShimParams().isEmpty()) return ret;
2613 }
2614 }
2615
2616 status_t err;
2617
2618 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002619 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002620 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002621 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2622 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002623 switch (err) {
2624 case -ENODEV:
2625 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2626 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002627 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002628 case -EBUSY:
2629 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2630 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002631 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002632 case -EUSERS:
2633 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2634 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002635 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002636 default:
2637 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2638 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002639 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002640 }
2641 }
2642
2643 if (clientTmp.get() != nullptr) {
2644 // Handle special case for API1 MediaRecorder where the existing client is returned
2645 device = static_cast<CLIENT*>(clientTmp.get());
2646 return ret;
2647 }
2648
2649 // give flashlight a chance to close devices if necessary.
2650 mFlashlight->prepareDeviceOpen(cameraId);
2651
Austin Borger18b30a72022-10-27 12:20:29 -07002652 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002653 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07002654 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
2655 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002656 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002657 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002658 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002659 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002660 }
2661
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002662 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002663 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002664 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002665 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002666 clientFeatureId, cameraId, api1CameraId, facing,
2667 orientation, clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002668 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
malikakash82ed4352023-07-21 22:44:34 +00002669 overrideToPortrait, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002670 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002671 return ret;
2672 }
2673 client = static_cast<CLIENT*>(tmp.get());
2674
2675 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2676 __FUNCTION__);
2677
Austin Borgered99f642023-06-01 16:51:35 -07002678 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002679 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002680 if (err != OK) {
2681 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002682 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002683 mServiceLock.unlock();
2684 client->disconnect();
2685 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002686 switch(err) {
2687 case BAD_VALUE:
2688 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002689 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002690 case -EBUSY:
2691 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002692 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002693 case -EUSERS:
2694 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2695 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002696 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002697 case PERMISSION_DENIED:
2698 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002699 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002700 case -EACCES:
2701 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002702 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002703 case -ENODEV:
2704 default:
2705 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002706 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002707 strerror(-err), err);
2708 }
2709 }
2710
2711 // Update shim paremeters for legacy clients
2712 if (effectiveApiLevel == API_1) {
2713 // Assume we have always received a Client subclass for API1
2714 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2715 String8 rawParams = shimClient->getParameters();
2716 CameraParameters params(rawParams);
2717
2718 auto cameraState = getCameraState(cameraId);
2719 if (cameraState != nullptr) {
2720 cameraState->setShimParams(params);
2721 } else {
2722 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002723 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002724 }
2725 }
2726
Ravneetaeb20dc2022-03-30 05:33:03 +00002727 // Enable/disable camera service watchdog
2728 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2729
Emilian Peev6d45db82024-01-18 20:11:54 +00002730 CameraMetadata chars;
2731 bool rotateAndCropSupported = true;
2732 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
2733 &chars, overrideToPortrait);
2734 if (err == OK) {
2735 auto availableRotateCropEntry = chars.find(
2736 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2737 if (availableRotateCropEntry.count <= 1) {
2738 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002739 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002740 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002741 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2742 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002743 }
2744
Emilian Peev6d45db82024-01-18 20:11:54 +00002745 if (rotateAndCropSupported) {
2746 // Set rotate-and-crop override behavior
2747 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2748 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
2749 } else if (overrideToPortrait && portraitRotation != 0) {
2750 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2751 switch (portraitRotation) {
2752 case 90:
2753 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2754 break;
2755 case 180:
2756 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2757 break;
2758 case 270:
2759 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2760 break;
2761 default:
2762 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2763 break;
2764 }
2765 client->setRotateAndCropOverride(rotateAndCropMode);
2766 } else {
2767 client->setRotateAndCropOverride(
2768 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2769 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2770 }
2771 }
2772
2773 bool autoframingSupported = true;
2774 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2775 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2776 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2777 autoframingSupported = false;
2778 }
2779
2780 if (autoframingSupported) {
2781 // Set autoframing override behaviour
2782 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2783 client->setAutoframingOverride(mOverrideAutoframingMode);
2784 } else {
2785 client->setAutoframingOverride(
2786 mCameraServiceProxyWrapper->getAutoframingOverride(
2787 clientPackageName));
2788 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002789 }
2790
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002791 bool isCameraPrivacyEnabled;
2792 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002793 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002794 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2795 toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2796 } else {
2797 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002798 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002799 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002800
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002801 if (client->supportsCameraMute()) {
2802 client->setCameraMute(
2803 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2804 } else if (isCameraPrivacyEnabled) {
2805 // no camera mute supported, but privacy is on! => disconnect
2806 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2807 client->getPackageName().c_str(), cameraId.c_str());
2808 // Do not hold mServiceLock while disconnecting clients, but
2809 // retain the condition blocking other clients from connecting
2810 // in mServiceLockWrapper if held.
2811 mServiceLock.unlock();
2812 // Clear caller identity temporarily so client disconnect PID
2813 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002814 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002815 // Note AppOp to trigger the "Unblock" dialog
2816 client->noteAppOp();
2817 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002818 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002819 // Reacquire mServiceLock
2820 mServiceLock.lock();
2821
2822 return STATUS_ERROR_FMT(ERROR_DISABLED,
2823 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002824 }
2825
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002826 if (shimUpdateOnly) {
2827 // If only updating legacy shim parameters, immediately disconnect client
2828 mServiceLock.unlock();
2829 client->disconnect();
2830 mServiceLock.lock();
2831 } else {
2832 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002833 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002834 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002835
2836 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002837 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002838 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002839 } // lock is destroyed, allow further connect calls
2840
2841 // Important: release the mutex here so the client can call back into the service from its
2842 // destructor (can be at the end of the call)
2843 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002844
2845 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002846 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002847 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002848
Cliff Wud3a05312021-04-26 23:07:31 +08002849 {
2850 Mutex::Autolock lock(mInjectionParametersLock);
2851 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2852 mInjectionInitPending = false;
2853 status_t res = NO_ERROR;
2854 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2855 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002856 sp<BasicClient> clientSp = clientDescriptor->getValue();
2857 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2858 if(res != OK) {
2859 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2860 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002861 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002862 }
2863 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002864 if (res != OK) {
2865 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2866 }
2867 } else {
2868 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002869 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002870 res = NO_INIT;
2871 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2872 }
2873 }
2874 }
2875
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002876 return ret;
2877}
2878
Austin Borgered99f642023-06-01 16:51:35 -07002879status_t CameraService::addOfflineClient(const std::string &cameraId,
2880 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002881 if (offlineClient.get() == nullptr) {
2882 return BAD_VALUE;
2883 }
2884
2885 {
2886 // Acquire mServiceLock and prevent other clients from connecting
2887 std::unique_ptr<AutoConditionLock> lock =
2888 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2889
2890 if (lock == nullptr) {
2891 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2892 , __FUNCTION__, offlineClient->getClientPid());
2893 return TIMED_OUT;
2894 }
2895
2896 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2897 if (onlineClientDesc.get() == nullptr) {
2898 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2899 cameraId.c_str());
2900 return BAD_VALUE;
2901 }
2902
2903 // Offline clients do not evict or conflict with other online devices. Resource sharing
2904 // conflicts are handled by the camera provider which will either succeed or fail before
2905 // reaching this method.
2906 const auto& onlinePriority = onlineClientDesc->getPriority();
2907 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2908 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002909 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002910 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002911 // native clients don't have offline processing support.
2912 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002913 if (offlineClientDesc == nullptr) {
2914 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2915 return BAD_VALUE;
2916 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002917
2918 // Allow only one offline device per camera
2919 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2920 if (!incompatibleClients.empty()) {
2921 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2922 return BAD_VALUE;
2923 }
2924
Austin Borgered99f642023-06-01 16:51:35 -07002925 std::string monitorTags = isClientWatched(offlineClient.get())
2926 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002927 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002928 if (err != OK) {
2929 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2930 return err;
2931 }
2932
2933 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2934 if (evicted.size() > 0) {
2935 for (auto& i : evicted) {
2936 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002937 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002938 }
2939
2940 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2941 "properly", __FUNCTION__);
2942
2943 return BAD_VALUE;
2944 }
2945
2946 logConnectedOffline(offlineClientDesc->getKey(),
2947 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002948 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002949
2950 sp<IBinder> remoteCallback = offlineClient->getRemote();
2951 if (remoteCallback != nullptr) {
2952 remoteCallback->linkToDeath(this);
2953 }
2954 } // lock is destroyed, allow further connect calls
2955
2956 return OK;
2957}
2958
Austin Borgered99f642023-06-01 16:51:35 -07002959Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +00002960 int32_t torchStrength, const sp<IBinder>& clientBinder, int32_t deviceId,
2961 int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002962 Mutex::Autolock lock(mServiceLock);
2963
2964 ATRACE_CALL();
2965 if (clientBinder == nullptr) {
2966 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2967 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2968 "Torch client binder in null.");
2969 }
2970
Austin Borger22c5c852024-03-08 13:31:36 -08002971 int uid = getCallingUid();
Biswarup Pal37a75182024-01-16 15:53:35 +00002972 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
2973 devicePolicy, uid);
2974 if (!cameraIdOptional.has_value()) {
2975 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
2976 unresolvedCameraId.c_str(), deviceId);
2977 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2978 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2979 }
2980 std::string cameraId = cameraIdOptional.value();
2981
Austin Borgered99f642023-06-01 16:51:35 -07002982 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002983 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002984 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002985 }
2986
2987 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002988 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002989 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002990 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002991 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002992 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002993 }
2994
2995 StatusInternal cameraStatus = state->getStatus();
2996 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2997 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002998 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002999 (int)cameraStatus);
3000 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003001 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003002 }
3003
3004 {
3005 Mutex::Autolock al(mTorchStatusMutex);
3006 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003007 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08003008 if (err != OK) {
3009 if (err == NAME_NOT_FOUND) {
3010 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003011 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003012 }
3013 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003014 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003015 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
3016 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003017 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08003018 }
3019
3020 if (status == TorchModeStatus::NOT_AVAILABLE) {
3021 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
3022 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003023 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003024 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3025 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003026 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003027 } else {
3028 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003029 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003030 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3031 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003032 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003033 }
3034 }
3035 }
3036
3037 {
3038 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003039 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08003040 }
3041 // Check if the current torch strength level is same as the new one.
3042 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07003043 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003044
Austin Borgered99f642023-06-01 16:51:35 -07003045 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003046
3047 if (err != OK) {
3048 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003049 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08003050 switch (err) {
3051 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003052 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
3053 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003054 errorCode = ERROR_ILLEGAL_ARGUMENT;
3055 break;
3056 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003057 msg = fmt::sprintf("Camera \"%s\" is in use",
3058 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003059 errorCode = ERROR_CAMERA_IN_USE;
3060 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08003061 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07003062 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08003063 "valid range.", torchStrength);
3064 errorCode = ERROR_ILLEGAL_ARGUMENT;
3065 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08003066 default:
Austin Borgered99f642023-06-01 16:51:35 -07003067 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08003068 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08003069 }
Austin Borgered99f642023-06-01 16:51:35 -07003070 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3071 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003072 }
3073
3074 {
3075 // update the link to client's death
3076 // Store the last client that turns on each camera's torch mode.
3077 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003078 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08003079 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003080 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08003081 } else {
3082 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
3083 mTorchClientMap.replaceValueAt(index, clientBinder);
3084 }
3085 clientBinder->linkToDeath(this);
3086 }
3087
Austin Borger22c5c852024-03-08 13:31:36 -08003088 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08003089 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07003090 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08003091 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07003092 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003093 }
3094 return Status::ok();
3095}
3096
malikakash73125c62023-07-21 22:44:34 +00003097Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Biswarup Pal37a75182024-01-16 15:53:35 +00003098 const sp<IBinder>& clientBinder, int32_t deviceId, int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003099 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003100
3101 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07003102 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003103 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003104 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
3105 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003106 }
3107
Austin Borger22c5c852024-03-08 13:31:36 -08003108 int uid = getCallingUid();
Biswarup Pal37a75182024-01-16 15:53:35 +00003109 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
3110 devicePolicy, uid);
3111 if (!cameraIdOptional.has_value()) {
3112 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
3113 unresolvedCameraId.c_str(), deviceId);
3114 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3115 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3116 }
3117 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003118
Austin Borgered99f642023-06-01 16:51:35 -07003119 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003120 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07003121 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003122 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003123 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07003124 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003125 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07003126 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003127 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003128 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003129 }
3130
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003131 StatusInternal cameraStatus = state->getStatus();
3132 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003133 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07003134 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
3135 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003136 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003137 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003138 }
3139
3140 {
3141 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003142 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003143 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003144 if (err != OK) {
3145 if (err == NAME_NOT_FOUND) {
3146 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003147 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003148 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003149 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003150 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003151 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07003152 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003153 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003154 }
3155
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003156 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003157 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003158 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003159 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003160 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3161 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003162 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003163 } else {
3164 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003165 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003166 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3167 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003168 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003169 }
3170 }
3171 }
3172
Ruben Brunk99e69712015-05-26 17:25:07 -07003173 {
3174 // Update UID map - this is used in the torch status changed callbacks, so must be done
3175 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003176 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003177 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003178 }
3179
Austin Borgered99f642023-06-01 16:51:35 -07003180 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003181
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003182 if (err != OK) {
3183 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003184 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003185 switch (err) {
3186 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003187 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3188 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003189 errorCode = ERROR_ILLEGAL_ARGUMENT;
3190 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003191 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003192 msg = fmt::sprintf("Camera \"%s\" is in use",
3193 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003194 errorCode = ERROR_CAMERA_IN_USE;
3195 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003196 default:
Austin Borgered99f642023-06-01 16:51:35 -07003197 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003198 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003199 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003200 errorCode = ERROR_INVALID_OPERATION;
3201 }
Austin Borgered99f642023-06-01 16:51:35 -07003202 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3203 logServiceError(msg, errorCode);
3204 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003205 }
3206
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003207 {
3208 // update the link to client's death
3209 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003210 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003211 if (enabled) {
3212 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003213 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003214 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003215 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003216 mTorchClientMap.replaceValueAt(index, clientBinder);
3217 }
3218 clientBinder->linkToDeath(this);
3219 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003220 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003221 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003222 }
3223
Austin Borger22c5c852024-03-08 13:31:36 -08003224 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003225 std::string torchState = enabled ? "on" : "off";
3226 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3227 torchState.c_str(), clientPid);
3228 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003229 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003230}
3231
Austin Borgered99f642023-06-01 16:51:35 -07003232void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3233 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3234 mTorchUidMap[cameraId].first = uid;
3235 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003236 } else {
3237 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003238 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003239 }
3240}
3241
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003242Status CameraService::notifySystemEvent(int32_t eventId,
3243 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003244 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003245 const int selfPid = getpid();
3246
3247 // Permission checks
3248 if (pid != selfPid) {
3249 // Ensure we're being called by system_server, or similar process with
3250 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003251 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003252 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003253 ALOGE("Permission Denial: cannot send updates to camera service about system"
3254 " events from pid=%d, uid=%d", pid, uid);
3255 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003256 "No permission to send updates to camera service about system events"
3257 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003258 }
3259 }
3260
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003261 ATRACE_CALL();
3262
Ruben Brunk36597b22015-03-20 22:15:57 -07003263 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003264 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003265 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003266 // from a system server crash
3267 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003268 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003269 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003270 break;
3271 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003272 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3273 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003274 if (args.size() != 1) {
3275 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3276 "USB Device Event requires 1 argument");
3277 }
3278
Valentin Iftime29e2e152021-08-13 15:17:33 +02003279 // Notify CameraProviderManager for lazy HALs
3280 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3281 std::to_string(args[0]));
3282 break;
3283 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003284 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003285 default: {
3286 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3287 eventId);
3288 break;
3289 }
3290 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003291 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003292}
3293
Emilian Peev53722fa2019-02-22 17:47:20 -08003294void CameraService::notifyMonitoredUids() {
3295 Mutex::Autolock lock(mStatusListenerLock);
3296
3297 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003298 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003299 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3300 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003301 }
3302}
3303
Austin Borgerdddb7552023-03-30 17:53:01 -07003304void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3305 Mutex::Autolock lock(mStatusListenerLock);
3306
3307 for (const auto& it : mListenerList) {
3308 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3309 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3310 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3311 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3312 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3313 }
3314 }
3315}
3316
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003317Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003318 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003319 const int selfPid = getpid();
3320
3321 // Permission checks
3322 if (pid != selfPid) {
3323 // Ensure we're being called by system_server, or similar process with
3324 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003325 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003326 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003327 ALOGE("Permission Denial: cannot send updates to camera service about device"
3328 " state changes from pid=%d, uid=%d", pid, uid);
3329 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3330 "No permission to send updates to camera service about device state"
3331 " changes from pid=%d, uid=%d", pid, uid);
3332 }
3333 }
3334
3335 ATRACE_CALL();
3336
Austin Borger18b30a72022-10-27 12:20:29 -07003337 {
3338 Mutex::Autolock lock(mServiceLock);
3339 mDeviceState = newState;
3340 }
3341
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003342 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003343
3344 return Status::ok();
3345}
3346
Emilian Peev8b64f282021-03-25 16:49:57 -07003347Status CameraService::notifyDisplayConfigurationChange() {
3348 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003349 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003350 const int selfPid = getpid();
3351
3352 // Permission checks
3353 if (callingPid != selfPid) {
3354 // Ensure we're being called by system_server, or similar process with
3355 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003356 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003357 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003358 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3359 " changes from pid=%d, uid=%d", callingPid, uid);
3360 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3361 "No permission to send updates to camera service about orientation"
3362 " changes from pid=%d, uid=%d", callingPid, uid);
3363 }
3364 }
3365
3366 Mutex::Autolock lock(mServiceLock);
3367
3368 // Don't do anything if rotate-and-crop override via cmd is active
3369 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3370
3371 const auto clients = mActiveClientManager.getAll();
3372 for (auto& current : clients) {
3373 if (current != nullptr) {
3374 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003375 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3376 basicClient->setRotateAndCropOverride(
3377 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3378 basicClient->getPackageName(),
3379 basicClient->getCameraFacing(),
3380 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003381 }
3382 }
3383 }
3384
3385 return Status::ok();
3386}
3387
Biswarup Pal37a75182024-01-16 15:53:35 +00003388// TODO(b/291736219): This to be made device-aware.
Emilian Peev8b64f282021-03-25 16:49:57 -07003389Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003390 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3391 ATRACE_CALL();
3392 if (!concurrentCameraIds) {
3393 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3394 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3395 }
3396
3397 if (!mInitialized) {
3398 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003399 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003400 return STATUS_ERROR(ERROR_DISCONNECTED,
3401 "Camera subsystem is not available");
3402 }
3403 // First call into the provider and get the set of concurrent camera
3404 // combinations
3405 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003406 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003407 for (auto &combination : concurrentCameraCombinations) {
3408 std::vector<std::string> validCombination;
3409 for (auto &cameraId : combination) {
3410 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003411 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003412 if (state == nullptr) {
3413 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3414 continue;
3415 }
3416 StatusInternal status = state->getStatus();
3417 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3418 continue;
3419 }
Austin Borgered99f642023-06-01 16:51:35 -07003420 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003421 continue;
3422 }
3423 validCombination.push_back(cameraId);
3424 }
3425 if (validCombination.size() != 0) {
3426 concurrentCameraIds->push_back(std::move(validCombination));
3427 }
3428 }
3429 return Status::ok();
3430}
3431
3432Status CameraService::isConcurrentSessionConfigurationSupported(
3433 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003434 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003435 if (!isSupported) {
3436 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3437 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3438 }
3439
3440 if (!mInitialized) {
3441 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3442 return STATUS_ERROR(ERROR_DISCONNECTED,
3443 "Camera subsystem is not available");
3444 }
3445
3446 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003447 int callingPid = getCallingPid();
3448 int callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003449 bool hasCameraPermission = ((callingPid == getpid()) ||
3450 hasPermissionsForCamera(callingPid, callingUid));
3451 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003452 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3453 "android.permission.CAMERA needed to call"
3454 "isConcurrentSessionConfigurationSupported");
3455 }
3456
3457 status_t res =
3458 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003459 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3460 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003461 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003462 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003463 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003464 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3465 "support %s (%d)", strerror(-res), res);
3466 }
3467 return Status::ok();
3468}
3469
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003470Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3471 /*out*/
3472 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003473 return addListenerHelper(listener, cameraStatuses);
3474}
3475
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003476binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3477 std::vector<hardware::CameraStatus>* cameraStatuses) {
3478 return addListenerHelper(listener, cameraStatuses, false, true);
3479}
3480
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003481Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3482 /*out*/
3483 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003484 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003485 ATRACE_CALL();
3486
Igor Murashkinbfc99152013-02-27 12:55:20 -08003487 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003488
Ruben Brunk3450ba72015-06-16 11:00:37 -07003489 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003490 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003491 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003492 }
3493
Austin Borger22c5c852024-03-08 13:31:36 -08003494 auto clientPid = getCallingPid();
3495 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003496 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003497
Igor Murashkinbfc99152013-02-27 12:55:20 -08003498 Mutex::Autolock lock(mServiceLock);
3499
Ruben Brunkcc776712015-02-17 20:18:47 -08003500 {
3501 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003502 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003503 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003504 ALOGW("%s: Tried to add listener %p which was already subscribed",
3505 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003506 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003507 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003508 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003509
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003510 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003511 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3512 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003513 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003514 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003515 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003516 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003517 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3518 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3519 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003520 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003521 // The listener still needs to be added to the list of listeners, regardless of what
3522 // permissions the listener process has / whether it is a vendor listener. Since it might be
3523 // eligible to listen to other camera ids.
3524 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003525 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003526 }
3527
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003528 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003529 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003530 Mutex::Autolock lock(mCameraStatesLock);
3531 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003532 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3533 auto [deviceId, mappedCameraId] =
3534 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3535
3536 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003537 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003538 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3539 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003540 }
3541 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003542 // Remove the camera statuses that should be hidden from the client, we do
3543 // this after collecting the states in order to avoid holding
3544 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3545 // the same time.
3546 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3547 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003548 std::string cameraId = s.cameraId;
3549 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
3550 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM,
3551 clientUid);
3552 if (!cameraIdOptional.has_value()) {
3553 std::string msg =
3554 fmt::sprintf(
3555 "Camera %s: Invalid camera id for device id %d",
3556 s.cameraId.c_str(), s.deviceId);
3557 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3558 return true;
3559 }
3560 cameraId = cameraIdOptional.value();
3561 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3562 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3563 ALOGE("%s: Invalid camera id %s, skipping status update",
3564 __FUNCTION__, s.cameraId.c_str());
3565 return true;
3566 }
3567 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3568 clientUid);
3569 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003570
Biswarup Pal37a75182024-01-16 15:53:35 +00003571 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003572 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003573 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003574 // Add only default device cameras here, as virtual cameras currently don't support torch
3575 // anyway. Note that this is a simplification of the implementation here, and we should
3576 // change this when virtual cameras support torch.
3577 if (s.deviceId == kDefaultDeviceId) {
3578 idsChosenForCallback.insert(s.cameraId);
3579 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003580 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003581
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003582 /*
3583 * Immediately signal current torch status to this listener only
3584 * This may be a subset of all the devices, so don't include it in the response directly
3585 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003586 {
3587 Mutex::Autolock al(mTorchStatusMutex);
3588 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003589 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003590 // The camera id is visible to the client. Fine to send torch
3591 // callback.
3592 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003593 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3594 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003595 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003596 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003597 }
3598
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003599 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003600}
Ruben Brunkcc776712015-02-17 20:18:47 -08003601
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003602Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003603 ATRACE_CALL();
3604
Igor Murashkinbfc99152013-02-27 12:55:20 -08003605 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3606
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003607 if (listener == 0) {
3608 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003609 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003610 }
3611
Igor Murashkinbfc99152013-02-27 12:55:20 -08003612 Mutex::Autolock lock(mServiceLock);
3613
Ruben Brunkcc776712015-02-17 20:18:47 -08003614 {
3615 Mutex::Autolock lock(mStatusListenerLock);
3616 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003617 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003618 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003619 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003620 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003621 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003622 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003623 }
3624 }
3625
3626 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3627 __FUNCTION__, listener.get());
3628
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003629 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003630}
3631
Austin Borgered99f642023-06-01 16:51:35 -07003632Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003633
3634 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003635 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3636
3637 if (parameters == NULL) {
3638 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003639 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003640 }
3641
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003642 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003643
3644 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003645 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003646 // Error logged by caller
3647 return ret;
3648 }
3649
3650 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003651
Austin Borgered99f642023-06-01 16:51:35 -07003652 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003653
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003654 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003655}
3656
Austin Borgered99f642023-06-01 16:51:35 -07003657Status CameraService::supportsCameraApi(const std::string& unresolvedCameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003658 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003659 ATRACE_CALL();
3660
malikakashedb38962023-09-06 00:03:35 +00003661 const std::string cameraId = resolveCameraId(
Austin Borger22c5c852024-03-08 13:31:36 -08003662 unresolvedCameraId, getCallingUid());
malikakash82ed4352023-07-21 22:44:34 +00003663
Austin Borgered99f642023-06-01 16:51:35 -07003664 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003665
3666 switch (apiVersion) {
3667 case API_VERSION_1:
3668 case API_VERSION_2:
3669 break;
3670 default:
Austin Borgered99f642023-06-01 16:51:35 -07003671 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3672 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3673 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003674 }
3675
Austin Borger18b30a72022-10-27 12:20:29 -07003676 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -07003677 auto deviceVersionAndTransport = getDeviceVersion(cameraId, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003678 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003679 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3680 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3681 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003682 }
3683 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3684 int deviceVersion = deviceVersionAndTransport.first;
3685 switch (deviceVersion) {
3686 case CAMERA_DEVICE_API_VERSION_1_0:
3687 case CAMERA_DEVICE_API_VERSION_3_0:
3688 case CAMERA_DEVICE_API_VERSION_3_1:
3689 if (apiVersion == API_VERSION_2) {
3690 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003691 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003692 *isSupported = false;
3693 } else { // if (apiVersion == API_VERSION_1) {
3694 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003695 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003696 *isSupported = true;
3697 }
3698 break;
3699 case CAMERA_DEVICE_API_VERSION_3_2:
3700 case CAMERA_DEVICE_API_VERSION_3_3:
3701 case CAMERA_DEVICE_API_VERSION_3_4:
3702 case CAMERA_DEVICE_API_VERSION_3_5:
3703 case CAMERA_DEVICE_API_VERSION_3_6:
3704 case CAMERA_DEVICE_API_VERSION_3_7:
3705 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003706 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003707 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003708 break;
3709 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003710 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3711 deviceVersion, cameraId.c_str());
3712 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3713 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003714 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003715 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003716 } else {
3717 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003718 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003719 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003720}
3721
Austin Borgered99f642023-06-01 16:51:35 -07003722Status CameraService::isHiddenPhysicalCamera(const std::string& unresolvedCameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003723 /*out*/ bool *isSupported) {
3724 ATRACE_CALL();
3725
malikakashedb38962023-09-06 00:03:35 +00003726 const std::string cameraId = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08003727 getCallingUid());
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003728
Austin Borgered99f642023-06-01 16:51:35 -07003729 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3730 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003731
3732 return Status::ok();
3733}
3734
Cliff Wud8cae102021-03-11 01:37:42 +08003735Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003736 const std::string& packageName, const std::string& internalCamId,
3737 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003738 const sp<ICameraInjectionCallback>& callback,
3739 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003740 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003741 ATRACE_CALL();
3742
Austin Borgered99f642023-06-01 16:51:35 -07003743 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003744 const int pid = getCallingPid();
3745 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003746 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3747 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003748 "Permission Denial: no permission to inject camera");
3749 }
3750
3751 // Do not allow any camera injection that injects or replaces a virtual camera.
3752 auto [deviceIdForInternalCamera, _] =
3753 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3754 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3755 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3756 "Cannot replace a virtual camera");
3757 }
3758 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3759 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3760 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3761 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3762 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003763 }
3764
3765 ALOGV(
3766 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3767 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003768 __FUNCTION__, packageName.c_str(),
3769 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003770
Cliff Wud3a05312021-04-26 23:07:31 +08003771 {
3772 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003773 mInjectionInternalCamId = internalCamId;
3774 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003775 mInjectionStatusListener->addListener(callback);
3776 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003777 status_t res = NO_ERROR;
3778 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3779 // If the client already exists, we can directly connect to the camera device through the
3780 // client's injectCamera(), otherwise we need to wait until the client is established
3781 // (execute connectHelper()) before injecting the camera to the camera device.
3782 if (clientDescriptor != nullptr) {
3783 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003784 sp<BasicClient> clientSp = clientDescriptor->getValue();
3785 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3786 if(res != OK) {
3787 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3788 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003789 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003790 }
3791 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003792 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003793 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3794 }
3795 } else {
3796 mInjectionInitPending = true;
3797 }
3798 }
Cliff Wud8cae102021-03-11 01:37:42 +08003799
Cliff Wud3a05312021-04-26 23:07:31 +08003800 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003801}
3802
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003803Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003804 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003805 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3806 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3807 return Status::ok();
3808}
3809
Ruben Brunkcc776712015-02-17 20:18:47 -08003810void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003811 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003812 for (auto& i : mActiveClientManager.getAll()) {
3813 auto clientSp = i->getValue();
3814 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003815 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003816 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003817 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003818 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003819 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003820}
3821
Ruben Brunkcc776712015-02-17 20:18:47 -08003822bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003823 bool ret = false;
3824 {
3825 // Acquire mServiceLock and prevent other clients from connecting
3826 std::unique_ptr<AutoConditionLock> lock =
3827 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003828
Ruben Brunkcc776712015-02-17 20:18:47 -08003829 std::vector<sp<BasicClient>> evicted;
3830 for (auto& i : mActiveClientManager.getAll()) {
3831 auto clientSp = i->getValue();
3832 if (clientSp.get() == nullptr) {
3833 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3834 mActiveClientManager.remove(i);
3835 continue;
3836 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003837 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003838 mActiveClientManager.remove(i);
3839 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003840
Ruben Brunkcc776712015-02-17 20:18:47 -08003841 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003842 clientSp->notifyError(
3843 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003844 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003845 }
3846 }
3847
Ruben Brunkcc776712015-02-17 20:18:47 -08003848 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3849 // other clients from connecting in mServiceLockWrapper if held
3850 mServiceLock.unlock();
3851
Ruben Brunk36597b22015-03-20 22:15:57 -07003852 // Do not clear caller identity, remote caller should be client proccess
3853
Ruben Brunkcc776712015-02-17 20:18:47 -08003854 for (auto& i : evicted) {
3855 if (i.get() != nullptr) {
3856 i->disconnect();
3857 ret = true;
3858 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003859 }
3860
Ruben Brunkcc776712015-02-17 20:18:47 -08003861 // Reacquire mServiceLock
3862 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003863
Ruben Brunkcc776712015-02-17 20:18:47 -08003864 } // lock is destroyed, allow further connect calls
3865
3866 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003867}
3868
Ruben Brunkcc776712015-02-17 20:18:47 -08003869std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003870 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003871 std::shared_ptr<CameraState> state;
3872 {
3873 Mutex::Autolock lock(mCameraStatesLock);
3874 auto iter = mCameraStates.find(cameraId);
3875 if (iter != mCameraStates.end()) {
3876 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003877 }
3878 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003879 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003880}
3881
Austin Borgered99f642023-06-01 16:51:35 -07003882sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003883 // Remove from active clients list
3884 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3885 if (clientDescriptorPtr == nullptr) {
3886 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003887 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003888 return sp<BasicClient>{nullptr};
3889 }
3890
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003891 sp<BasicClient> client = clientDescriptorPtr->getValue();
3892 if (client.get() != nullptr) {
3893 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3894 }
3895 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003896}
3897
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003898void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003899 // Acquire mServiceLock and prevent other clients from connecting
3900 std::unique_ptr<AutoConditionLock> lock =
3901 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3902
Ruben Brunk6267b532015-04-30 17:44:07 -07003903 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003904 for (size_t i = 0; i < newUserIds.size(); i++) {
3905 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003906 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003907 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003908 return;
3909 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003910 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003911 }
3912
Ruben Brunka8ca9152015-04-07 14:23:40 -07003913
Ruben Brunk6267b532015-04-30 17:44:07 -07003914 if (newAllowedUsers == mAllowedUsers) {
3915 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3916 return;
3917 }
3918
3919 logUserSwitch(mAllowedUsers, newAllowedUsers);
3920
3921 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003922
3923 // Current user has switched, evict all current clients.
3924 std::vector<sp<BasicClient>> evicted;
3925 for (auto& i : mActiveClientManager.getAll()) {
3926 auto clientSp = i->getValue();
3927
3928 if (clientSp.get() == nullptr) {
3929 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3930 continue;
3931 }
3932
Ruben Brunk6267b532015-04-30 17:44:07 -07003933 // Don't evict clients that are still allowed.
3934 uid_t clientUid = clientSp->getClientUid();
3935 userid_t clientUserId = multiuser_get_user_id(clientUid);
3936 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3937 continue;
3938 }
3939
Ruben Brunk36597b22015-03-20 22:15:57 -07003940 evicted.push_back(clientSp);
3941
Ruben Brunk36597b22015-03-20 22:15:57 -07003942 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003943 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003944
Ruben Brunk36597b22015-03-20 22:15:57 -07003945 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003946 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003947 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003948 " to user switch.", i->getKey().c_str(),
3949 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003950 i->getOwnerId(), i->getPriority().getScore(),
3951 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003952
3953 }
3954
3955 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3956 // blocking other clients from connecting in mServiceLockWrapper if held.
3957 mServiceLock.unlock();
3958
3959 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08003960 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003961
3962 for (auto& i : evicted) {
3963 i->disconnect();
3964 }
3965
Austin Borger22c5c852024-03-08 13:31:36 -08003966 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003967
3968 // Reacquire mServiceLock
3969 mServiceLock.lock();
3970}
Ruben Brunkcc776712015-02-17 20:18:47 -08003971
Austin Borgered99f642023-06-01 16:51:35 -07003972void CameraService::logEvent(const std::string &event) {
3973 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003974 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003975 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003976 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003977 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003978 mEventLog.add(msg);
3979 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3980 // Error event not added to the dumpsys log before
3981 mEventLog.add(msg);
3982 sServiceErrorEventSet.insert(msg);
3983 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003984}
3985
Austin Borgered99f642023-06-01 16:51:35 -07003986void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3987 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003988 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003989 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3990 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003991}
3992
Austin Borgered99f642023-06-01 16:51:35 -07003993void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3994 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003995 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003996 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3997 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003998}
3999
Austin Borgered99f642023-06-01 16:51:35 -07004000void CameraService::logConnected(const std::string &cameraId, int clientPid,
4001 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004002 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004003 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
4004 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004005}
4006
Austin Borgered99f642023-06-01 16:51:35 -07004007void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
4008 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004009 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004010 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
4011 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004012}
4013
Austin Borgered99f642023-06-01 16:51:35 -07004014void CameraService::logRejected(const std::string &cameraId, int clientPid,
4015 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004016 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07004017 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
4018 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004019}
4020
Austin Borgered99f642023-06-01 16:51:35 -07004021void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
4022 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07004023 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07004024 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
4025 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07004026}
4027
Ruben Brunk6267b532015-04-30 17:44:07 -07004028void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
4029 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07004030 std::string newUsers = toString(newUserIds);
4031 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004032 if (oldUsers.size() == 0) {
4033 oldUsers = "<None>";
4034 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07004035 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07004036 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
4037 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004038}
4039
Austin Borgered99f642023-06-01 16:51:35 -07004040void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004041 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004042 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004043}
4044
Austin Borgered99f642023-06-01 16:51:35 -07004045void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004046 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004047 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004048}
4049
Austin Borgered99f642023-06-01 16:51:35 -07004050void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004051 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004052 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07004053}
4054
Austin Borgered99f642023-06-01 16:51:35 -07004055void CameraService::logServiceError(const std::string &msg, int errorCode) {
4056 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
4057 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004058}
4059
Ruben Brunk36597b22015-03-20 22:15:57 -07004060status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4061 uint32_t flags) {
4062
Mathias Agopian65ab4712010-07-14 17:59:35 -07004063 // Permission checks
4064 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004065 case SHELL_COMMAND_TRANSACTION: {
4066 int in = data.readFileDescriptor();
4067 int out = data.readFileDescriptor();
4068 int err = data.readFileDescriptor();
4069 int argc = data.readInt32();
4070 Vector<String16> args;
4071 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
4072 args.add(data.readString16());
4073 }
4074 sp<IBinder> unusedCallback;
4075 sp<IResultReceiver> resultReceiver;
4076 status_t status;
4077 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
4078 return status;
4079 }
4080 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
4081 return status;
4082 }
4083 status = shellCommand(in, out, err, args);
4084 if (resultReceiver != nullptr) {
4085 resultReceiver->send(status);
4086 }
4087 return NO_ERROR;
4088 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004089 }
4090
4091 return BnCameraService::onTransact(code, data, reply, flags);
4092}
4093
Mathias Agopian65ab4712010-07-14 17:59:35 -07004094// We share the media players for shutter and recording sound for all clients.
4095// A reference count is kept to determine when we will actually release the
4096// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09004097sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
4098 sp<MediaPlayer> mp = new MediaPlayer();
4099 status_t error;
4100 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08004101 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09004102 error = mp->prepare();
4103 }
4104 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004105 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09004106 mp->disconnect();
4107 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004108 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004109 }
4110 return mp;
4111}
4112
username5755fea2018-12-27 09:48:08 +08004113void CameraService::increaseSoundRef() {
4114 Mutex::Autolock lock(mSoundLock);
4115 mSoundRef++;
4116}
4117
4118void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004119 ATRACE_CALL();
4120
username5755fea2018-12-27 09:48:08 +08004121 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
4122 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
4123 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
4124 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
4125 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4126 }
4127 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
4128 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4129 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4130 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004131 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08004132 }
4133 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4134 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4135 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4136 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4137 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004138 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004139}
4140
username5755fea2018-12-27 09:48:08 +08004141void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004142 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004143 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004144 if (--mSoundRef) return;
4145
4146 for (int i = 0; i < NUM_SOUNDS; i++) {
4147 if (mSoundPlayer[i] != 0) {
4148 mSoundPlayer[i]->disconnect();
4149 mSoundPlayer[i].clear();
4150 }
4151 }
4152}
4153
4154void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004155 ATRACE_CALL();
4156
Mathias Agopian65ab4712010-07-14 17:59:35 -07004157 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004158 if (kind < 0 || kind >= NUM_SOUNDS) {
4159 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4160 return;
4161 }
4162
Mathias Agopian65ab4712010-07-14 17:59:35 -07004163 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004164 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004165 sp<MediaPlayer> player = mSoundPlayer[kind];
4166 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004167 player->seekTo(0);
4168 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004169 }
4170}
4171
4172// ----------------------------------------------------------------------------
4173
4174CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004175 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004176 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004177 const std::string& clientPackageName, bool systemNativeClient,
4178 const std::optional<std::string>& clientFeatureId,
4179 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004180 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004181 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004182 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004183 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004184 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07004185 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004186 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004187 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004188 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004189 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004190 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004191{
Austin Borger22c5c852024-03-08 13:31:36 -08004192 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004193 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004194
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004195 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004196
username5755fea2018-12-27 09:48:08 +08004197 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004198
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004199 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004200}
4201
Mathias Agopian65ab4712010-07-14 17:59:35 -07004202// tear down the client
4203CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004204 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004205 mDestructionStarted = true;
4206
username5755fea2018-12-27 09:48:08 +08004207 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004208 // unconditionally disconnect. function is idempotent
4209 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004210}
4211
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004212sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4213
Igor Murashkin634a5152013-02-20 17:15:11 -08004214CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004215 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004216 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004217 const std::string& clientPackageName, bool nativeClient,
4218 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004219 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004220 int servicePid, bool overrideToPortrait):
Austin Borger249e6592024-03-10 22:28:11 -07004221 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004222 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004223 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004224 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4225 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004226 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004227 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004228 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07004229 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004230 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004231 mRemoteBinder(remoteCallback),
4232 mOpsActive(false),
4233 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004234{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004235 if (sCameraService == nullptr) {
4236 sCameraService = cameraService;
4237 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004238
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004239 // There are 2 scenarios in which a client won't have AppOps operations
4240 // (both scenarios : native clients)
4241 // 1) It's an system native client*, the package name will be empty
4242 // and it will return from this function in the previous if condition
4243 // (This is the same as the previously existing behavior).
4244 // 2) It is a system native client, but its package name has been
4245 // modified for debugging, however it still must not use AppOps since
4246 // the package name is not a real one.
4247 //
4248 // * system native client - native client with UID < AID_APP_START. It
4249 // doesn't exclude clients not on the system partition.
4250 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004251 mAppOpsManager = std::make_unique<AppOpsManager>();
4252 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004253
Charles Chenf075f082024-03-04 23:32:55 +00004254 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004255}
4256
4257CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004258 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004259 mDestructionStarted = true;
4260}
4261
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004262binder::Status CameraService::BasicClient::disconnect() {
4263 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004264 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004265 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004266 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004267 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004268
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004269 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004270 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004271 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004272 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004273
4274 sp<IBinder> remote = getRemote();
4275 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004276 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004277 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004278
4279 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004280 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004281 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004282 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004283 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004284
Igor Murashkincba2c162013-03-20 15:56:31 -07004285 // client shouldn't be able to call into us anymore
4286 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004287
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004288 const auto& mActivityManager = getActivityManager();
4289 if (mActivityManager) {
4290 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004291 getCallingUid(),
4292 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004293 }
4294
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004295 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004296}
4297
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004298status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4299 // No dumping of clients directly over Binder,
4300 // must go through CameraService::dump
4301 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004302 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004303 return OK;
4304}
4305
Austin Borgered99f642023-06-01 16:51:35 -07004306status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004307 // Can't watch tags directly, must go through CameraService::startWatchingTags
4308 return OK;
4309}
4310
4311status_t CameraService::BasicClient::stopWatchingTags(int) {
4312 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4313 return OK;
4314}
4315
4316status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4317 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4318 return OK;
4319}
4320
Austin Borgered99f642023-06-01 16:51:35 -07004321std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004322 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004323}
4324
Emilian Peev8b64f282021-03-25 16:49:57 -07004325int CameraService::BasicClient::getCameraFacing() const {
4326 return mCameraFacing;
4327}
4328
4329int CameraService::BasicClient::getCameraOrientation() const {
4330 return mOrientation;
4331}
Ruben Brunkcc776712015-02-17 20:18:47 -08004332
4333int CameraService::BasicClient::getClientPid() const {
4334 return mClientPid;
4335}
4336
Ruben Brunk6267b532015-04-30 17:44:07 -07004337uid_t CameraService::BasicClient::getClientUid() const {
4338 return mClientUid;
4339}
4340
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004341bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4342 // Defaults to API2.
4343 return level == API_2;
4344}
4345
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004346status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004347 {
4348 Mutex::Autolock l(mAudioRestrictionLock);
4349 mAudioRestriction = mode;
4350 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004351 sCameraService->updateAudioRestriction();
4352 return OK;
4353}
4354
4355int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004356 return sCameraService->updateAudioRestriction();
4357}
4358
4359int32_t CameraService::BasicClient::getAudioRestriction() const {
4360 Mutex::Autolock l(mAudioRestrictionLock);
4361 return mAudioRestriction;
4362}
4363
4364bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4365 switch (mode) {
4366 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4367 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4368 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4369 return true;
4370 default:
4371 return false;
4372 }
4373}
4374
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004375status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4376 if (mode == AppOpsManager::MODE_ERRORED) {
4377 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004378 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004379 return PERMISSION_DENIED;
4380 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4381 // If the calling Uid is trusted (a native service), the AppOpsManager could
4382 // return MODE_IGNORED. Do not treat such case as error.
4383 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4384 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004385
4386 bool isCameraPrivacyEnabled;
4387 if (flags::camera_privacy_allowlist()) {
4388 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4389 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4390 } else {
4391 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004392 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004393 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004394 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4395 // We prefer to successfully open the camera and perform camera muting
4396 // or blocking in connectHelper as handleAppOpMode can be called before the
4397 // connection has been fully established and at that time camera muting
4398 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004399 if (!isUidActive || !isCameraPrivacyEnabled) {
4400 ALOGI("Camera %s: Access for \"%s\" has been restricted",
Austin Borgered99f642023-06-01 16:51:35 -07004401 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004402 // Return the same error as for device policy manager rejection
4403 return -EACCES;
4404 }
4405 }
4406 return OK;
4407}
4408
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004409status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004410 ATRACE_CALL();
4411
Igor Murashkine6800ce2013-03-04 17:25:57 -08004412 {
4413 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004414 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004415 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004416 if (mAppOpsManager != nullptr) {
4417 // Notify app ops that the camera is not available
4418 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004419
4420 if (flags::watch_foreground_changes()) {
4421 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4422 toString16(mClientPackageName),
4423 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4424 } else {
4425 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004426 toString16(mClientPackageName), mOpsCallback);
Austin Borgerca1e0062023-06-28 11:32:55 -07004427 }
Igor Murashkine6800ce2013-03-04 17:25:57 -08004428
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004429 // Just check for camera acccess here on open - delay startOp until
4430 // camera frames start streaming in startCameraStreamingOps
4431 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004432 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004433 status_t res = handleAppOpMode(mode);
4434 if (res != OK) {
4435 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004436 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004437 }
4438
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004439 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004440
4441 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004442 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004443
Austin Borgerdddb7552023-03-30 17:53:01 -07004444 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004445
Shuzhen Wang695044d2020-03-06 09:02:23 -08004446 // Notify listeners of camera open/close status
4447 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4448
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004449 return OK;
4450}
4451
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004452status_t CameraService::BasicClient::startCameraStreamingOps() {
4453 ATRACE_CALL();
4454
4455 if (!mOpsActive) {
4456 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4457 return INVALID_OPERATION;
4458 }
4459 if (mOpsStreaming) {
4460 ALOGV("%s: Streaming already active!", __FUNCTION__);
4461 return OK;
4462 }
4463
4464 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004465 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004466
4467 if (mAppOpsManager != nullptr) {
4468 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004469 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4470 toString16(mClientFeatureId),
4471 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004472 status_t res = handleAppOpMode(mode);
4473 if (res != OK) {
4474 return res;
4475 }
4476 }
4477
4478 mOpsStreaming = true;
4479
4480 return OK;
4481}
4482
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004483status_t CameraService::BasicClient::noteAppOp() {
4484 ATRACE_CALL();
4485
4486 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004487 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004488
4489 // noteAppOp is only used for when camera mute is not supported, in order
4490 // to trigger the sensor privacy "Unblock" dialog
4491 if (mAppOpsManager != nullptr) {
4492 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004493 toString16(mClientPackageName), toString16(mClientFeatureId),
4494 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004495 status_t res = handleAppOpMode(mode);
4496 if (res != OK) {
4497 return res;
4498 }
4499 }
4500
4501 return OK;
4502}
4503
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004504status_t CameraService::BasicClient::finishCameraStreamingOps() {
4505 ATRACE_CALL();
4506
4507 if (!mOpsActive) {
4508 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4509 return INVALID_OPERATION;
4510 }
4511 if (!mOpsStreaming) {
4512 ALOGV("%s: Streaming not active!", __FUNCTION__);
4513 return OK;
4514 }
4515
4516 if (mAppOpsManager != nullptr) {
4517 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004518 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004519 mOpsStreaming = false;
4520 }
4521
4522 return OK;
4523}
4524
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004525status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004526 ATRACE_CALL();
4527
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004528 if (mOpsStreaming) {
4529 // Make sure we've notified everyone about camera stopping
4530 finishCameraStreamingOps();
4531 }
4532
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004533 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004534 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004535 mOpsActive = false;
4536
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004537 // This function is called when a client disconnects. This should
4538 // release the camera, but actually only if it was in a proper
4539 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004540 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004541 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004542
Ruben Brunkcc776712015-02-17 20:18:47 -08004543 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004544 sCameraService->updateStatus(StatusInternal::PRESENT,
4545 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004546 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004547 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004548 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4549 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004550 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004551 mOpsCallback.clear();
4552
Austin Borgerdddb7552023-03-30 17:53:01 -07004553 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004554
Shuzhen Wang695044d2020-03-06 09:02:23 -08004555 // Notify listeners of camera open/close status
4556 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4557
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004558 return OK;
4559}
4560
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004561void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004562 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004563 if (mAppOpsManager == nullptr) {
4564 return;
4565 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004566 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004567 if (op != AppOpsManager::OP_CAMERA) {
4568 ALOGW("Unexpected app ops notification received: %d", op);
4569 return;
4570 }
4571
4572 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004573 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004574 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004575 ALOGV("checkOp returns: %d, %s ", res,
4576 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4577 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4578 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4579 "UNKNOWN");
4580
Shuzhen Wang64900852021-02-05 09:03:29 -08004581 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004582 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4583 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004584 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004585 } else if (res == AppOpsManager::MODE_IGNORED) {
4586 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004587
Austin Borgerca1e0062023-06-28 11:32:55 -07004588 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4589 // If not visible, but still active, then we want to block instead of muting the camera.
4590 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4591 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4592
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004593 bool isCameraPrivacyEnabled;
4594 if (flags::camera_privacy_allowlist()) {
4595 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4596 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4597 } else {
4598 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004599 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004600 }
4601
4602 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004603 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4604 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4605 isCameraPrivacyEnabled);
4606 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4607 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4608 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004609 if (!mUidIsTrusted) {
Austin Borgerca1e0062023-06-28 11:32:55 -07004610 if (flags::watch_foreground_changes()) {
4611 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4612 setCameraMute(true);
4613 } else {
4614 block();
4615 }
4616 } else {
4617 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4618 setCameraMute(true);
4619 } else if (!isUidActive
4620 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4621 block();
4622 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004623 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004624 }
Evan Severson09ab4002021-02-10 14:15:19 -08004625 } else if (res == AppOpsManager::MODE_ALLOWED) {
4626 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004627 }
4628}
4629
Svet Ganova453d0d2018-01-11 15:37:58 -08004630void CameraService::BasicClient::block() {
4631 ATRACE_CALL();
4632
4633 // Reset the client PID to allow server-initiated disconnect,
4634 // and to prevent further calls by client.
Austin Borger22c5c852024-03-08 13:31:36 -08004635 mClientPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004636 CaptureResultExtras resultExtras; // a dummy result (invalid)
4637 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4638 disconnect();
4639}
4640
Mathias Agopian65ab4712010-07-14 17:59:35 -07004641// ----------------------------------------------------------------------------
4642
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004643void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004644 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004645 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004646 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4647 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4648 api1ErrorCode = CAMERA_ERROR_DISABLED;
4649 }
4650 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004651 } else {
4652 ALOGE("mRemoteCallback is NULL!!");
4653 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004654}
4655
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004656// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004657binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004658 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004659 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004660}
4661
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004662bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4663 return level == API_1;
4664}
4665
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004666CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4667 mClient(client) {
4668}
4669
4670void CameraService::Client::OpsCallback::opChanged(int32_t op,
4671 const String16& packageName) {
4672 sp<BasicClient> client = mClient.promote();
4673 if (client != NULL) {
4674 client->opChanged(op, packageName);
4675 }
4676}
4677
Mathias Agopian65ab4712010-07-14 17:59:35 -07004678// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004679// UidPolicy
4680// ----------------------------------------------------------------------------
4681
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004682void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004683 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004684 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004685
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004686 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004687 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004688 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004689 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004690 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4691 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004692 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004693 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004694 if (res == OK) {
4695 mRegistered = true;
4696 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004697 } else {
4698 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004699 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004700}
4701
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004702void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004703 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004704 return;
4705 }
4706
4707 registerWithActivityManager();
4708}
4709
4710void CameraService::UidPolicy::registerSelf() {
4711 // Use check service to see if the activity service is available
4712 // If not available then register for notifications, instead of blocking
4713 // till the service is ready
4714 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004715 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004716 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004717 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004718 } else {
4719 registerWithActivityManager();
4720 }
4721}
4722
Svet Ganova453d0d2018-01-11 15:37:58 -08004723void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004724 Mutex::Autolock _l(mUidLock);
4725
Steven Moreland2f348142019-07-02 15:59:07 -07004726 mAm.unregisterUidObserver(this);
4727 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004728 mRegistered = false;
4729 mActiveUids.clear();
4730 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004731}
4732
4733void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4734 onUidIdle(uid, disabled);
4735}
4736
4737void CameraService::UidPolicy::onUidActive(uid_t uid) {
4738 Mutex::Autolock _l(mUidLock);
4739 mActiveUids.insert(uid);
4740}
4741
4742void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4743 bool deleted = false;
4744 {
4745 Mutex::Autolock _l(mUidLock);
4746 if (mActiveUids.erase(uid) > 0) {
4747 deleted = true;
4748 }
4749 }
4750 if (deleted) {
4751 sp<CameraService> service = mService.promote();
4752 if (service != nullptr) {
4753 service->blockClientsForUid(uid);
4754 }
4755 }
4756}
4757
Emilian Peev53722fa2019-02-22 17:47:20 -08004758void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004759 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004760 bool procStateChange = false;
4761 {
4762 Mutex::Autolock _l(mUidLock);
4763 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4764 mMonitoredUids[uid].procState != procState) {
4765 mMonitoredUids[uid].procState = procState;
4766 procStateChange = true;
4767 }
4768 }
4769
4770 if (procStateChange) {
4771 sp<CameraService> service = mService.promote();
4772 if (service != nullptr) {
4773 service->notifyMonitoredUids();
4774 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004775 }
4776}
4777
Austin Borgerdddb7552023-03-30 17:53:01 -07004778/**
4779 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4780 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4781 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4782 * monitoredUids. If it is revised above some other monitoredUid, signal
4783 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4784 * foreground apps in split screen - state changes will capture all other cases.
4785 */
4786void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4787 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004788 {
4789 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004790 auto it = mMonitoredUids.find(uid);
4791
4792 if (it != mMonitoredUids.end()) {
4793 if (it->second.hasCamera) {
4794 for (auto &monitoredUid : mMonitoredUids) {
4795 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004796 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004797 notifyUidSet.emplace(monitoredUid.first);
4798 }
4799 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004800 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004801 notifyUidSet.emplace(uid);
4802 } else {
4803 for (auto &monitoredUid : mMonitoredUids) {
4804 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004805 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004806 notifyUidSet.emplace(uid);
4807 }
4808 }
4809 }
4810 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004811 }
4812 }
4813
Austin Borgerdddb7552023-03-30 17:53:01 -07004814 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004815 sp<CameraService> service = mService.promote();
4816 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004817 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004818 }
4819 }
4820}
4821
Austin Borgerdddb7552023-03-30 17:53:01 -07004822/**
4823 * Register a uid for monitoring, and note whether it owns a camera.
4824 */
4825void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004826 Mutex::Autolock _l(mUidLock);
4827 auto it = mMonitoredUids.find(uid);
4828 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004829 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004830 } else {
Austin Borger65577682022-02-17 00:25:43 +00004831 MonitoredUid monitoredUid;
4832 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004833 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004834 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004835 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004836 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004837 if (res != OK) {
4838 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4839 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004840 }
4841
4842 if (openCamera) {
4843 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004844 }
4845}
4846
Austin Borgerdddb7552023-03-30 17:53:01 -07004847/**
4848 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4849 */
4850void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004851 Mutex::Autolock _l(mUidLock);
4852 auto it = mMonitoredUids.find(uid);
4853 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004854 it->second.refCount--;
4855 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004856 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004857 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004858 if (res != OK) {
4859 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4860 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004861 } else if (closeCamera) {
4862 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004863 }
4864 } else {
4865 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4866 }
4867}
4868
Austin Borgered99f642023-06-01 16:51:35 -07004869bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004870 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004871 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004872}
4873
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004874static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4875static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004876
Austin Borgered99f642023-06-01 16:51:35 -07004877bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004878 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004879 // If activity manager is unreachable, assume everything is active
4880 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004881 return true;
4882 }
4883 auto it = mOverrideUids.find(uid);
4884 if (it != mOverrideUids.end()) {
4885 return it->second;
4886 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004887 bool active = mActiveUids.find(uid) != mActiveUids.end();
4888 if (!active) {
4889 // We want active UIDs to always access camera with their first attempt since
4890 // there is no guarantee the app is robustly written and would retry getting
4891 // the camera on failure. The inverse case is not a problem as we would take
4892 // camera away soon once we get the callback that the uid is no longer active.
4893 ActivityManager am;
4894 // Okay to access with a lock held as UID changes are dispatched without
4895 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004896 int64_t startTimeMillis = 0;
4897 do {
4898 // TODO: Fix this b/109950150!
4899 // Okay this is a hack. There is a race between the UID turning active and
4900 // activity being resumed. The proper fix is very risky, so we temporary add
4901 // some polling which should happen pretty rarely anyway as the race is hard
4902 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004903 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004904 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004905 if (active) {
4906 break;
4907 }
4908 if (startTimeMillis <= 0) {
4909 startTimeMillis = uptimeMillis();
4910 }
4911 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004912 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004913 if (remainingTimeMillis <= 0) {
4914 break;
4915 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004916 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4917
4918 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004919 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004920 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004921 } while (true);
4922
Svet Ganov7b4ab782018-03-25 12:48:10 -07004923 if (active) {
4924 // Now that we found out the UID is actually active, cache that
4925 mActiveUids.insert(uid);
4926 }
4927 }
4928 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004929}
4930
Varun Shahb42f1eb2019-04-16 14:45:13 -07004931int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4932 Mutex::Autolock _l(mUidLock);
4933 return getProcStateLocked(uid);
4934}
4935
4936int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4937 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4938 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004939 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004940 }
4941 return procState;
4942}
4943
Austin Borgered99f642023-06-01 16:51:35 -07004944void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4945 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004946 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004947}
4948
Austin Borgered99f642023-06-01 16:51:35 -07004949void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004950 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004951}
4952
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004953void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4954 Mutex::Autolock _l(mUidLock);
4955 ALOGV("UidPolicy: ActivityManager has died");
4956 mRegistered = false;
4957 mActiveUids.clear();
4958}
4959
Austin Borgered99f642023-06-01 16:51:35 -07004960void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004961 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004962 bool wasActive = false;
4963 bool isActive = false;
4964 {
4965 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004966 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004967 mOverrideUids.erase(uid);
4968 if (insert) {
4969 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4970 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004971 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004972 }
4973 if (wasActive != isActive && !isActive) {
4974 sp<CameraService> service = mService.promote();
4975 if (service != nullptr) {
4976 service->blockClientsForUid(uid);
4977 }
4978 }
4979}
4980
4981// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004982// SensorPrivacyPolicy
4983// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004984
4985void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4986{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004987 Mutex::Autolock _l(mSensorPrivacyLock);
4988 if (mRegistered) {
4989 return;
4990 }
Evan Severson09ab4002021-02-10 14:15:19 -08004991 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004992 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004993 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004994 mSpm.addToggleSensorPrivacyListener(this);
4995 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004996 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004997 if (flags::camera_privacy_allowlist()) {
4998 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
4999 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
5000 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5001 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005002 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005003 if (res == OK) {
5004 mRegistered = true;
5005 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
5006 }
5007}
5008
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005009void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
5010 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07005011 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005012 return;
5013 }
5014
5015 registerWithSensorPrivacyManager();
5016}
5017
5018void CameraService::SensorPrivacyPolicy::registerSelf() {
5019 // Use checkservice to see if the sensor_privacy service is available
5020 // If service is not available then register for notification
5021 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07005022 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005023 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07005024 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005025 } else {
5026 registerWithSensorPrivacyManager();
5027 }
5028}
5029
Michael Grooverd1d435a2018-12-18 17:39:42 -08005030void CameraService::SensorPrivacyPolicy::unregisterSelf() {
5031 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08005032 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00005033 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005034 mSpm.removeToggleSensorPrivacyListener(this);
5035 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005036 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005037 mRegistered = false;
5038 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
5039}
5040
5041bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005042 if (!mRegistered) {
5043 registerWithSensorPrivacyManager();
5044 }
5045
Michael Grooverd1d435a2018-12-18 17:39:42 -08005046 Mutex::Autolock _l(mSensorPrivacyLock);
5047 return mSensorPrivacyEnabled;
5048}
5049
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005050int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
5051 if (!mRegistered) {
5052 registerWithSensorPrivacyManager();
5053 }
5054
5055 Mutex::Autolock _l(mSensorPrivacyLock);
5056 return mCameraPrivacyState;
5057}
5058
Evan Seversond0b69922022-01-27 10:47:34 -08005059bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08005060 if (!hasCameraPrivacyFeature()) {
5061 return false;
5062 }
Evan Seversond0b69922022-01-27 10:47:34 -08005063 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08005064}
5065
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005066bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
5067 if (!hasCameraPrivacyFeature()) {
5068 return SensorPrivacyManager::DISABLED;
5069 }
5070 return mSpm.isCameraPrivacyEnabled(packageName);
5071}
5072
Evan Seversond0b69922022-01-27 10:47:34 -08005073binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005074 int toggleType, int sensor, bool enabled) {
5075 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
5076 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
5077 {
5078 Mutex::Autolock _l(mSensorPrivacyLock);
5079 mSensorPrivacyEnabled = enabled;
5080 }
5081 // if sensor privacy is enabled then block all clients from accessing the camera
5082 if (enabled) {
5083 sp<CameraService> service = mService.promote();
5084 if (service != nullptr) {
5085 service->blockAllClients();
5086 }
5087 }
5088 }
5089 return binder::Status::ok();
5090}
5091
5092binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
5093 int, int sensor, int state) {
5094 if (!flags::camera_privacy_allowlist()
5095 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
5096 return binder::Status::ok();
5097 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08005098 {
5099 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005100 mCameraPrivacyState = state;
5101 }
5102 sp<CameraService> service = mService.promote();
5103 if (!service) {
5104 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005105 }
5106 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005107 if (state == SensorPrivacyManager::ENABLED) {
5108 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08005109 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005110 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005111 }
5112 return binder::Status::ok();
5113}
5114
5115void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
5116 Mutex::Autolock _l(mSensorPrivacyLock);
5117 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
5118 mRegistered = false;
5119}
5120
Evan Severson09ab4002021-02-10 14:15:19 -08005121bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08005122 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
5123 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5124 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
5125 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5126 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08005127}
5128
Michael Grooverd1d435a2018-12-18 17:39:42 -08005129// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005130// CameraState
5131// ----------------------------------------------------------------------------
5132
Austin Borgered99f642023-06-01 16:51:35 -07005133CameraService::CameraState::CameraState(const std::string& id, int cost,
5134 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005135 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005136 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005137 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005138
5139CameraService::CameraState::~CameraState() {}
5140
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005141CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005142 Mutex::Autolock lock(mStatusLock);
5143 return mStatus;
5144}
5145
Austin Borgered99f642023-06-01 16:51:35 -07005146std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005147 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005148 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005149 return res;
5150}
5151
Ruben Brunkcc776712015-02-17 20:18:47 -08005152CameraParameters CameraService::CameraState::getShimParams() const {
5153 return mShimParams;
5154}
5155
5156void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5157 mShimParams = params;
5158}
5159
5160int CameraService::CameraState::getCost() const {
5161 return mCost;
5162}
5163
Austin Borgered99f642023-06-01 16:51:35 -07005164std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005165 return mConflicting;
5166}
5167
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005168SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5169 return mSystemCameraKind;
5170}
5171
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005172bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5173 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5174 != mPhysicalCameras.end();
5175}
5176
Austin Borgered99f642023-06-01 16:51:35 -07005177bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005178 Mutex::Autolock lock(mStatusLock);
5179 auto result = mUnavailablePhysicalIds.insert(physicalId);
5180 return result.second;
5181}
5182
Austin Borgered99f642023-06-01 16:51:35 -07005183bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005184 Mutex::Autolock lock(mStatusLock);
5185 auto count = mUnavailablePhysicalIds.erase(physicalId);
5186 return count > 0;
5187}
5188
Austin Borgered99f642023-06-01 16:51:35 -07005189void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005190 Mutex::Autolock lock(mStatusLock);
5191 mClientPackage = clientPackage;
5192}
5193
Austin Borgered99f642023-06-01 16:51:35 -07005194std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005195 Mutex::Autolock lock(mStatusLock);
5196 return mClientPackage;
5197}
5198
Ruben Brunkcc776712015-02-17 20:18:47 -08005199// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005200// ClientEventListener
5201// ----------------------------------------------------------------------------
5202
5203void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005204 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005205 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005206 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005207 if (basicClient.get() != nullptr) {
5208 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005209 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005210 static_cast<int>(basicClient->getClientUid()));
5211 }
5212}
5213
5214void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005215 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005216 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005217 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005218 if (basicClient.get() != nullptr) {
5219 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005220 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005221 static_cast<int>(basicClient->getClientUid()));
5222 }
5223}
5224
Ruben Brunk99e69712015-05-26 17:25:07 -07005225// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005226// CameraClientManager
5227// ----------------------------------------------------------------------------
5228
Ruben Brunk99e69712015-05-26 17:25:07 -07005229CameraService::CameraClientManager::CameraClientManager() {
5230 setListener(std::make_shared<ClientEventListener>());
5231}
5232
Ruben Brunkcc776712015-02-17 20:18:47 -08005233CameraService::CameraClientManager::~CameraClientManager() {}
5234
5235sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005236 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005237 auto descriptor = get(id);
5238 if (descriptor == nullptr) {
5239 return sp<BasicClient>{nullptr};
5240 }
5241 return descriptor->getValue();
5242}
5243
Austin Borgered99f642023-06-01 16:51:35 -07005244std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005245 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005246 std::ostringstream ret;
5247 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005248 bool hasAny = false;
5249 for (auto& i : all) {
5250 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005251 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005252 int32_t cost = i->getCost();
5253 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005254 int32_t score = i->getPriority().getScore();
5255 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005256 auto conflicting = i->getConflicting();
5257 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005258 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005259 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005260 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005261 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005262 uid_t clientUid = clientSp->getClientUid();
5263 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005264 }
Austin Borgered99f642023-06-01 16:51:35 -07005265 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5266 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005267
Ruben Brunk6267b532015-04-30 17:44:07 -07005268 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005269 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005270 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005271 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005272 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005273 }
5274
Austin Borgered99f642023-06-01 16:51:35 -07005275 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005276 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005277 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005278 }
Austin Borgered99f642023-06-01 16:51:35 -07005279 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005280 }
Austin Borgered99f642023-06-01 16:51:35 -07005281 if (hasAny) ret << "\n";
5282 ret << "]\n";
5283 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005284}
5285
5286CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005287 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5288 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005289 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005290
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005291 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005292 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005293
Austin Borgered99f642023-06-01 16:51:35 -07005294 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005295 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5296 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005297}
5298
5299CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005300 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005301 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005302 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005303 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005304 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5305 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005306}
5307
5308// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005309// InjectionStatusListener
5310// ----------------------------------------------------------------------------
5311
5312void CameraService::InjectionStatusListener::addListener(
5313 const sp<ICameraInjectionCallback>& callback) {
5314 Mutex::Autolock lock(mListenerLock);
5315 if (mCameraInjectionCallback) return;
5316 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5317 if (res == OK) {
5318 mCameraInjectionCallback = callback;
5319 }
5320}
5321
5322void CameraService::InjectionStatusListener::removeListener() {
5323 Mutex::Autolock lock(mListenerLock);
5324 if (mCameraInjectionCallback == nullptr) {
5325 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5326 return;
5327 }
5328 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5329 mCameraInjectionCallback = nullptr;
5330}
5331
5332void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005333 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005334 if (mCameraInjectionCallback == nullptr) {
5335 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5336 return;
5337 }
Cliff Wud3a05312021-04-26 23:07:31 +08005338
5339 switch (err) {
5340 case -ENODEV:
5341 mCameraInjectionCallback->onInjectionError(
5342 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5343 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005344 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005345 break;
5346 case -EBUSY:
5347 mCameraInjectionCallback->onInjectionError(
5348 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5349 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005350 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005351 break;
5352 case DEAD_OBJECT:
5353 mCameraInjectionCallback->onInjectionError(
5354 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5355 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005356 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005357 break;
5358 case INVALID_OPERATION:
5359 mCameraInjectionCallback->onInjectionError(
5360 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5361 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005362 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005363 break;
5364 case UNKNOWN_TRANSACTION:
5365 mCameraInjectionCallback->onInjectionError(
5366 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5367 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005368 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005369 break;
5370 default:
5371 mCameraInjectionCallback->onInjectionError(
5372 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5373 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005374 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005375 }
Cliff Wud8cae102021-03-11 01:37:42 +08005376}
5377
5378void CameraService::InjectionStatusListener::binderDied(
5379 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005380 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5381 auto parent = mParent.promote();
5382 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005383 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5384 if (clientDescriptor != nullptr) {
5385 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5386 baseClientPtr->stopInjection();
5387 }
Cliff Wu3b268182021-07-06 15:44:43 +08005388 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005389 }
5390}
5391
5392// ----------------------------------------------------------------------------
5393// CameraInjectionSession
5394// ----------------------------------------------------------------------------
5395
5396binder::Status CameraService::CameraInjectionSession::stopInjection() {
5397 Mutex::Autolock lock(mInjectionSessionLock);
5398 auto parent = mParent.promote();
5399 if (parent == nullptr) {
5400 ALOGE("CameraInjectionSession: Parent is gone");
5401 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5402 "Camera service encountered error");
5403 }
Cliff Wud3a05312021-04-26 23:07:31 +08005404
5405 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005406 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5407 if (clientDescriptor != nullptr) {
5408 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5409 res = baseClientPtr->stopInjection();
5410 if (res != OK) {
5411 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5412 " ret != NO_ERROR: %d", res);
5413 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5414 "Camera session encountered error");
5415 }
5416 }
Cliff Wu3b268182021-07-06 15:44:43 +08005417 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005418 return binder::Status::ok();
5419}
5420
5421// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005422
5423static const int kDumpLockRetries = 50;
5424static const int kDumpLockSleep = 60000;
5425
5426static bool tryLock(Mutex& mutex)
5427{
5428 bool locked = false;
5429 for (int i = 0; i < kDumpLockRetries; ++i) {
5430 if (mutex.tryLock() == NO_ERROR) {
5431 locked = true;
5432 break;
5433 }
5434 usleep(kDumpLockSleep);
5435 }
5436 return locked;
5437}
5438
Rucha Katakwardf223072021-06-15 10:21:00 -07005439void CameraService::cacheDump() {
5440 if (mMemFd != -1) {
5441 const Vector<String16> args;
5442 ATRACE_CALL();
5443 // Acquiring service lock here will avoid the deadlock since
5444 // cacheDump will not be called during the second disconnect.
5445 Mutex::Autolock lock(mServiceLock);
5446
5447 Mutex::Autolock l(mCameraStatesLock);
5448 // Start collecting the info for open sessions and store it in temp file.
5449 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005450 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005451 auto clientDescriptor = mActiveClientManager.get(cameraId);
5452 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005453 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005454 // Log the current open session info before device is disconnected.
5455 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5456 }
5457 }
5458 }
5459}
5460
Mathias Agopian65ab4712010-07-14 17:59:35 -07005461status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005462 ATRACE_CALL();
5463
Austin Borgered99f642023-06-01 16:51:35 -07005464 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005465 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005466 getCallingPid(),
5467 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005468 return NO_ERROR;
5469 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005470 bool locked = tryLock(mServiceLock);
5471 // failed to lock - CameraService is probably deadlocked
5472 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005473 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005474 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005475
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005476 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005477 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005478
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005479 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005480 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005481
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005482 if (locked) mServiceLock.unlock();
5483 return NO_ERROR;
5484 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005485 dprintf(fd, "\n== Service global info: ==\n\n");
5486 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005487 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005488 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5489 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005490 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5491 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5492 }
Austin Borgered99f642023-06-01 16:51:35 -07005493 std::string activeClientString = mActiveClientManager.toString();
5494 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5495 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005496 if (mStreamUseCaseOverrides.size() > 0) {
5497 dprintf(fd, "Active stream use case overrides:");
5498 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5499 dprintf(fd, " %" PRId64, useCaseOverride);
5500 }
5501 dprintf(fd, "\n");
5502 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005503
5504 dumpEventLog(fd);
5505
5506 bool stateLocked = tryLock(mCameraStatesLock);
5507 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005508 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005509 }
5510
Emilian Peevbd8c5032018-02-14 23:05:40 +00005511 int argSize = args.size();
5512 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005513 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005514 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005515 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005516 }
5517 break;
5518 }
5519 }
5520
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005521 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005522 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005523
Austin Borgered99f642023-06-01 16:51:35 -07005524 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005525
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005526 CameraParameters p = state.second->getShimParams();
5527 if (!p.isEmpty()) {
5528 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5529 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005530 }
5531
5532 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005533 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005534 // log the current open session info
5535 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005536 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005537 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005538 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005539
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005540 }
5541
5542 if (stateLocked) mCameraStatesLock.unlock();
5543
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005544 if (locked) mServiceLock.unlock();
5545
Emilian Peevf53f66e2017-04-11 14:29:43 +01005546 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005547
5548 dprintf(fd, "\n== Vendor tags: ==\n\n");
5549
5550 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5551 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005552 sp<VendorTagDescriptorCache> cache =
5553 VendorTagDescriptorCache::getGlobalVendorTagCache();
5554 if (cache == NULL) {
5555 dprintf(fd, "No vendor tags.\n");
5556 } else {
5557 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5558 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005559 } else {
5560 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5561 }
5562
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005563 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005564 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005565 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005566
5567 // Process dump arguments, if any
5568 int n = args.size();
5569 String16 verboseOption("-v");
5570 String16 unreachableOption("--unreachable");
5571 for (int i = 0; i < n; i++) {
5572 if (args[i] == verboseOption) {
5573 // change logging level
5574 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005575 std::string levelStr = toStdString(args[i+1]);
5576 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005577 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005578 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005579 } else if (args[i] == unreachableOption) {
5580 // Dump memory analysis
5581 // TODO - should limit be an argument parameter?
5582 UnreachableMemoryInfo info;
5583 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5584 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005585 dprintf(fd, "\n== Unable to dump unreachable memory. "
5586 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005587 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005588 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005589 std::string s = info.ToString(/*log_contents*/ true);
5590 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005591 }
5592 }
5593 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005594
5595 bool serviceLocked = tryLock(mServiceLock);
5596
5597 // Dump info from previous open sessions.
5598 // Reposition the offset to beginning of the file before reading
5599
5600 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5601 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5602 ssize_t size_read;
5603 char buf[4096];
5604 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5605 // Read data from file to a small buffer and write it to fd.
5606 write(fd, buf, size_read);
5607 if (size_read == -1) {
5608 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5609 break;
5610 }
5611 }
5612 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5613 } else {
5614 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5615 }
5616
5617 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005618 return NO_ERROR;
5619}
5620
Rucha Katakwardf223072021-06-15 10:21:00 -07005621void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005622 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005623 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005624 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005625 getFormattedCurrentTime().c_str(),
5626 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005627 dprintf(fd, " Client priority score: %d state: %d\n",
5628 clientDescriptor->getPriority().getScore(),
5629 clientDescriptor->getPriority().getState());
5630 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5631
5632 auto client = clientDescriptor->getValue();
5633 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005634 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005635
5636 client->dumpClient(fd, args);
5637}
5638
Austin Borgered99f642023-06-01 16:51:35 -07005639void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005640 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005641 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005642}
5643
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005644void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005645 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005646
5647 Mutex::Autolock l(mLogLock);
5648 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005649 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005650 }
5651
5652 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005653 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005654 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005655 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005656 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005657 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005658}
5659
Austin Borgered99f642023-06-01 16:51:35 -07005660void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005661 Mutex::Autolock lock(mLogLock);
5662 if (!isClientWatchedLocked(client)) { return; }
5663
5664 std::vector<std::string> dumpVector;
5665 client->dumpWatchedEventsToVector(dumpVector);
5666
5667 if (dumpVector.empty()) { return; }
5668
Austin Borgered99f642023-06-01 16:51:35 -07005669 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005670
Austin Borgered99f642023-06-01 16:51:35 -07005671 std::string currentTime = getFormattedCurrentTime();
5672 dumpString << "Cached @ ";
5673 dumpString << currentTime;
5674 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005675
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005676 size_t i = dumpVector.size();
5677
5678 // Store the string in reverse order (latest last)
5679 while (i > 0) {
5680 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005681 dumpString << cameraId;
5682 dumpString << ":";
5683 dumpString << client->getPackageName();
5684 dumpString << " ";
5685 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005686 }
5687
Austin Borgered99f642023-06-01 16:51:35 -07005688 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005689}
5690
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005691void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005692 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005693 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5694 if (mTorchClientMap[i] == who) {
5695 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005696 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005697 status_t res = mFlashlight->setTorchMode(cameraId, false);
5698 if (res) {
5699 ALOGE("%s: torch client died but couldn't turn off torch: "
5700 "%s (%d)", __FUNCTION__, strerror(-res), res);
5701 return;
5702 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005703 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005704 break;
5705 }
5706 }
5707}
5708
Ruben Brunkcc776712015-02-17 20:18:47 -08005709/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005710
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005711 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005712 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5713 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005714 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005715 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005716 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005717
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005718 // check torch client
5719 handleTorchClientBinderDied(who);
5720
5721 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005722 if(!evictClientIdByRemote(who)) {
5723 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005724 return;
5725 }
5726
Ruben Brunkcc776712015-02-17 20:18:47 -08005727 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5728 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005729}
5730
Austin Borgered99f642023-06-01 16:51:35 -07005731void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005732 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005733}
5734
Austin Borgered99f642023-06-01 16:51:35 -07005735void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005736 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005737 // Do not lock mServiceLock here or can get into a deadlock from
5738 // connect() -> disconnect -> updateStatus
5739
5740 auto state = getCameraState(cameraId);
5741
5742 if (state == nullptr) {
5743 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005744 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005745 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005746 }
5747
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005748 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5749 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5750 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005751 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005752 return;
5753 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005754
Biswarup Pal37a75182024-01-16 15:53:35 +00005755 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5756 CameraMetadata cameraInfo;
5757 status_t res = mCameraProviderManager->getCameraCharacteristics(
5758 cameraId, false, &cameraInfo, false);
5759 if (res != OK) {
5760 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5761 __FUNCTION__, cameraId.c_str());
5762 } else {
5763 int32_t deviceId = getDeviceId(cameraInfo);
5764 if (deviceId != kDefaultDeviceId) {
5765 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5766 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5767 static_cast<camera_metadata_enum_android_lens_facing_t>(
5768 lensFacingEntry.data.u8[0]);
5769 std::string mappedCameraId;
5770 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5771 mappedCameraId = kVirtualDeviceBackCameraId;
5772 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5773 mappedCameraId = kVirtualDeviceFrontCameraId;
5774 } else {
5775 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5776 __func__);
5777 }
5778 if (!mappedCameraId.empty()) {
5779 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5780 }
5781 }
5782 }
5783 }
5784
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005785 // Collect the logical cameras without holding mStatusLock in updateStatus
5786 // as that can lead to a deadlock(b/162192331).
5787 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005788 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005789 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005790 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005791 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005792 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005793 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5794 auto [deviceId, mappedCameraId] =
5795 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005796
Biswarup Pal37a75182024-01-16 15:53:35 +00005797 if (status != StatusInternal::ENUMERATING) {
5798 // Update torch status if it has a flash unit.
5799 Mutex::Autolock al(mTorchStatusMutex);
5800 TorchModeStatus torchStatus;
5801 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5802 NAME_NOT_FOUND) {
5803 TorchModeStatus newTorchStatus =
5804 status == StatusInternal::PRESENT ?
5805 TorchModeStatus::AVAILABLE_OFF :
5806 TorchModeStatus::NOT_AVAILABLE;
5807 if (torchStatus != newTorchStatus) {
5808 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5809 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005810 }
5811 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005812
Biswarup Pal37a75182024-01-16 15:53:35 +00005813 Mutex::Autolock lock(mStatusListenerLock);
5814 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5815 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005816
Biswarup Pal37a75182024-01-16 15:53:35 +00005817 for (auto& listener : mListenerList) {
5818 bool isVendorListener = listener->isVendorListener();
5819 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5820 listener->getListenerPid(), listener->getListenerUid())) {
5821 ALOGV("Skipping discovery callback for system-only camera device %s",
5822 cameraId.c_str());
5823 continue;
5824 }
5825
5826 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5827 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005828 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005829 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005830 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5831 ret.exceptionCode());
Biswarup Pal37a75182024-01-16 15:53:35 +00005832
5833 // Only cameras of the default device can be remapped to a different camera
5834 // (using remapCameraIds method), so do the following only if the camera is
5835 // associated with the default device.
5836 if (deviceId == kDefaultDeviceId) {
5837 // For the default device, also trigger the callbacks for cameras that were
5838 // remapped to the current cameraId for the specific package that this
5839 // listener belongs to.
5840 std::vector<std::string> remappedCameraIds =
5841 findOriginalIdsForRemappedCameraId(cameraId,
5842 listener->getListenerUid());
5843 for (auto &remappedCameraId: remappedCameraIds) {
5844 ret = listener->getListener()->onStatusChanged(
5845 mapToInterface(status), remappedCameraId, kDefaultDeviceId);
5846 listener->handleBinderStatus(ret,
5847 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
5848 __FUNCTION__, listener->getListenerUid(),
5849 listener->getListenerPid(), ret.exceptionCode());
5850 }
5851 }
malikakash82ed4352023-07-21 22:44:34 +00005852 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005853 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005854}
5855
Austin Borgered99f642023-06-01 16:51:35 -07005856void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5857 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005858 auto state = getCameraState(cameraId);
5859 if (state == nullptr) {
5860 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005861 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005862 return;
5863 }
5864 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005865 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005866 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005867 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005868 }
5869
Biswarup Pal37a75182024-01-16 15:53:35 +00005870 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5871 auto [deviceId, mappedCameraId] =
5872 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5873
Shuzhen Wang695044d2020-03-06 09:02:23 -08005874 Mutex::Autolock lock(mStatusListenerLock);
5875
5876 for (const auto& it : mListenerList) {
5877 if (!it->isOpenCloseCallbackAllowed()) {
5878 continue;
5879 }
5880
5881 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005882 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005883 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5884 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005885 } else {
Biswarup Pal37a75182024-01-16 15:53:35 +00005886 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005887 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005888
5889 it->handleBinderStatus(ret,
5890 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5891 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005892 }
5893}
5894
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005895template<class Func>
5896void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005897 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005898 std::initializer_list<StatusInternal> rejectSourceStates,
5899 Func onStatusUpdatedLocked) {
5900 Mutex::Autolock lock(mStatusLock);
5901 StatusInternal oldStatus = mStatus;
5902 mStatus = status;
5903
5904 if (oldStatus == status) {
5905 return;
5906 }
5907
5908 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005909 cameraId.c_str(), oldStatus, status);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005910
5911 if (oldStatus == StatusInternal::NOT_PRESENT &&
5912 (status != StatusInternal::PRESENT &&
5913 status != StatusInternal::ENUMERATING)) {
5914
5915 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5916 __FUNCTION__);
5917 mStatus = oldStatus;
5918 return;
5919 }
5920
5921 /**
5922 * Sometimes we want to conditionally do a transition.
5923 * For example if a client disconnects, we want to go to PRESENT
5924 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5925 */
5926 for (auto& rejectStatus : rejectSourceStates) {
5927 if (oldStatus == rejectStatus) {
5928 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005929 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005930 mStatus = oldStatus;
5931 return;
5932 }
5933 }
5934
5935 onStatusUpdatedLocked(cameraId, status);
5936}
5937
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005938status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005939 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005940 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005941 if (!status) {
5942 return BAD_VALUE;
5943 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005944 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5945 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005946 // invalid camera ID or the camera doesn't have a flash unit
5947 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005948 }
5949
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005950 *status = mTorchStatusMap.valueAt(index);
5951 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005952}
5953
Austin Borgered99f642023-06-01 16:51:35 -07005954status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005955 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005956 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5957 if (index == NAME_NOT_FOUND) {
5958 return BAD_VALUE;
5959 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005960 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005961
5962 return OK;
5963}
5964
Austin Borgered99f642023-06-01 16:51:35 -07005965std::list<std::string> CameraService::getLogicalCameras(
5966 const std::string& physicalCameraId) {
5967 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005968 Mutex::Autolock lock(mCameraStatesLock);
5969 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005970 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5971 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005972 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005973 }
5974 return retList;
5975}
5976
5977void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005978 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00005979 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005980 // mStatusListenerLock is expected to be locked
5981 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005982 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005983 // Note: we check only the deviceKind of the physical camera id
5984 // since, logical camera ids and their physical camera ids are
5985 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005986 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5987 listener->getListenerPid(), listener->getListenerUid())) {
5988 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005989 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005990 continue;
5991 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005992 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00005993 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005994 listener->handleBinderStatus(ret,
5995 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5996 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5997 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005998 }
5999 }
6000}
6001
Svet Ganova453d0d2018-01-11 15:37:58 -08006002void CameraService::blockClientsForUid(uid_t uid) {
6003 const auto clients = mActiveClientManager.getAll();
6004 for (auto& current : clients) {
6005 if (current != nullptr) {
6006 const auto basicClient = current->getValue();
6007 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
6008 basicClient->block();
6009 }
6010 }
6011 }
6012}
6013
Michael Grooverd1d435a2018-12-18 17:39:42 -08006014void CameraService::blockAllClients() {
6015 const auto clients = mActiveClientManager.getAll();
6016 for (auto& current : clients) {
6017 if (current != nullptr) {
6018 const auto basicClient = current->getValue();
6019 if (basicClient.get() != nullptr) {
6020 basicClient->block();
6021 }
6022 }
6023 }
6024}
6025
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00006026void CameraService::blockPrivacyEnabledClients() {
6027 const auto clients = mActiveClientManager.getAll();
6028 for (auto& current : clients) {
6029 if (current != nullptr) {
6030 const auto basicClient = current->getValue();
6031 if (basicClient.get() != nullptr) {
6032 std::string pkgName = basicClient->getPackageName();
6033 bool cameraPrivacyEnabled =
6034 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
6035 if (cameraPrivacyEnabled) {
6036 basicClient->block();
6037 }
6038 }
6039 }
6040 }
6041}
6042
Svet Ganova453d0d2018-01-11 15:37:58 -08006043// NOTE: This is a remote API - make sure all args are validated
6044status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006045 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006046 return PERMISSION_DENIED;
6047 }
6048 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
6049 return BAD_VALUE;
6050 }
Austin Borgered99f642023-06-01 16:51:35 -07006051 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006052 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006053 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006054 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006055 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006056 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07006057 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006058 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07006059 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006060 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07006061 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006062 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07006063 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006064 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07006065 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006066 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07006067 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006068 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07006069 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006070 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07006071 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006072 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07006073 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006074 handleClearStreamUseCaseOverrides();
6075 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07006076 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006077 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07006078 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006079 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07006080 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00006081 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07006082 } else if (args.size() >= 4 && args[0] == toString16("remap-camera-id")) {
malikakash82ed4352023-07-21 22:44:34 +00006083 return handleCameraIdRemapping(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006084 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006085 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006086 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08006087 }
6088 printHelp(err);
6089 return BAD_VALUE;
6090}
6091
malikakash82ed4352023-07-21 22:44:34 +00006092status_t CameraService::handleCameraIdRemapping(const Vector<String16>& args, int err) {
6093 uid_t uid = IPCThreadState::self()->getCallingUid();
6094 if (uid != AID_ROOT) {
6095 dprintf(err, "Must be adb root\n");
6096 return PERMISSION_DENIED;
6097 }
6098 if (args.size() != 4) {
6099 dprintf(err, "Expected format: remap-camera-id <PACKAGE> <Id0> <Id1>\n");
6100 return BAD_VALUE;
6101 }
Austin Borgered99f642023-06-01 16:51:35 -07006102 std::string packageName = toStdString(args[1]);
6103 std::string cameraIdToReplace = toStdString(args[2]);
6104 std::string cameraIdNew = toStdString(args[3]);
malikakash82ed4352023-07-21 22:44:34 +00006105 remapCameraIds({{packageName, {{cameraIdToReplace, cameraIdNew}}}});
6106 return OK;
6107}
6108
Svet Ganova453d0d2018-01-11 15:37:58 -08006109status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006110 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006111
Svet Ganova453d0d2018-01-11 15:37:58 -08006112 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07006113 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006114 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07006115 } else if ((args[2] != toString16("idle"))) {
6116 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08006117 return BAD_VALUE;
6118 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006119
6120 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006121 if (args.size() >= 5 && args[3] == toString16("--user")) {
6122 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006123 }
6124
6125 uid_t uid;
6126 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
6127 return BAD_VALUE;
6128 }
6129
6130 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08006131 return NO_ERROR;
6132}
6133
6134status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006135 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006136
6137 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006138 if (args.size() >= 4 && args[2] == toString16("--user")) {
6139 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006140 }
6141
6142 uid_t uid;
6143 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006144 return BAD_VALUE;
6145 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006146
6147 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08006148 return NO_ERROR;
6149}
6150
6151status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006152 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006153
6154 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006155 if (args.size() >= 4 && args[2] == toString16("--user")) {
6156 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006157 }
6158
6159 uid_t uid;
6160 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006161 return BAD_VALUE;
6162 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006163
6164 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006165 return dprintf(out, "active\n");
6166 } else {
6167 return dprintf(out, "idle\n");
6168 }
6169}
6170
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006171status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006172 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006173 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
6174 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
6175 Mutex::Autolock lock(mServiceLock);
6176
6177 mOverrideRotateAndCropMode = rotateValue;
6178
6179 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6180
6181 const auto clients = mActiveClientManager.getAll();
6182 for (auto& current : clients) {
6183 if (current != nullptr) {
6184 const auto basicClient = current->getValue();
6185 if (basicClient.get() != nullptr) {
6186 basicClient->setRotateAndCropOverride(rotateValue);
6187 }
6188 }
6189 }
6190
6191 return OK;
6192}
6193
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006194status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6195 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006196 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006197 if ((*end != '\0') ||
6198 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6199 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6200 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6201 return BAD_VALUE;
6202 }
6203
6204 Mutex::Autolock lock(mServiceLock);
6205 mOverrideAutoframingMode = autoframingValue;
6206
6207 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6208
6209 const auto clients = mActiveClientManager.getAll();
6210 for (auto& current : clients) {
6211 if (current != nullptr) {
6212 const auto basicClient = current->getValue();
6213 if (basicClient.get() != nullptr) {
6214 basicClient->setAutoframingOverride(autoframingValue);
6215 }
6216 }
6217 }
6218
6219 return OK;
6220}
6221
Ravneetaeb20dc2022-03-30 05:33:03 +00006222status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006223 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006224
6225 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6226
6227 Mutex::Autolock lock(mServiceLock);
6228
6229 mCameraServiceWatchdogEnabled = enableWatchdog;
6230
6231 const auto clients = mActiveClientManager.getAll();
6232 for (auto& current : clients) {
6233 if (current != nullptr) {
6234 const auto basicClient = current->getValue();
6235 if (basicClient.get() != nullptr) {
6236 basicClient->setCameraServiceWatchdog(enableWatchdog);
6237 }
6238 }
6239 }
6240
6241 return OK;
6242}
6243
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006244status_t CameraService::handleGetRotateAndCrop(int out) {
6245 Mutex::Autolock lock(mServiceLock);
6246
6247 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6248}
6249
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006250status_t CameraService::handleGetAutoframing(int out) {
6251 Mutex::Autolock lock(mServiceLock);
6252
6253 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6254}
6255
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006256status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6257 char *endPtr;
6258 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006259 std::string maskString = toStdString(args[1]);
6260 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006261
6262 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006263 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006264 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6265
6266 Mutex::Autolock lock(mServiceLock);
6267
6268 mImageDumpMask = maskValue;
6269
6270 return OK;
6271}
6272
6273status_t CameraService::handleGetImageDumpMask(int out) {
6274 Mutex::Autolock lock(mServiceLock);
6275
6276 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6277}
6278
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006279status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006280 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006281 if (errno != 0) return BAD_VALUE;
6282
6283 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6284 Mutex::Autolock lock(mServiceLock);
6285
6286 mOverrideCameraMuteMode = (muteValue == 1);
6287
6288 const auto clients = mActiveClientManager.getAll();
6289 for (auto& current : clients) {
6290 if (current != nullptr) {
6291 const auto basicClient = current->getValue();
6292 if (basicClient.get() != nullptr) {
6293 if (basicClient->supportsCameraMute()) {
6294 basicClient->setCameraMute(mOverrideCameraMuteMode);
6295 }
6296 }
6297 }
6298 }
6299
6300 return OK;
6301}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006302
Shuzhen Wang16610a62022-12-15 22:38:07 -08006303status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6304 std::vector<int64_t> useCasesOverride;
6305 for (size_t i = 1; i < args.size(); i++) {
6306 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006307 std::string arg = toStdString(args[i]);
6308 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006309 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006310 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006311 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006312 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006313 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006314 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006315 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006316 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006317 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006318 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006319 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006320 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006321 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6322 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006323 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006324 return BAD_VALUE;
6325 }
6326 useCasesOverride.push_back(useCase);
6327 }
6328
6329 Mutex::Autolock lock(mServiceLock);
6330 mStreamUseCaseOverrides = std::move(useCasesOverride);
6331
6332 return OK;
6333}
6334
6335void CameraService::handleClearStreamUseCaseOverrides() {
6336 Mutex::Autolock lock(mServiceLock);
6337 mStreamUseCaseOverrides.clear();
6338}
6339
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006340status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6341 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006342 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006343 if ((*end != '\0') ||
6344 (zoomOverrideValue != -1 &&
6345 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6346 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6347 return BAD_VALUE;
6348 }
6349
6350 Mutex::Autolock lock(mServiceLock);
6351 mZoomOverrideValue = zoomOverrideValue;
6352
6353 const auto clients = mActiveClientManager.getAll();
6354 for (auto& current : clients) {
6355 if (current != nullptr) {
6356 const auto basicClient = current->getValue();
6357 if (basicClient.get() != nullptr) {
6358 if (basicClient->supportsZoomOverride()) {
6359 basicClient->setZoomOverride(mZoomOverrideValue);
6360 }
6361 }
6362 }
6363 }
6364
6365 return OK;
6366}
6367
Avichal Rakesh84147132021-11-11 17:47:11 -08006368status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006369 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006370 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006371 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006372 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006373 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006374 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006375 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006376 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006377 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006378 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006379 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006380 dprintf(outFd, "Camera service watch commands:\n"
6381 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6382 " starts watching the provided tags for clients with provided package\n"
6383 " recognizes tag shorthands like '3a'\n"
6384 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006385 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006386 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006387 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006388 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006389 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006390 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006391 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006392}
6393
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006394status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6395 Mutex::Autolock lock(mLogLock);
6396 size_t tagsIdx; // index of '-m'
6397 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006398 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006399 if (tagsIdx < args.size() - 1) {
6400 tags = args[tagsIdx + 1];
6401 } else {
6402 dprintf(outFd, "No tags provided.\n");
6403 return BAD_VALUE;
6404 }
6405
6406 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006407 // watch all clients if no clients are provided
6408 String16 clients = toString16(kWatchAllClientsFlag);
6409 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006410 clientsIdx++);
6411 if (clientsIdx < args.size() - 1) {
6412 clients = args[clientsIdx + 1];
6413 }
Austin Borgered99f642023-06-01 16:51:35 -07006414 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006415
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006416 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006417 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006418
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006419 bool serviceLock = tryLock(mServiceLock);
6420 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006421 auto cameraClients = mActiveClientManager.getAll();
6422 for (const auto &clientDescriptor: cameraClients) {
6423 if (clientDescriptor == nullptr) { continue; }
6424 sp<BasicClient> client = clientDescriptor->getValue();
6425 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006426
6427 if (isClientWatchedLocked(client.get())) {
6428 client->startWatchingTags(mMonitorTags, outFd);
6429 numWatchedClients++;
6430 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006431 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006432 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6433
6434 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006435 return OK;
6436}
6437
6438status_t CameraService::stopWatchingTags(int outFd) {
6439 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006440 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006441 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006442
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006443 mWatchedClientPackages.clear();
6444 mWatchedClientsDumpCache.clear();
6445
6446 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006447 auto cameraClients = mActiveClientManager.getAll();
6448 for (const auto &clientDescriptor : cameraClients) {
6449 if (clientDescriptor == nullptr) { continue; }
6450 sp<BasicClient> client = clientDescriptor->getValue();
6451 if (client.get() == nullptr) { continue; }
6452 client->stopWatchingTags(outFd);
6453 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006454 dprintf(outFd, "Stopped watching all clients.\n");
6455 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006456 return OK;
6457}
6458
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006459status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6460 Mutex::Autolock lock(mLogLock);
6461 size_t clearedSize = mWatchedClientsDumpCache.size();
6462 mWatchedClientsDumpCache.clear();
6463 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6464 return OK;
6465}
6466
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006467status_t CameraService::printWatchedTags(int outFd) {
6468 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006469 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006470
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006471 bool printedSomething = false; // tracks if any monitoring information was printed
6472 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006473
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006474 bool serviceLock = tryLock(mServiceLock);
6475 // get all watched clients that are currently connected
6476 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6477 if (clientDescriptor == nullptr) { continue; }
6478
6479 sp<BasicClient> client = clientDescriptor->getValue();
6480 if (client.get() == nullptr) { continue; }
6481 if (!isClientWatchedLocked(client.get())) { continue; }
6482
6483 std::vector<std::string> dumpVector;
6484 client->dumpWatchedEventsToVector(dumpVector);
6485
6486 size_t printIdx = dumpVector.size();
6487 if (printIdx == 0) {
6488 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006489 }
6490
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006491 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006492 const std::string &cameraId = clientDescriptor->getKey();
6493 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006494 while(printIdx > 0) {
6495 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006496 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006497 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006498 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006499 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006500 printedSomething = true;
6501
6502 connectedMonitoredClients.emplace(client->getPackageName());
6503 }
6504 if (serviceLock) { mServiceLock.unlock(); }
6505
6506 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6507 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006508 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006509 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6510 continue;
6511 }
6512
Austin Borgered99f642023-06-01 16:51:35 -07006513 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006514 dprintf(outFd, "%s\n", kv.second.c_str());
6515 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006516 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006517
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006518 if (!printedSomething) {
6519 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006520 }
6521
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006522 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006523}
6524
Avichal Rakesh84147132021-11-11 17:47:11 -08006525// Print all events in vector `events' that came after lastPrintedEvent
6526void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006527 const std::string &cameraId,
6528 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006529 const std::vector<std::string> &events,
6530 const std::string &lastPrintedEvent) {
6531 if (events.empty()) { return; }
6532
6533 // index of lastPrintedEvent in events.
6534 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6535 size_t lastPrintedIdx;
6536 for (lastPrintedIdx = 0;
6537 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6538 lastPrintedIdx++);
6539
6540 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6541
Avichal Rakesh84147132021-11-11 17:47:11 -08006542 // print events in chronological order (latest event last)
6543 size_t idxToPrint = lastPrintedIdx;
6544 do {
6545 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006546 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6547 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006548 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006549}
6550
6551// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6552// command should be interrupted if the user presses the return key, or if user loses any way to
6553// signal interrupt.
6554// If timeoutMs == 0, this function will always return false
6555bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6556 struct timeval startTime;
6557 int startTimeError = gettimeofday(&startTime, nullptr);
6558 if (startTimeError) {
6559 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6560 return true;
6561 }
6562
6563 const nfds_t numFds = 1;
6564 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6565
6566 struct timeval currTime;
6567 char buffer[2];
6568 while(true) {
6569 int currTimeError = gettimeofday(&currTime, nullptr);
6570 if (currTimeError) {
6571 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6572 return true;
6573 }
6574
6575 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6576 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6577 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6578
6579 if (remainingTimeMs <= 0) {
6580 // No user interrupt within timeoutMs, don't interrupt watch command
6581 return false;
6582 }
6583
6584 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6585 if (numFdsUpdated < 0) {
6586 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6587 return true;
6588 }
6589
6590 if (numFdsUpdated == 0) {
6591 // No user input within timeoutMs, don't interrupt watch command
6592 return false;
6593 }
6594
6595 if (!(pollFd.revents & POLLIN)) {
6596 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6597 return true;
6598 }
6599
6600 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6601 if (sizeRead < 0) {
6602 dprintf(outFd, "Error reading user input. Exiting.\n");
6603 return true;
6604 }
6605
6606 if (sizeRead == 0) {
6607 // Reached end of input fd (can happen if input is piped)
6608 // User has no way to signal an interrupt, so interrupt here
6609 return true;
6610 }
6611
6612 if (buffer[0] == '\n') {
6613 // User pressed return, interrupt watch command.
6614 return true;
6615 }
6616 }
6617}
6618
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006619status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6620 int inFd, int outFd) {
6621 // Figure out refresh interval, if present in args
6622 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006623 if (args.size() > 2) {
6624 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006625 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006626 intervalIdx++);
6627
6628 size_t intervalValIdx = intervalIdx + 1;
6629 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006630 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006631 if (errno) { return BAD_VALUE; }
6632 }
6633 }
6634
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006635 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6636 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006637
Avichal Rakesh84147132021-11-11 17:47:11 -08006638 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006639 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006640
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006641 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006642 bool serviceLock = tryLock(mServiceLock);
6643 auto cameraClients = mActiveClientManager.getAll();
6644 if (serviceLock) { mServiceLock.unlock(); }
6645
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006646 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006647 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006648 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006649
6650 sp<BasicClient> client = clientDescriptor->getValue();
6651 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006652 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006653
Austin Borgered99f642023-06-01 16:51:35 -07006654 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006655 // This also initializes the map entries with an empty string
6656 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6657
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006658 std::vector<std::string> latestEvents;
6659 client->dumpWatchedEventsToVector(latestEvents);
6660
6661 if (!latestEvents.empty()) {
6662 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006663 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006664 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006665 latestEvents,
6666 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006667 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006668 }
6669 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006670 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006671 break;
6672 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006673 }
6674 return OK;
6675}
6676
Austin Borgered99f642023-06-01 16:51:35 -07006677void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006678 mWatchedClientPackages.clear();
6679
Austin Borgered99f642023-06-01 16:51:35 -07006680 std::istringstream iss(clients);
6681 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006682
Austin Borgered99f642023-06-01 16:51:35 -07006683 while (std::getline(iss, nextClient, ',')) {
6684 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006685 // Don't need to track any other package if 'all' is present
6686 mWatchedClientPackages.clear();
6687 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6688 break;
6689 }
6690
6691 // track package names
6692 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006693 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006694}
6695
Svet Ganova453d0d2018-01-11 15:37:58 -08006696status_t CameraService::printHelp(int out) {
6697 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006698 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6699 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6700 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006701 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6702 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6703 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006704 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6705 " Valid values 0=false, 1=true, 2=auto\n"
6706 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006707 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6708 " Valid values 0=OFF, 1=ON for JPEG\n"
6709 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006710 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006711 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6712 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6713 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6714 " on. In case the number of usecases is smaller than the number of streams, the\n"
6715 " last use case is assigned to all the remaining streams. In case of multiple\n"
6716 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6717 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6718 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6719 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006720 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6721 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006722 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6723 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006724 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
malikakash73125c62023-07-21 22:44:34 +00006725 " remap-camera-id <PACKAGE> <Id0> <Id1> remaps camera ids. Must use adb root\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006726 " help print this message\n");
6727}
6728
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006729bool CameraService::isClientWatched(const BasicClient *client) {
6730 Mutex::Autolock lock(mLogLock);
6731 return isClientWatchedLocked(client);
6732}
6733
6734bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6735 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6736 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6737}
6738
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006739int32_t CameraService::updateAudioRestriction() {
6740 Mutex::Autolock lock(mServiceLock);
6741 return updateAudioRestrictionLocked();
6742}
6743
6744int32_t CameraService::updateAudioRestrictionLocked() {
6745 int32_t mode = 0;
6746 // iterate through all active client
6747 for (const auto& i : mActiveClientManager.getAll()) {
6748 const auto clientSp = i->getValue();
6749 mode |= clientSp->getAudioRestriction();
6750 }
6751
6752 bool modeChanged = (mAudioRestriction != mode);
6753 mAudioRestriction = mode;
6754 if (modeChanged) {
6755 mAppOps.setCameraAudioRestriction(mode);
6756 }
6757 return mode;
6758}
6759
Austin Borgered99f642023-06-01 16:51:35 -07006760status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006761 sp<BasicClient> clientSp) {
6762 std::unique_ptr<AutoConditionLock> lock =
6763 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6764 status_t res = NO_ERROR;
6765 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006766 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006767 mInjectionStatusListener->notifyInjectionError(
6768 externalCamId, UNKNOWN_TRANSACTION);
6769 clientSp->notifyError(
6770 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6771 CaptureResultExtras());
6772
6773 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6774 // other clients from connecting in mServiceLockWrapper if held
6775 mServiceLock.unlock();
6776
6777 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006778 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006779 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006780 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006781
6782 // Reacquire mServiceLock
6783 mServiceLock.lock();
6784 }
6785
6786 return res;
6787}
6788
Cliff Wud3a05312021-04-26 23:07:31 +08006789void CameraService::clearInjectionParameters() {
6790 {
6791 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006792 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006793 mInjectionInternalCamId = "";
6794 }
6795 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006796 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006797}
6798
Biswarup Pal37a75182024-01-16 15:53:35 +00006799} // namespace android