blob: 20ea5bb8002e41cd9c0d7ab6c7192f6d5615dc50 [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
994 if (!mInitialized) {
995 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
996 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
997 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
998 }
999
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001000 if (outMetadata == nullptr) {
1001 std::string msg =
1002 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
1003 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1004 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1005 }
1006
Biswarup Pal37a75182024-01-16 15:53:35 +00001007 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
1008 devicePolicy, getCallingUid());
1009 if (!cameraIdOptional.has_value()) {
1010 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1011 unresolvedCameraId.c_str(), deviceId);
1012 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 Rakesh3c522e22024-02-07 16:40:46 -08001017 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1018 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
1019
1020 status_t ret = mCameraProviderManager->getSessionCharacteristics(
1021 cameraId, sessionConfiguration, overrideForPerfClass, overrideToPortrait, outMetadata);
1022
1023 // TODO(b/303645857): Remove fingerprintable metadata if the caller process does not have
1024 // camera access permission.
1025
1026 Status res = Status::ok();
1027 switch (ret) {
1028 case OK:
1029 // Expected, no handling needed.
1030 break;
1031 case INVALID_OPERATION: {
1032 std::string msg = fmt::sprintf(
1033 "Camera %s: Session characteristics query not supported!",
1034 cameraId.c_str());
1035 ALOGD("%s: %s", __FUNCTION__, msg.c_str());
1036 res = STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1037 }
1038 break;
1039 default: {
1040 std::string msg = fmt::sprintf("Camera %s: Error: %s (%d)", cameraId.c_str(),
1041 strerror(-ret), ret);
1042 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1043 res = STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1044 }
1045 }
1046
1047 return res;
1048}
1049
malikakash82ed4352023-07-21 22:44:34 +00001050Status CameraService::parseCameraIdRemapping(
1051 const hardware::CameraIdRemapping& cameraIdRemapping,
malikakash214f6e62023-08-10 23:50:56 +00001052 /* out */ TCameraIdRemapping* cameraIdRemappingMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001053 std::string packageName;
1054 std::string cameraIdToReplace, updatedCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001055 for (const auto& packageIdRemapping: cameraIdRemapping.packageIdRemappings) {
malikakash82ed4352023-07-21 22:44:34 +00001056 packageName = packageIdRemapping.packageName;
malikakash0894f5b2023-08-10 22:46:47 +00001057 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001058 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1059 "CameraIdRemapping: Package name cannot be empty");
1060 }
malikakash214f6e62023-08-10 23:50:56 +00001061 if (packageIdRemapping.cameraIdsToReplace.size()
1062 != packageIdRemapping.updatedCameraIds.size()) {
malikakash82ed4352023-07-21 22:44:34 +00001063 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1064 "CameraIdRemapping: Mismatch in CameraId Remapping lists sizes for package %s",
malikakash73125c62023-07-21 22:44:34 +00001065 packageName.c_str());
malikakash82ed4352023-07-21 22:44:34 +00001066 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001067 for (size_t i = 0; i < packageIdRemapping.cameraIdsToReplace.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -07001068 cameraIdToReplace = packageIdRemapping.cameraIdsToReplace[i];
1069 updatedCameraId = packageIdRemapping.updatedCameraIds[i];
malikakash0894f5b2023-08-10 22:46:47 +00001070 if (cameraIdToReplace.empty() || updatedCameraId.empty()) {
malikakash214f6e62023-08-10 23:50:56 +00001071 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1072 "CameraIdRemapping: Camera Id cannot be empty for package %s",
Austin Borgered99f642023-06-01 16:51:35 -07001073 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001074 }
1075 if (cameraIdToReplace == updatedCameraId) {
1076 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1077 "CameraIdRemapping: CameraIdToReplace cannot be the same"
1078 " as updatedCameraId for %s",
Austin Borgered99f642023-06-01 16:51:35 -07001079 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001080 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001081
1082 // Do not allow any camera remapping that involves a virtual camera.
1083 auto [deviceIdForCameraToReplace, _] =
1084 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1085 cameraIdToReplace);
1086 if (deviceIdForCameraToReplace != kDefaultDeviceId) {
1087 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1088 "CameraIdRemapping: CameraIdToReplace cannot be a virtual camera");
1089 }
1090 [[maybe_unused]] auto [deviceIdForUpdatedCamera, unusedMappedCameraId] =
1091 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(updatedCameraId);
1092 if (deviceIdForUpdatedCamera != kDefaultDeviceId) {
1093 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1094 "CameraIdRemapping: UpdatedCameraId cannot be a virtual camera");
1095 }
1096
malikakash214f6e62023-08-10 23:50:56 +00001097 (*cameraIdRemappingMap)[packageName][cameraIdToReplace] = updatedCameraId;
malikakash82ed4352023-07-21 22:44:34 +00001098 }
1099 }
1100 return Status::ok();
1101}
1102
1103void CameraService::remapCameraIds(const TCameraIdRemapping& cameraIdRemapping) {
1104 // Acquire mServiceLock and prevent other clients from connecting
1105 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1106 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1107
malikakashedb38962023-09-06 00:03:35 +00001108 // Collect all existing clients for camera Ids that are being
1109 // remapped in the new cameraIdRemapping, but only if they were being used by a
1110 // targeted packageName.
malikakash82ed4352023-07-21 22:44:34 +00001111 std::vector<sp<BasicClient>> clientsToDisconnect;
Austin Borgered99f642023-06-01 16:51:35 -07001112 std::vector<std::string> cameraIdsToUpdate;
malikakash82ed4352023-07-21 22:44:34 +00001113 for (const auto& [packageName, injectionMap] : cameraIdRemapping) {
1114 for (auto& [id0, id1] : injectionMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001115 ALOGI("%s: UPDATE:= %s: %s: %s", __FUNCTION__, packageName.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001116 id0.c_str(), id1.c_str());
1117 auto clientDescriptor = mActiveClientManager.get(id0);
1118 if (clientDescriptor != nullptr) {
1119 sp<BasicClient> clientSp = clientDescriptor->getValue();
1120 if (clientSp->getPackageName() == packageName) {
malikakashedb38962023-09-06 00:03:35 +00001121 // This camera is being used by a targeted packageName and
1122 // being remapped to a new camera Id. We should disconnect it.
malikakash82ed4352023-07-21 22:44:34 +00001123 clientsToDisconnect.push_back(clientSp);
1124 cameraIdsToUpdate.push_back(id0);
1125 }
1126 }
1127 }
1128 }
1129
malikakashedb38962023-09-06 00:03:35 +00001130 for (auto& clientSp : clientsToDisconnect) {
malikakashf4c80f22023-09-25 21:50:28 +00001131 // Notify the clients about the disconnection.
1132 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
malikakashedb38962023-09-06 00:03:35 +00001133 CaptureResultExtras{});
1134 }
malikakash82ed4352023-07-21 22:44:34 +00001135
1136 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1137 // blocking other clients from connecting in mServiceLockWrapper if held.
1138 mServiceLock.unlock();
1139
malikakashedb38962023-09-06 00:03:35 +00001140 // Clear calling identity for disconnect() PID checks.
Austin Borger22c5c852024-03-08 13:31:36 -08001141 int64_t token = clearCallingIdentity();
malikakashedb38962023-09-06 00:03:35 +00001142
malikakash82ed4352023-07-21 22:44:34 +00001143 // Disconnect clients.
1144 for (auto& clientSp : clientsToDisconnect) {
malikakashedb38962023-09-06 00:03:35 +00001145 // This also triggers a call to updateStatus() which also reads mCameraIdRemapping
1146 // and requires mCameraIdRemappingLock.
malikakash82ed4352023-07-21 22:44:34 +00001147 clientSp->disconnect();
1148 }
1149
malikakashedb38962023-09-06 00:03:35 +00001150 // Invoke destructors (which call disconnect()) now while we don't hold the mServiceLock.
1151 clientsToDisconnect.clear();
1152
Austin Borger22c5c852024-03-08 13:31:36 -08001153 restoreCallingIdentity(token);
malikakash82ed4352023-07-21 22:44:34 +00001154 mServiceLock.lock();
malikakashedb38962023-09-06 00:03:35 +00001155
1156 {
1157 Mutex::Autolock lock(mCameraIdRemappingLock);
1158 // Update mCameraIdRemapping.
1159 mCameraIdRemapping.clear();
1160 mCameraIdRemapping.insert(cameraIdRemapping.begin(), cameraIdRemapping.end());
1161 }
malikakash82ed4352023-07-21 22:44:34 +00001162}
1163
malikakash22af94c2023-12-04 18:13:14 +00001164Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001165 const std::string& cameraId,
1166 const CameraMetadata& sessionParams) {
1167 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001168 const int pid = getCallingPid();
1169 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001170 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1171 __FUNCTION__, pid, uid);
1172 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1173 "Permission Denial: no permission to inject session params");
1174 }
1175
Biswarup Pal37a75182024-01-16 15:53:35 +00001176 // Do not allow session params injection for a virtual camera.
1177 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1178 if (deviceId != kDefaultDeviceId) {
1179 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1180 "Cannot inject session params for a virtual camera");
1181 }
1182
malikakash22af94c2023-12-04 18:13:14 +00001183 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1184 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1185
1186 auto clientDescriptor = mActiveClientManager.get(cameraId);
1187 if (clientDescriptor == nullptr) {
1188 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1189 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1190 "No active client for camera id %s", cameraId.c_str());
1191 }
1192
1193 sp<BasicClient> clientSp = clientDescriptor->getValue();
1194 status_t res = clientSp->injectSessionParams(sessionParams);
1195
1196 if (res != OK) {
1197 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1198 "Error injecting session params into camera \"%s\": %s (%d)",
1199 cameraId.c_str(), strerror(-res), res);
1200 }
1201 return Status::ok();
1202}
1203
Austin Borgered99f642023-06-01 16:51:35 -07001204std::vector<std::string> CameraService::findOriginalIdsForRemappedCameraId(
1205 const std::string& inputCameraId, int clientUid) {
1206 std::string packageName = getPackageNameFromUid(clientUid);
1207 std::vector<std::string> cameraIds;
malikakash82ed4352023-07-21 22:44:34 +00001208 Mutex::Autolock lock(mCameraIdRemappingLock);
1209 if (auto packageMapIter = mCameraIdRemapping.find(packageName);
1210 packageMapIter != mCameraIdRemapping.end()) {
1211 for (auto& [id0, id1]: packageMapIter->second) {
1212 if (id1 == inputCameraId) {
1213 cameraIds.push_back(id0);
1214 }
1215 }
1216 }
1217 return cameraIds;
1218}
1219
Austin Borgered99f642023-06-01 16:51:35 -07001220std::string CameraService::resolveCameraId(
1221 const std::string& inputCameraId,
malikakashedb38962023-09-06 00:03:35 +00001222 int clientUid,
Austin Borgered99f642023-06-01 16:51:35 -07001223 const std::string& packageName) {
1224 std::string packageNameVal = packageName;
malikakashedb38962023-09-06 00:03:35 +00001225 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001226 packageNameVal = getPackageNameFromUid(clientUid);
1227 }
malikakash65d20692023-09-07 01:06:33 +00001228 if (clientUid < AID_APP_START || packageNameVal.empty()) {
malikakashedb38962023-09-06 00:03:35 +00001229 // We shouldn't remap cameras for processes with system/vendor UIDs.
1230 return inputCameraId;
1231 }
malikakash82ed4352023-07-21 22:44:34 +00001232 Mutex::Autolock lock(mCameraIdRemappingLock);
1233 if (auto packageMapIter = mCameraIdRemapping.find(packageNameVal);
1234 packageMapIter != mCameraIdRemapping.end()) {
malikakash82ed4352023-07-21 22:44:34 +00001235 auto packageMap = packageMapIter->second;
1236 if (auto replacementIdIter = packageMap.find(inputCameraId);
1237 replacementIdIter != packageMap.end()) {
malikakashedb38962023-09-06 00:03:35 +00001238 ALOGI("%s: resolveCameraId: remapping cameraId %s for %s to %s",
malikakash82ed4352023-07-21 22:44:34 +00001239 __FUNCTION__, inputCameraId.c_str(),
malikakashedb38962023-09-06 00:03:35 +00001240 packageNameVal.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001241 replacementIdIter->second.c_str());
1242 return replacementIdIter->second;
1243 }
1244 }
1245 return inputCameraId;
1246}
1247
Biswarup Pal37a75182024-01-16 15:53:35 +00001248std::optional<std::string> CameraService::resolveCameraId(
1249 const std::string& inputCameraId,
1250 int32_t deviceId,
1251 int32_t devicePolicy,
1252 int clientUid,
1253 const std::string& packageName) {
1254 if ((deviceId == kDefaultDeviceId)
1255 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1256 auto [storedDeviceId, _] =
1257 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1258 if (storedDeviceId != kDefaultDeviceId) {
1259 // Trying to access a virtual camera from default-policy device context, we should fail.
1260 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1261 inputCameraId.c_str(), deviceId);
1262 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1263 return std::nullopt;
1264 }
1265 return resolveCameraId(inputCameraId, clientUid, packageName);
1266 }
1267
1268 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1269}
1270
1271Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait, int32_t deviceId,
1272 int32_t devicePolicy, CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001273 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001274 Mutex::Autolock l(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001275 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId, deviceId, devicePolicy);
1276 if (cameraIdStr.empty()) {
1277 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
1278 cameraId, deviceId);
1279 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1280 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1281 }
malikakashedb38962023-09-06 00:03:35 +00001282
Austin Borgered99f642023-06-01 16:51:35 -07001283 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001284 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1285 "characteristics for system only device %s: ", cameraIdStr.c_str());
1286 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001287
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001288 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001289 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001290 return STATUS_ERROR(ERROR_DISCONNECTED,
1291 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001292 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001293 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001294 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001295 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1296 if (hasSystemCameraPermissions) {
1297 cameraIdBound = mNumberOfCameras;
1298 }
1299 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001300 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1301 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001302 }
1303
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001304 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001305 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001306 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borgered99f642023-06-01 16:51:35 -07001307 cameraIdStr, overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001308 if (err != OK) {
1309 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1310 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1311 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001312 logServiceError(std::string("Error retrieving camera info from device ")
1313 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001314 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001315
Ruben Brunkcc776712015-02-17 20:18:47 -08001316 return ret;
1317}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001318
Biswarup Pal37a75182024-01-16 15:53:35 +00001319std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1320 int32_t deviceId, int32_t devicePolicy) {
1321 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1322 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1323 std::optional<std::string> cameraIdOptional =
1324 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1325 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1326 }
1327
1328 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001329 auto callingPid = getCallingPid();
1330 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001331 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1332 callingPid, callingUid, /* checkCameraPermissions= */ false);
1333 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001334 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001335 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001336 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1337 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1338 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001339 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001340 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001341
Biswarup Pal37a75182024-01-16 15:53:35 +00001342 std::string unresolvedCameraId = (*cameraIds)[cameraIdInt];
1343 return resolveCameraId(unresolvedCameraId, getCallingUid());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001344}
1345
Biswarup Pal37a75182024-01-16 15:53:35 +00001346std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1347 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001348 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001349 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001350}
1351
Austin Borgered99f642023-06-01 16:51:35 -07001352Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +00001353 int targetSdkVersion, bool overrideToPortrait, int32_t deviceId, int32_t devicePolicy,
1354 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001355 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001356
Zhijun He2b59be82013-09-25 10:14:30 -07001357 if (!cameraInfo) {
1358 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001359 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001360 }
1361
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001362 if (!mInitialized) {
1363 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
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");;
Zhijun He2b59be82013-09-25 10:14:30 -07001367 }
1368
Biswarup Pal37a75182024-01-16 15:53:35 +00001369 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
1370 devicePolicy, getCallingUid());
1371 if (!cameraIdOptional.has_value()) {
1372 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1373 unresolvedCameraId.c_str(), deviceId);
1374 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1375 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1376 }
1377 std::string cameraId = cameraIdOptional.value();
1378
Austin Borgered99f642023-06-01 16:51:35 -07001379 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001380 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001381 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001382 }
1383
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001384 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001385
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001386 bool overrideForPerfClass =
1387 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001388 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001389 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borgered99f642023-06-01 16:51:35 -07001390 cameraId, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001391 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001392 if (res == NAME_NOT_FOUND) {
1393 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001394 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001395 strerror(-res), res);
1396 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001397 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1398 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001399 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001400 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001401 strerror(-res), res);
1402 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001403 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001404 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Austin Borgered99f642023-06-01 16:51:35 -07001405 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1406 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001407 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
Austin Borgered99f642023-06-01 16:51:35 -07001408 "for device %s", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001409 }
Austin Borger22c5c852024-03-08 13:31:36 -08001410 int callingPid = getCallingPid();
1411 int callingUid = getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +01001412 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001413 // If it's not calling from cameraserver, check the permission only if
1414 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
1415 // it would've already been checked in shouldRejectSystemCameraConnection.
Austin Borger249e6592024-03-10 22:28:11 -07001416 bool checkPermissionForCamera = hasPermissionsForCamera(cameraId, callingPid, callingUid);
Emilian Peeve20c6372018-08-14 18:45:53 +01001417 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001418 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001419 !checkPermissionForCamera) {
Emilian Peeve20c6372018-08-14 18:45:53 +01001420 res = cameraInfo->removePermissionEntries(
Austin Borgered99f642023-06-01 16:51:35 -07001421 mCameraProviderManager->getProviderTagIdLocked(cameraId),
Emilian Peeve20c6372018-08-14 18:45:53 +01001422 &tagsRemoved);
1423 if (res != OK) {
1424 cameraInfo->clear();
1425 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
1426 " characteristics needing camera permission for device %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07001427 cameraId.c_str(), strerror(-res), res);
Emilian Peeve20c6372018-08-14 18:45:53 +01001428 }
1429 }
1430
1431 if (!tagsRemoved.empty()) {
1432 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1433 tagsRemoved.data(), tagsRemoved.size());
1434 if (res != OK) {
1435 cameraInfo->clear();
1436 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
Austin Borgered99f642023-06-01 16:51:35 -07001437 "keys needing permission for device %s: %s (%d)", cameraId.c_str(),
Emilian Peeve20c6372018-08-14 18:45:53 +01001438 strerror(-res), res);
1439 }
1440 }
1441
Zhijun He2b59be82013-09-25 10:14:30 -07001442 return ret;
1443}
1444
Biswarup Pal37a75182024-01-16 15:53:35 +00001445Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId, int32_t deviceId,
1446 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001447 ATRACE_CALL();
1448 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001449
Biswarup Pal37a75182024-01-16 15:53:35 +00001450 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
1451 devicePolicy, getCallingUid());
1452 if (!cameraIdOptional.has_value()) {
1453 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1454 unresolvedCameraId.c_str(), deviceId);
1455 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1456 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1457 }
1458 std::string cameraId = cameraIdOptional.value();
1459
Rucha Katakwar38284522021-11-10 11:25:21 -08001460 if (!mInitialized) {
1461 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1462 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1463 }
1464
Biswarup Pal37a75182024-01-16 15:53:35 +00001465 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001466 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1467 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1468 }
1469
Austin Borgered99f642023-06-01 16:51:35 -07001470 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001471 if (res != OK) {
1472 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001473 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001474 strerror(-res), res);
1475 }
1476 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1477 return Status::ok();
1478}
1479
Austin Borgered99f642023-06-01 16:51:35 -07001480std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001481 time_t now = time(nullptr);
1482 char formattedTime[64];
1483 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001484 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001485}
1486
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001487Status CameraService::getCameraVendorTagDescriptor(
1488 /*out*/
1489 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001490 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001491 if (!mInitialized) {
1492 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001493 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001494 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001495 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1496 if (globalDescriptor != nullptr) {
1497 *desc = *(globalDescriptor.get());
1498 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001499 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001500}
1501
Emilian Peev71c73a22017-03-21 16:35:51 +00001502Status CameraService::getCameraVendorTagCache(
1503 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1504 ATRACE_CALL();
1505 if (!mInitialized) {
1506 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1507 return STATUS_ERROR(ERROR_DISCONNECTED,
1508 "Camera subsystem not available");
1509 }
1510 sp<VendorTagDescriptorCache> globalCache =
1511 VendorTagDescriptorCache::getGlobalVendorTagCache();
1512 if (globalCache != nullptr) {
1513 *cache = *(globalCache.get());
1514 }
1515 return Status::ok();
1516}
1517
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001518void CameraService::clearCachedVariables() {
1519 BasicClient::BasicClient::sCameraService = nullptr;
1520}
1521
Austin Borgered99f642023-06-01 16:51:35 -07001522std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001523 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001524 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001525
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001526 int deviceVersion = 0;
1527
Emilian Peevf53f66e2017-04-11 14:29:43 +01001528 status_t res;
1529 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001530 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001531 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001532 if (res != OK || transport == IPCTransport::INVALID) {
1533 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001534 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001535 return std::make_pair(-1, IPCTransport::INVALID) ;
1536 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001537 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001538
Emilian Peevf53f66e2017-04-11 14:29:43 +01001539 hardware::CameraInfo info;
1540 if (facing) {
Austin Borgered99f642023-06-01 16:51:35 -07001541 res = mCameraProviderManager->getCameraInfo(cameraId, overrideToPortrait,
Austin Borger18b30a72022-10-27 12:20:29 -07001542 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001543 if (res != OK) {
1544 return std::make_pair(-1, IPCTransport::INVALID);
1545 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001546 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001547 if (orientation) {
1548 *orientation = info.orientation;
1549 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001550 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001551
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001552 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001553}
1554
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001555Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001556 switch(err) {
1557 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001558 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001559 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001560 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1561 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001562 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001563 return STATUS_ERROR(ERROR_DISCONNECTED,
1564 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001565 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001566 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1567 "Camera HAL encountered error %d: %s",
1568 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001569 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001570}
1571
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001572Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001573 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1574 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001575 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001576 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001577 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
malikakash73125c62023-07-21 22:44:34 +00001578 bool forceSlowJpegMode, const std::string& originalCameraId,
1579 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001580 // For HIDL devices
1581 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1582 // Create CameraClient based on device version reported by the HAL.
1583 int deviceVersion = deviceVersionAndTransport.first;
1584 switch(deviceVersion) {
1585 case CAMERA_DEVICE_API_VERSION_1_0:
1586 ALOGE("Camera using old HAL version: %d", deviceVersion);
1587 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1588 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001589 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001590 break;
1591 case CAMERA_DEVICE_API_VERSION_3_0:
1592 case CAMERA_DEVICE_API_VERSION_3_1:
1593 case CAMERA_DEVICE_API_VERSION_3_2:
1594 case CAMERA_DEVICE_API_VERSION_3_3:
1595 case CAMERA_DEVICE_API_VERSION_3_4:
1596 case CAMERA_DEVICE_API_VERSION_3_5:
1597 case CAMERA_DEVICE_API_VERSION_3_6:
1598 case CAMERA_DEVICE_API_VERSION_3_7:
1599 break;
1600 default:
1601 // Should not be reachable
1602 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1603 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1604 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001605 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001606 }
1607 }
1608 if (effectiveApiLevel == API_1) { // Camera1 API route
1609 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001610 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001611 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001612 api1CameraId, facing, sensorOrientation,
Chengfei Taobe683db2023-01-31 18:52:49 +00001613 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait,
1614 forceSlowJpegMode);
1615 ALOGI("%s: Camera1 API (legacy), override to portrait %d, forceSlowJpegMode %d",
1616 __FUNCTION__, overrideToPortrait, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001617 } else { // Camera2 API route
1618 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1619 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001620 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001621 cameraService->mCameraServiceProxyWrapper,
1622 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001623 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
malikakash82ed4352023-07-21 22:44:34 +00001624 overrideForPerfClass, overrideToPortrait, originalCameraId);
Austin Borger18b30a72022-10-27 12:20:29 -07001625 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001626 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001627 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001628}
1629
Austin Borgered99f642023-06-01 16:51:35 -07001630std::string CameraService::toString(std::set<userid_t> intSet) {
1631 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001632 bool first = true;
1633 for (userid_t i : intSet) {
1634 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001635 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001636 first = false;
1637 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001638 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001639 }
1640 }
Austin Borgered99f642023-06-01 16:51:35 -07001641 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001642}
1643
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001644int32_t CameraService::mapToInterface(TorchModeStatus status) {
1645 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1646 switch (status) {
1647 case TorchModeStatus::NOT_AVAILABLE:
1648 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1649 break;
1650 case TorchModeStatus::AVAILABLE_OFF:
1651 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1652 break;
1653 case TorchModeStatus::AVAILABLE_ON:
1654 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1655 break;
1656 default:
1657 ALOGW("Unknown new flash status: %d", status);
1658 }
1659 return serviceStatus;
1660}
1661
1662CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1663 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1664 switch (status) {
1665 case CameraDeviceStatus::NOT_PRESENT:
1666 serviceStatus = StatusInternal::NOT_PRESENT;
1667 break;
1668 case CameraDeviceStatus::PRESENT:
1669 serviceStatus = StatusInternal::PRESENT;
1670 break;
1671 case CameraDeviceStatus::ENUMERATING:
1672 serviceStatus = StatusInternal::ENUMERATING;
1673 break;
1674 default:
1675 ALOGW("Unknown new HAL device status: %d", status);
1676 }
1677 return serviceStatus;
1678}
1679
1680int32_t CameraService::mapToInterface(StatusInternal status) {
1681 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1682 switch (status) {
1683 case StatusInternal::NOT_PRESENT:
1684 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1685 break;
1686 case StatusInternal::PRESENT:
1687 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1688 break;
1689 case StatusInternal::ENUMERATING:
1690 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1691 break;
1692 case StatusInternal::NOT_AVAILABLE:
1693 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1694 break;
1695 case StatusInternal::UNKNOWN:
1696 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1697 break;
1698 default:
1699 ALOGW("Unknown new internal device status: %d", status);
1700 }
1701 return serviceStatus;
1702}
1703
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001704Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001705 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001706
Austin Borgered99f642023-06-01 16:51:35 -07001707 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001708 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001709 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001710 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001711 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1712 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001713 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Chengfei Taobe683db2023-01-31 18:52:49 +00001714 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true,
Austin Borgered99f642023-06-01 16:51:35 -07001715 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001716 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001717 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001718 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001719 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001720}
1721
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001722Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001723 /*out*/
1724 CameraParameters* parameters) {
1725
1726 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1727
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001728 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001729
1730 if (parameters == NULL) {
1731 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001732 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001733 }
1734
malikakashedb38962023-09-06 00:03:35 +00001735 std::string unresolvedCameraId = std::to_string(cameraId);
1736 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08001737 getCallingUid());
Ruben Brunkcc776712015-02-17 20:18:47 -08001738
1739 // Check if we already have parameters
1740 {
1741 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001742 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001743 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001744 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001745 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001746 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001747 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001748 }
1749 CameraParameters p = cameraState->getShimParams();
1750 if (!p.isEmpty()) {
1751 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001752 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001753 }
1754 }
1755
Austin Borger22c5c852024-03-08 13:31:36 -08001756 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001757 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001758 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001759 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001760 // Error already logged by callee
1761 return ret;
1762 }
1763
1764 // Check for parameters again
1765 {
1766 // Scope for service lock
1767 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001768 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001769 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001770 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001771 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001772 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001773 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001774 CameraParameters p = cameraState->getShimParams();
1775 if (!p.isEmpty()) {
1776 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001777 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001778 }
1779 }
1780
Ruben Brunkcc776712015-02-17 20:18:47 -08001781 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1782 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001783 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001784}
1785
Austin Borgered99f642023-06-01 16:51:35 -07001786Status CameraService::validateConnectLocked(const std::string& cameraId,
1787 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001788 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001789
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001790#ifdef __BRILLO__
1791 UNUSED(clientName8);
1792 UNUSED(clientUid);
1793 UNUSED(clientPid);
1794 UNUSED(originalClientPid);
1795#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001796 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1797 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001798 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001799 return allowed;
1800 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001801#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001802
Austin Borger22c5c852024-03-08 13:31:36 -08001803 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001804
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001805 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001806 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1807 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001808 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001809 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001810 }
1811
Ruben Brunkcc776712015-02-17 20:18:47 -08001812 if (getCameraState(cameraId) == nullptr) {
1813 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001814 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001815 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001816 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001817 }
1818
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001819 status_t err = checkIfDeviceIsUsable(cameraId);
1820 if (err != NO_ERROR) {
1821 switch(err) {
1822 case -ENODEV:
1823 case -EBUSY:
1824 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001825 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001826 default:
1827 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001828 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001829 }
1830 }
1831 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001832}
1833
Austin Borgered99f642023-06-01 16:51:35 -07001834Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1835 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001836 /*out*/int& originalClientPid) const {
Austin Borger22c5c852024-03-08 13:31:36 -08001837 int callingPid = getCallingPid();
1838 int callingUid = getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001839
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001840 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001841 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001842 clientUid = callingUid;
1843 } else if (!isTrustedCallingUid(callingUid)) {
1844 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1845 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001846 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1847 "Untrusted caller (calling PID %d, UID %d) trying to "
1848 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001849 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001850 clientName.c_str(), clientPid, clientUid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001851 }
1852
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001853 // Check if we can trust clientPid
1854 if (clientPid == USE_CALLING_PID) {
1855 clientPid = callingPid;
1856 } else if (!isTrustedCallingUid(callingUid)) {
1857 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1858 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001859 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1860 "Untrusted caller (calling PID %d, UID %d) trying to "
1861 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001862 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001863 clientName.c_str(), clientPid, clientUid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001864 }
1865
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001866 if (shouldRejectSystemCameraConnection(cameraId)) {
1867 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1868 cameraId.c_str());
1869 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001870 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001871 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001872 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1873 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001874 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001875 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001876 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001877
1878 }
1879
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001880 // If it's not calling from cameraserver, check the permission if the
1881 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1882 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001883 bool checkPermissionForCamera =
1884 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001885 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001886 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001887 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001888 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1889 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001890 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001891 }
1892
Svet Ganova453d0d2018-01-11 15:37:58 -08001893 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001894 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001895 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001896 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1897 clientPid, clientUid);
1898 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001899 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1900 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001901 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001902 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001903 }
1904
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001905 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1906 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1907 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1908 if ((!isAutomotivePrivilegedClient(callingUid) ||
1909 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1910 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001911 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1912 return STATUS_ERROR_FMT(ERROR_DISABLED,
1913 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001914 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001915 }
1916
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001917 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1918 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001919 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001920 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001921
Ruben Brunk6267b532015-04-30 17:44:07 -07001922 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001923
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001924 // For non-system clients : Only allow clients who are being used by the current foreground
1925 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08001926 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001927 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001928 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1929 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001930 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001931 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1932 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001933 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001934 }
1935
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001936 if (flags::camera_hsum_permission()) {
1937 // If the System User tries to access the camera when the device is running in
1938 // headless system user mode, ensure that client has the required permission
1939 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07001940 if (isHeadlessSystemUserMode()
1941 && (clientUserId == USER_SYSTEM)
1942 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001943 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
1944 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1945 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1946 User without camera headless system user permission",
Austin Borger249e6592024-03-10 22:28:11 -07001947 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001948 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001949 }
1950
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001951 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001952}
1953
Austin Borgered99f642023-06-01 16:51:35 -07001954status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001955 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001956 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001957 if (cameraState == nullptr) {
1958 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001959 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001960 return -ENODEV;
1961 }
1962
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001963 StatusInternal currentStatus = cameraState->getStatus();
1964 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001965 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001966 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001967 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001968 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001969 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001970 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001971 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001972 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001973
Ruben Brunkcc776712015-02-17 20:18:47 -08001974 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001975}
1976
Ruben Brunkcc776712015-02-17 20:18:47 -08001977void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001978 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001979
Ruben Brunkcc776712015-02-17 20:18:47 -08001980 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001981 auto clientDescriptor =
1982 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001983 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001984 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1985
1986 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001987 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001988
1989 if (evicted.size() > 0) {
1990 // This should never happen - clients should already have been removed in disconnect
1991 for (auto& i : evicted) {
1992 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001993 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001994 }
1995
1996 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1997 __FUNCTION__);
1998 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001999
2000 // And register a death notification for the client callback. Do
2001 // this last to avoid Binder policy where a nested Binder
2002 // transaction might be pre-empted to service the client death
2003 // notification if the client process dies before linkToDeath is
2004 // invoked.
2005 sp<IBinder> remoteCallback = client->getRemote();
2006 if (remoteCallback != nullptr) {
2007 remoteCallback->linkToDeath(this);
2008 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002009}
2010
Austin Borgered99f642023-06-01 16:51:35 -07002011status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
2012 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
2013 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08002014 /*out*/
2015 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07002016 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002017 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08002018 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002019 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08002020 DescriptorPtr clientDescriptor;
2021 {
2022 if (effectiveApiLevel == API_1) {
2023 // If we are using API1, any existing client for this camera ID with the same remote
2024 // should be returned rather than evicted to allow MediaRecorder to work properly.
2025
2026 auto current = mActiveClientManager.get(cameraId);
2027 if (current != nullptr) {
2028 auto clientSp = current->getValue();
2029 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002030 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07002031 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002032 " API level, evicting prior client...");
2033 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002034 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002035 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002036 *client = clientSp;
2037 return NO_ERROR;
2038 }
2039 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002040 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002041 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08002042
Ruben Brunkcc776712015-02-17 20:18:47 -08002043 // Get state for the given cameraId
2044 auto state = getCameraState(cameraId);
2045 if (state == nullptr) {
2046 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07002047 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002048 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07002049 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002050 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002051
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002052 sp<IServiceManager> sm = defaultServiceManager();
2053 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08002054 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002055 // If processinfo service is not available and the client is automotive privileged
2056 // client used for safety critical uses cases such as rear-view and surround-view which
2057 // needs to be available before android boot completes, then use the hardcoded values
2058 // for the process state and priority score. As this scenario is before android system
2059 // services are up and client is native client, hence using NATIVE_ADJ as the priority
2060 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
2061 // visible on the top.
2062 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2063 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2064 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
2065 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
2066 } else {
2067 // Get current active client PIDs
2068 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
2069 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002070
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002071 std::vector<int> priorityScores(ownerPids.size());
2072 std::vector<int> states(ownerPids.size());
2073
2074 // Get priority scores of all active PIDs
2075 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
2076 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
2077 if (err != OK) {
2078 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
2079 return err;
2080 }
2081
2082 // Update all active clients' priorities
2083 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
2084 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
2085 pidToPriorityMap.emplace(ownerPids[i],
2086 resource_policy::ClientPriority(priorityScores[i], states[i],
2087 /* isVendorClient won't get copied over*/ false,
2088 /* oomScoreOffset won't get copied over*/ 0));
2089 }
2090 mActiveClientManager.updatePriorities(pidToPriorityMap);
2091
2092 int32_t actualScore = priorityScores[priorityScores.size() - 1];
2093 int32_t actualState = states[states.size() - 1];
2094
2095 // Make descriptor for incoming client. We store the oomScoreOffset
2096 // since we might need it later on new handleEvictionsLocked and
2097 // ProcessInfoService would not take that into account.
2098 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2099 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2100 state->getConflicting(), actualScore, clientPid, actualState,
2101 oomScoreOffset, systemNativeClient);
2102 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002103
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002104 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
2105
Ruben Brunkcc776712015-02-17 20:18:47 -08002106 // Find clients that would be evicted
2107 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
2108
2109 // If the incoming client was 'evicted,' higher priority clients have the camera in the
2110 // background, so we cannot do evictions
2111 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2112 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2113 " priority).", clientPid);
2114
2115 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002116 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002117 auto incompatibleClients =
2118 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2119
Austin Borgered99f642023-06-01 16:51:35 -07002120 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2121 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2122 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002123 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002124
2125 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002126 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002127 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002128 i->getKey().c_str(),
2129 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002130 i->getOwnerId(), i->getPriority().getScore(),
2131 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002132 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002133 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2134 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002135 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002136 }
2137
2138 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002139 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002140 mEventLog.add(msg);
2141
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002142 auto current = mActiveClientManager.get(cameraId);
2143 if (current != nullptr) {
2144 return -EBUSY; // CAMERA_IN_USE
2145 } else {
2146 return -EUSERS; // MAX_CAMERAS_IN_USE
2147 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002148 }
2149
2150 for (auto& i : evicted) {
2151 sp<BasicClient> clientSp = i->getValue();
2152 if (clientSp.get() == nullptr) {
2153 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2154
2155 // TODO: Remove this
2156 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2157 __FUNCTION__);
2158 mActiveClientManager.remove(i);
2159 continue;
2160 }
2161
2162 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002163 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002164 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002165
Ruben Brunkcc776712015-02-17 20:18:47 -08002166 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002167 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002168 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2169 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002170 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002171 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002172 i->getPriority().getState(), cameraId.c_str(),
2173 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002174 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002175
2176 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002177 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002178 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002179 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002180 }
2181
Ruben Brunkcc776712015-02-17 20:18:47 -08002182 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2183 // other clients from connecting in mServiceLockWrapper if held
2184 mServiceLock.unlock();
2185
2186 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002187 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002188
2189 // Destroy evicted clients
2190 for (auto& i : evictedClients) {
2191 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002192 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002193 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002194
Austin Borger22c5c852024-03-08 13:31:36 -08002195 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002196
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002197 for (const auto& i : evictedClients) {
2198 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002199 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002200 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2201 if (ret == TIMED_OUT) {
2202 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002203 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2204 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002205 return -EBUSY;
2206 }
2207 if (ret != NO_ERROR) {
2208 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002209 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2210 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002211 return ret;
2212 }
2213 }
2214
2215 evictedClients.clear();
2216
Ruben Brunkcc776712015-02-17 20:18:47 -08002217 // Once clients have been disconnected, relock
2218 mServiceLock.lock();
2219
2220 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2221 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2222 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002223 }
2224
Ruben Brunkcc776712015-02-17 20:18:47 -08002225 *partial = clientDescriptor;
2226 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002227}
2228
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002229Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002230 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002231 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07002232 const std::string& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002233 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08002234 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002235 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07002236 bool overrideToPortrait,
Chengfei Taobe683db2023-01-31 18:52:49 +00002237 bool forceSlowJpegMode,
Biswarup Pal37a75182024-01-16 15:53:35 +00002238 int32_t deviceId,
2239 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002240 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002241 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002242 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002243 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002244
Biswarup Pal37a75182024-01-16 15:53:35 +00002245 std::string cameraIdStr = cameraIdIntToStr(api1CameraId, deviceId, devicePolicy);
2246 if (cameraIdStr.empty()) {
2247 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
2248 api1CameraId, deviceId);
2249 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2250 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2251 }
malikakashedb38962023-09-06 00:03:35 +00002252
Ruben Brunkcc776712015-02-17 20:18:47 -08002253 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002254 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
2255 clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002256 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002257 overrideToPortrait, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002258
Biswarup Pal37a75182024-01-16 15:53:35 +00002259 if (!ret.isOk()) {
2260 logRejected(cameraIdStr, getCallingPid(), clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002261 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002262 }
2263
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002264 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002265
2266 const sp<IServiceManager> sm(defaultServiceManager());
2267 const auto& mActivityManager = getActivityManager();
2268 if (mActivityManager) {
2269 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002270 getCallingUid(),
2271 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002272 }
2273
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002274 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002275}
2276
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002277bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2278 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002279 // If the client is not a vendor client, don't add listener if
2280 // a) the camera is a publicly hidden secure camera OR
2281 // b) the camera is a system only camera and the client doesn't
2282 // have android.permission.SYSTEM_CAMERA permissions.
2283 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2284 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002285 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002286 return true;
2287 }
2288 return false;
2289}
2290
Austin Borgered99f642023-06-01 16:51:35 -07002291bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002292 // Rules for rejection:
2293 // 1) If cameraserver tries to access this camera device, accept the
2294 // connection.
2295 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002296 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002297 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2298 // and the serving thread is a non hwbinder thread, the client must have
2299 // android.permission.SYSTEM_CAMERA permissions to connect.
2300
Austin Borger22c5c852024-03-08 13:31:36 -08002301 int cPid = getCallingPid();
2302 int cUid = getCallingUid();
2303 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002304 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2305 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002306 // This isn't a known camera ID, so it's not a system camera
2307 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2308 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002309 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002310
2311 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002312 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002313 return false;
2314 }
2315 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002316 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002317 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2318 return true;
2319 }
2320 // (3) Here we only check for permissions if it is a system only camera device. This is since
2321 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2322 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2323 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002324 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002325 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002326 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2327 cameraId.c_str());
2328 return true;
2329 }
2330
2331 return false;
2332}
2333
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002334Status CameraService::connectDevice(
2335 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002336 const std::string& unresolvedCameraId,
2337 const std::string& clientPackageName,
2338 const std::optional<std::string>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002339 int clientUid, int oomScoreOffset, int targetSdkVersion,
Biswarup Pal37a75182024-01-16 15:53:35 +00002340 bool overrideToPortrait, int32_t deviceId, int32_t devicePolicy,
Ruben Brunkcc776712015-02-17 20:18:47 -08002341 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002342 sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002343 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002344 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002345 sp<CameraDeviceClient> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002346 std::string clientPackageNameAdj = clientPackageName;
Austin Borger22c5c852024-03-08 13:31:36 -08002347 int callingPid = getCallingPid();
2348 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002349 bool systemNativeClient = false;
Austin Borger22c5c852024-03-08 13:31:36 -08002350 if (callerHasSystemUid() && (clientPackageNameAdj.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002351 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borgered99f642023-06-01 16:51:35 -07002352 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002353 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002354 }
Austin Borger249e6592024-03-10 22:28:11 -07002355
Biswarup Pal37a75182024-01-16 15:53:35 +00002356 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
2357 devicePolicy, callingUid, clientPackageNameAdj);
2358 if (!cameraIdOptional.has_value()) {
2359 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
2360 unresolvedCameraId.c_str(), deviceId);
2361 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2362 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2363 }
2364 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002365
2366 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002367 std::string msg =
2368 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
2369 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
2370 cameraId.c_str());
2371 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2372 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002373 }
2374
Austin Borger9bfa0a72022-08-03 17:50:40 -07002375 userid_t clientUserId = multiuser_get_user_id(clientUid);
Austin Borger9bfa0a72022-08-03 17:50:40 -07002376 if (clientUid == USE_CALLING_UID) {
2377 clientUserId = multiuser_get_user_id(callingUid);
2378 }
2379
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002380 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2381 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002382 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2383 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002384 std::string msg = "Camera disabled by device policy";
2385 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2386 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002387 }
2388
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002389 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002390 if (oomScoreOffset > 0
2391 && !hasPermissionsForSystemCamera(cameraId, callingPid,
Austin Borger249e6592024-03-10 22:28:11 -07002392 callingUid)
2393 && !isTrustedCallingUid(callingUid)) {
Austin Borgered99f642023-06-01 16:51:35 -07002394 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002395 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07002396 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2397 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2398 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002399 }
2400
Austin Borgered99f642023-06-01 16:51:35 -07002401 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
2402 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002403 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
malikakash73125c62023-07-21 22:44:34 +00002404 targetSdkVersion, overrideToPortrait, /*forceSlowJpegMode*/false, unresolvedCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002405 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002406
Biswarup Pal37a75182024-01-16 15:53:35 +00002407 if (!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002408 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002409 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002410 }
2411
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002412 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002413 Mutex::Autolock lock(mServiceLock);
2414
2415 // Clear the previous cached logs and reposition the
2416 // file offset to beginning of the file to log new data.
2417 // If either truncate or lseek fails, close the previous file and create a new one.
2418 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2419 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2420 // Close the previous memfd.
2421 close(mMemFd);
2422 // If failure to wipe the data, then create a new file and
2423 // assign the new value to mMemFd.
2424 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2425 if (mMemFd == -1) {
2426 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2427 }
2428 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002429 const sp<IServiceManager> sm(defaultServiceManager());
2430 const auto& mActivityManager = getActivityManager();
2431 if (mActivityManager) {
2432 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002433 callingUid,
2434 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002435 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002436 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002437}
2438
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002439bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2440 int callingPid, int callingUid) {
2441 if (!isAutomotiveDevice()) {
2442 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2443 }
2444
2445 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2446 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2447 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2448 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2449 "using camera %s", callingUid, cam_id.c_str());
2450 return false;
2451 }
2452
2453 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2454 return true;
2455 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2456 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002457 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2458 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002459 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2460 return false;
2461 } else {
2462 return true;
2463 }
2464 }
2465 return false;
2466}
2467
Austin Borgered99f642023-06-01 16:51:35 -07002468std::string CameraService::getPackageNameFromUid(int clientUid) {
2469 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002470
Avichal Rakesh5788fec2024-03-15 14:39:20 -07002471 sp<IPermissionController> permCtrl;
2472 if (flags::cache_permission_services()) {
2473 permCtrl = getPermissionController();
2474 } else {
2475 sp<IServiceManager> sm = defaultServiceManager();
2476#pragma clang diagnostic push
2477#pragma clang diagnostic ignored "-Wdeprecated-declarations"
2478 // Using deprecated function to preserve functionality until the
2479 // cache_permission_services flag is removed.
2480 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
2481#pragma clang diagnostic pop
2482 if (binder == 0) {
2483 ALOGE("Cannot get permission service");
2484 permCtrl = nullptr;
2485 } else {
2486 permCtrl = interface_cast<IPermissionController>(binder);
2487 }
2488 }
2489
2490 if (permCtrl == nullptr) {
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002491 // Return empty package name and the further interaction
2492 // with camera will likely fail
2493 return packageName;
2494 }
2495
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002496 Vector<String16> packages;
2497
2498 permCtrl->getPackagesForUid(clientUid, packages);
2499
2500 if (packages.isEmpty()) {
2501 ALOGE("No packages for calling UID %d", clientUid);
2502 // Return empty package name and the further interaction
2503 // with camera will likely fail
2504 return packageName;
2505 }
2506
2507 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002508 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002509
2510 return packageName;
2511}
2512
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002513template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002514Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2515 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2516 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002517 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002518 bool overrideToPortrait, bool forceSlowJpegMode, const std::string& originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002519 /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002520 binder::Status ret = binder::Status::ok();
2521
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002522 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002523 std::string clientPackageName;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002524 int packageUid = (clientUid == USE_CALLING_UID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002525 getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002526 if (clientPackageNameMaybe.size() <= 0) {
2527 // NDK calls don't come with package names, but we need one for various cases.
2528 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2529 // do exist. For all authentication cases, all packages under the same UID get the
2530 // same permissions, so picking any associated package name is sufficient. For some
2531 // other cases, this may give inaccurate names for clients in logs.
2532 isNonSystemNdk = true;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002533 clientPackageName = getPackageNameFromUid(packageUid);
2534 } else {
2535 clientPackageName = clientPackageNameMaybe;
2536 }
2537
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002538 int originalClientPid = 0;
2539
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002540 int packagePid = (clientPid == USE_CALLING_PID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002541 getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002542 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002543 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002544 static_cast<int>(effectiveApiLevel));
2545
Shuzhen Wang316781a2020-08-18 18:11:01 -07002546 nsecs_t openTimeNs = systemTime();
2547
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002548 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002549 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002550 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002551
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002552 {
2553 // Acquire mServiceLock and prevent other clients from connecting
2554 std::unique_ptr<AutoConditionLock> lock =
2555 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2556
2557 if (lock == nullptr) {
2558 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2559 , clientPid);
2560 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2561 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002562 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002563 }
2564
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002565 // Enforce client permissions and do basic validity checks
Biswarup Pal37a75182024-01-16 15:53:35 +00002566 if (!(ret = validateConnectLocked(cameraId, clientPackageName,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002567 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2568 return ret;
2569 }
2570
2571 // Check the shim parameters after acquiring lock, if they have already been updated and
2572 // we were doing a shim update, return immediately
2573 if (shimUpdateOnly) {
2574 auto cameraState = getCameraState(cameraId);
2575 if (cameraState != nullptr) {
2576 if (!cameraState->getShimParams().isEmpty()) return ret;
2577 }
2578 }
2579
2580 status_t err;
2581
2582 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002583 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002584 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002585 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2586 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002587 switch (err) {
2588 case -ENODEV:
2589 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2590 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002591 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002592 case -EBUSY:
2593 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2594 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002595 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002596 case -EUSERS:
2597 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2598 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002599 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002600 default:
2601 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2602 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002603 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002604 }
2605 }
2606
2607 if (clientTmp.get() != nullptr) {
2608 // Handle special case for API1 MediaRecorder where the existing client is returned
2609 device = static_cast<CLIENT*>(clientTmp.get());
2610 return ret;
2611 }
2612
2613 // give flashlight a chance to close devices if necessary.
2614 mFlashlight->prepareDeviceOpen(cameraId);
2615
Austin Borger18b30a72022-10-27 12:20:29 -07002616 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002617 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07002618 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
2619 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002620 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002621 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002622 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002623 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002624 }
2625
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002626 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002627 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002628 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002629 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002630 clientFeatureId, cameraId, api1CameraId, facing,
2631 orientation, clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002632 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
malikakash82ed4352023-07-21 22:44:34 +00002633 overrideToPortrait, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002634 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002635 return ret;
2636 }
2637 client = static_cast<CLIENT*>(tmp.get());
2638
2639 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2640 __FUNCTION__);
2641
Austin Borgered99f642023-06-01 16:51:35 -07002642 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002643 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002644 if (err != OK) {
2645 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002646 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002647 mServiceLock.unlock();
2648 client->disconnect();
2649 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002650 switch(err) {
2651 case BAD_VALUE:
2652 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002653 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002654 case -EBUSY:
2655 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002656 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002657 case -EUSERS:
2658 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2659 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002660 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002661 case PERMISSION_DENIED:
2662 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002663 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002664 case -EACCES:
2665 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002666 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002667 case -ENODEV:
2668 default:
2669 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002670 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002671 strerror(-err), err);
2672 }
2673 }
2674
2675 // Update shim paremeters for legacy clients
2676 if (effectiveApiLevel == API_1) {
2677 // Assume we have always received a Client subclass for API1
2678 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2679 String8 rawParams = shimClient->getParameters();
2680 CameraParameters params(rawParams);
2681
2682 auto cameraState = getCameraState(cameraId);
2683 if (cameraState != nullptr) {
2684 cameraState->setShimParams(params);
2685 } else {
2686 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002687 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002688 }
2689 }
2690
Ravneetaeb20dc2022-03-30 05:33:03 +00002691 // Enable/disable camera service watchdog
2692 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2693
Emilian Peev6d45db82024-01-18 20:11:54 +00002694 CameraMetadata chars;
2695 bool rotateAndCropSupported = true;
2696 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
2697 &chars, overrideToPortrait);
2698 if (err == OK) {
2699 auto availableRotateCropEntry = chars.find(
2700 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2701 if (availableRotateCropEntry.count <= 1) {
2702 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002703 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002704 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002705 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2706 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002707 }
2708
Emilian Peev6d45db82024-01-18 20:11:54 +00002709 if (rotateAndCropSupported) {
2710 // Set rotate-and-crop override behavior
2711 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2712 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
2713 } else if (overrideToPortrait && portraitRotation != 0) {
2714 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2715 switch (portraitRotation) {
2716 case 90:
2717 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2718 break;
2719 case 180:
2720 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2721 break;
2722 case 270:
2723 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2724 break;
2725 default:
2726 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2727 break;
2728 }
2729 client->setRotateAndCropOverride(rotateAndCropMode);
2730 } else {
2731 client->setRotateAndCropOverride(
2732 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2733 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2734 }
2735 }
2736
2737 bool autoframingSupported = true;
2738 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2739 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2740 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2741 autoframingSupported = false;
2742 }
2743
2744 if (autoframingSupported) {
2745 // Set autoframing override behaviour
2746 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2747 client->setAutoframingOverride(mOverrideAutoframingMode);
2748 } else {
2749 client->setAutoframingOverride(
2750 mCameraServiceProxyWrapper->getAutoframingOverride(
2751 clientPackageName));
2752 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002753 }
2754
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002755 bool isCameraPrivacyEnabled;
2756 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002757 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002758 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2759 toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2760 } else {
2761 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002762 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002763 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002764
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002765 if (client->supportsCameraMute()) {
2766 client->setCameraMute(
2767 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2768 } else if (isCameraPrivacyEnabled) {
2769 // no camera mute supported, but privacy is on! => disconnect
2770 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2771 client->getPackageName().c_str(), cameraId.c_str());
2772 // Do not hold mServiceLock while disconnecting clients, but
2773 // retain the condition blocking other clients from connecting
2774 // in mServiceLockWrapper if held.
2775 mServiceLock.unlock();
2776 // Clear caller identity temporarily so client disconnect PID
2777 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002778 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002779 // Note AppOp to trigger the "Unblock" dialog
2780 client->noteAppOp();
2781 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002782 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002783 // Reacquire mServiceLock
2784 mServiceLock.lock();
2785
2786 return STATUS_ERROR_FMT(ERROR_DISABLED,
2787 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002788 }
2789
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002790 if (shimUpdateOnly) {
2791 // If only updating legacy shim parameters, immediately disconnect client
2792 mServiceLock.unlock();
2793 client->disconnect();
2794 mServiceLock.lock();
2795 } else {
2796 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002797 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002798 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002799
2800 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002801 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002802 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002803 } // lock is destroyed, allow further connect calls
2804
2805 // Important: release the mutex here so the client can call back into the service from its
2806 // destructor (can be at the end of the call)
2807 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002808
2809 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002810 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002811 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002812
Cliff Wud3a05312021-04-26 23:07:31 +08002813 {
2814 Mutex::Autolock lock(mInjectionParametersLock);
2815 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2816 mInjectionInitPending = false;
2817 status_t res = NO_ERROR;
2818 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2819 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002820 sp<BasicClient> clientSp = clientDescriptor->getValue();
2821 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2822 if(res != OK) {
2823 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2824 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002825 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002826 }
2827 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002828 if (res != OK) {
2829 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2830 }
2831 } else {
2832 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002833 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002834 res = NO_INIT;
2835 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2836 }
2837 }
2838 }
2839
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002840 return ret;
2841}
2842
Austin Borgered99f642023-06-01 16:51:35 -07002843status_t CameraService::addOfflineClient(const std::string &cameraId,
2844 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002845 if (offlineClient.get() == nullptr) {
2846 return BAD_VALUE;
2847 }
2848
2849 {
2850 // Acquire mServiceLock and prevent other clients from connecting
2851 std::unique_ptr<AutoConditionLock> lock =
2852 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2853
2854 if (lock == nullptr) {
2855 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2856 , __FUNCTION__, offlineClient->getClientPid());
2857 return TIMED_OUT;
2858 }
2859
2860 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2861 if (onlineClientDesc.get() == nullptr) {
2862 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2863 cameraId.c_str());
2864 return BAD_VALUE;
2865 }
2866
2867 // Offline clients do not evict or conflict with other online devices. Resource sharing
2868 // conflicts are handled by the camera provider which will either succeed or fail before
2869 // reaching this method.
2870 const auto& onlinePriority = onlineClientDesc->getPriority();
2871 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2872 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002873 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002874 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002875 // native clients don't have offline processing support.
2876 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002877 if (offlineClientDesc == nullptr) {
2878 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2879 return BAD_VALUE;
2880 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002881
2882 // Allow only one offline device per camera
2883 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2884 if (!incompatibleClients.empty()) {
2885 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2886 return BAD_VALUE;
2887 }
2888
Austin Borgered99f642023-06-01 16:51:35 -07002889 std::string monitorTags = isClientWatched(offlineClient.get())
2890 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002891 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002892 if (err != OK) {
2893 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2894 return err;
2895 }
2896
2897 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2898 if (evicted.size() > 0) {
2899 for (auto& i : evicted) {
2900 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002901 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002902 }
2903
2904 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2905 "properly", __FUNCTION__);
2906
2907 return BAD_VALUE;
2908 }
2909
2910 logConnectedOffline(offlineClientDesc->getKey(),
2911 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002912 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002913
2914 sp<IBinder> remoteCallback = offlineClient->getRemote();
2915 if (remoteCallback != nullptr) {
2916 remoteCallback->linkToDeath(this);
2917 }
2918 } // lock is destroyed, allow further connect calls
2919
2920 return OK;
2921}
2922
Austin Borgered99f642023-06-01 16:51:35 -07002923Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +00002924 int32_t torchStrength, const sp<IBinder>& clientBinder, int32_t deviceId,
2925 int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002926 Mutex::Autolock lock(mServiceLock);
2927
2928 ATRACE_CALL();
2929 if (clientBinder == nullptr) {
2930 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2931 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2932 "Torch client binder in null.");
2933 }
2934
Austin Borger22c5c852024-03-08 13:31:36 -08002935 int uid = getCallingUid();
Biswarup Pal37a75182024-01-16 15:53:35 +00002936 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
2937 devicePolicy, uid);
2938 if (!cameraIdOptional.has_value()) {
2939 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
2940 unresolvedCameraId.c_str(), deviceId);
2941 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2942 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2943 }
2944 std::string cameraId = cameraIdOptional.value();
2945
Austin Borgered99f642023-06-01 16:51:35 -07002946 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002947 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002948 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002949 }
2950
2951 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002952 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002953 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002954 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002955 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002956 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002957 }
2958
2959 StatusInternal cameraStatus = state->getStatus();
2960 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2961 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002962 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002963 (int)cameraStatus);
2964 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002965 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002966 }
2967
2968 {
2969 Mutex::Autolock al(mTorchStatusMutex);
2970 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002971 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002972 if (err != OK) {
2973 if (err == NAME_NOT_FOUND) {
2974 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002975 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002976 }
2977 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002978 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002979 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2980 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002981 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002982 }
2983
2984 if (status == TorchModeStatus::NOT_AVAILABLE) {
2985 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2986 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002987 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002988 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2989 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002990 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002991 } else {
2992 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002993 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002994 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2995 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002996 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002997 }
2998 }
2999 }
3000
3001 {
3002 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003003 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08003004 }
3005 // Check if the current torch strength level is same as the new one.
3006 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07003007 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003008
Austin Borgered99f642023-06-01 16:51:35 -07003009 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003010
3011 if (err != OK) {
3012 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003013 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08003014 switch (err) {
3015 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003016 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
3017 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003018 errorCode = ERROR_ILLEGAL_ARGUMENT;
3019 break;
3020 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003021 msg = fmt::sprintf("Camera \"%s\" is in use",
3022 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003023 errorCode = ERROR_CAMERA_IN_USE;
3024 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08003025 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07003026 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08003027 "valid range.", torchStrength);
3028 errorCode = ERROR_ILLEGAL_ARGUMENT;
3029 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08003030 default:
Austin Borgered99f642023-06-01 16:51:35 -07003031 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08003032 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08003033 }
Austin Borgered99f642023-06-01 16:51:35 -07003034 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3035 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003036 }
3037
3038 {
3039 // update the link to client's death
3040 // Store the last client that turns on each camera's torch mode.
3041 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003042 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08003043 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003044 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08003045 } else {
3046 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
3047 mTorchClientMap.replaceValueAt(index, clientBinder);
3048 }
3049 clientBinder->linkToDeath(this);
3050 }
3051
Austin Borger22c5c852024-03-08 13:31:36 -08003052 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08003053 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07003054 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08003055 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07003056 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003057 }
3058 return Status::ok();
3059}
3060
malikakash73125c62023-07-21 22:44:34 +00003061Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Biswarup Pal37a75182024-01-16 15:53:35 +00003062 const sp<IBinder>& clientBinder, int32_t deviceId, int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003063 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003064
3065 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07003066 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003067 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003068 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
3069 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003070 }
3071
Austin Borger22c5c852024-03-08 13:31:36 -08003072 int uid = getCallingUid();
Biswarup Pal37a75182024-01-16 15:53:35 +00003073 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
3074 devicePolicy, uid);
3075 if (!cameraIdOptional.has_value()) {
3076 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
3077 unresolvedCameraId.c_str(), deviceId);
3078 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3079 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3080 }
3081 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003082
Austin Borgered99f642023-06-01 16:51:35 -07003083 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003084 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07003085 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003086 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003087 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07003088 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003089 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07003090 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003091 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003092 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003093 }
3094
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003095 StatusInternal cameraStatus = state->getStatus();
3096 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003097 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07003098 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
3099 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003100 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003101 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003102 }
3103
3104 {
3105 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003106 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003107 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003108 if (err != OK) {
3109 if (err == NAME_NOT_FOUND) {
3110 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003111 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003112 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003113 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003114 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003115 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07003116 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003117 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003118 }
3119
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003120 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003121 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003122 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003123 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003124 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3125 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003126 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003127 } else {
3128 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003129 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003130 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3131 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003132 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003133 }
3134 }
3135 }
3136
Ruben Brunk99e69712015-05-26 17:25:07 -07003137 {
3138 // Update UID map - this is used in the torch status changed callbacks, so must be done
3139 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003140 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003141 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003142 }
3143
Austin Borgered99f642023-06-01 16:51:35 -07003144 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003145
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003146 if (err != OK) {
3147 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003148 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003149 switch (err) {
3150 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003151 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3152 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003153 errorCode = ERROR_ILLEGAL_ARGUMENT;
3154 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003155 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003156 msg = fmt::sprintf("Camera \"%s\" is in use",
3157 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003158 errorCode = ERROR_CAMERA_IN_USE;
3159 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003160 default:
Austin Borgered99f642023-06-01 16:51:35 -07003161 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003162 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003163 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003164 errorCode = ERROR_INVALID_OPERATION;
3165 }
Austin Borgered99f642023-06-01 16:51:35 -07003166 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3167 logServiceError(msg, errorCode);
3168 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003169 }
3170
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003171 {
3172 // update the link to client's death
3173 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003174 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003175 if (enabled) {
3176 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003177 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003178 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003179 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003180 mTorchClientMap.replaceValueAt(index, clientBinder);
3181 }
3182 clientBinder->linkToDeath(this);
3183 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003184 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003185 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003186 }
3187
Austin Borger22c5c852024-03-08 13:31:36 -08003188 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003189 std::string torchState = enabled ? "on" : "off";
3190 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3191 torchState.c_str(), clientPid);
3192 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003193 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003194}
3195
Austin Borgered99f642023-06-01 16:51:35 -07003196void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3197 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3198 mTorchUidMap[cameraId].first = uid;
3199 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003200 } else {
3201 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003202 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003203 }
3204}
3205
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003206Status CameraService::notifySystemEvent(int32_t eventId,
3207 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003208 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003209 const int selfPid = getpid();
3210
3211 // Permission checks
3212 if (pid != selfPid) {
3213 // Ensure we're being called by system_server, or similar process with
3214 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003215 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003216 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003217 ALOGE("Permission Denial: cannot send updates to camera service about system"
3218 " events from pid=%d, uid=%d", pid, uid);
3219 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003220 "No permission to send updates to camera service about system events"
3221 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003222 }
3223 }
3224
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003225 ATRACE_CALL();
3226
Ruben Brunk36597b22015-03-20 22:15:57 -07003227 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003228 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003229 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003230 // from a system server crash
3231 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003232 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003233 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003234 break;
3235 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003236 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3237 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003238 if (args.size() != 1) {
3239 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3240 "USB Device Event requires 1 argument");
3241 }
3242
Valentin Iftime29e2e152021-08-13 15:17:33 +02003243 // Notify CameraProviderManager for lazy HALs
3244 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3245 std::to_string(args[0]));
3246 break;
3247 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003248 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003249 default: {
3250 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3251 eventId);
3252 break;
3253 }
3254 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003255 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003256}
3257
Emilian Peev53722fa2019-02-22 17:47:20 -08003258void CameraService::notifyMonitoredUids() {
3259 Mutex::Autolock lock(mStatusListenerLock);
3260
3261 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003262 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003263 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3264 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003265 }
3266}
3267
Austin Borgerdddb7552023-03-30 17:53:01 -07003268void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3269 Mutex::Autolock lock(mStatusListenerLock);
3270
3271 for (const auto& it : mListenerList) {
3272 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3273 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3274 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3275 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3276 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3277 }
3278 }
3279}
3280
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003281Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003282 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003283 const int selfPid = getpid();
3284
3285 // Permission checks
3286 if (pid != selfPid) {
3287 // Ensure we're being called by system_server, or similar process with
3288 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003289 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003290 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003291 ALOGE("Permission Denial: cannot send updates to camera service about device"
3292 " state changes from pid=%d, uid=%d", pid, uid);
3293 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3294 "No permission to send updates to camera service about device state"
3295 " changes from pid=%d, uid=%d", pid, uid);
3296 }
3297 }
3298
3299 ATRACE_CALL();
3300
Austin Borger18b30a72022-10-27 12:20:29 -07003301 {
3302 Mutex::Autolock lock(mServiceLock);
3303 mDeviceState = newState;
3304 }
3305
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003306 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003307
3308 return Status::ok();
3309}
3310
Emilian Peev8b64f282021-03-25 16:49:57 -07003311Status CameraService::notifyDisplayConfigurationChange() {
3312 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003313 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003314 const int selfPid = getpid();
3315
3316 // Permission checks
3317 if (callingPid != selfPid) {
3318 // Ensure we're being called by system_server, or similar process with
3319 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003320 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003321 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003322 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3323 " changes from pid=%d, uid=%d", callingPid, uid);
3324 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3325 "No permission to send updates to camera service about orientation"
3326 " changes from pid=%d, uid=%d", callingPid, uid);
3327 }
3328 }
3329
3330 Mutex::Autolock lock(mServiceLock);
3331
3332 // Don't do anything if rotate-and-crop override via cmd is active
3333 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3334
3335 const auto clients = mActiveClientManager.getAll();
3336 for (auto& current : clients) {
3337 if (current != nullptr) {
3338 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003339 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3340 basicClient->setRotateAndCropOverride(
3341 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3342 basicClient->getPackageName(),
3343 basicClient->getCameraFacing(),
3344 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003345 }
3346 }
3347 }
3348
3349 return Status::ok();
3350}
3351
Biswarup Pal37a75182024-01-16 15:53:35 +00003352// TODO(b/291736219): This to be made device-aware.
Emilian Peev8b64f282021-03-25 16:49:57 -07003353Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003354 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3355 ATRACE_CALL();
3356 if (!concurrentCameraIds) {
3357 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3358 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3359 }
3360
3361 if (!mInitialized) {
3362 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003363 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003364 return STATUS_ERROR(ERROR_DISCONNECTED,
3365 "Camera subsystem is not available");
3366 }
3367 // First call into the provider and get the set of concurrent camera
3368 // combinations
3369 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003370 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003371 for (auto &combination : concurrentCameraCombinations) {
3372 std::vector<std::string> validCombination;
3373 for (auto &cameraId : combination) {
3374 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003375 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003376 if (state == nullptr) {
3377 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3378 continue;
3379 }
3380 StatusInternal status = state->getStatus();
3381 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3382 continue;
3383 }
Austin Borgered99f642023-06-01 16:51:35 -07003384 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003385 continue;
3386 }
3387 validCombination.push_back(cameraId);
3388 }
3389 if (validCombination.size() != 0) {
3390 concurrentCameraIds->push_back(std::move(validCombination));
3391 }
3392 }
3393 return Status::ok();
3394}
3395
3396Status CameraService::isConcurrentSessionConfigurationSupported(
3397 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003398 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003399 if (!isSupported) {
3400 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3401 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3402 }
3403
3404 if (!mInitialized) {
3405 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3406 return STATUS_ERROR(ERROR_DISCONNECTED,
3407 "Camera subsystem is not available");
3408 }
3409
3410 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003411 int callingPid = getCallingPid();
3412 int callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003413 bool hasCameraPermission = ((callingPid == getpid()) ||
3414 hasPermissionsForCamera(callingPid, callingUid));
3415 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003416 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3417 "android.permission.CAMERA needed to call"
3418 "isConcurrentSessionConfigurationSupported");
3419 }
3420
3421 status_t res =
3422 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003423 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3424 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003425 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003426 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003427 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003428 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3429 "support %s (%d)", strerror(-res), res);
3430 }
3431 return Status::ok();
3432}
3433
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003434Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3435 /*out*/
3436 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003437 return addListenerHelper(listener, cameraStatuses);
3438}
3439
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003440binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3441 std::vector<hardware::CameraStatus>* cameraStatuses) {
3442 return addListenerHelper(listener, cameraStatuses, false, true);
3443}
3444
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003445Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3446 /*out*/
3447 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003448 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003449 ATRACE_CALL();
3450
Igor Murashkinbfc99152013-02-27 12:55:20 -08003451 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003452
Ruben Brunk3450ba72015-06-16 11:00:37 -07003453 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003454 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003455 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003456 }
3457
Austin Borger22c5c852024-03-08 13:31:36 -08003458 auto clientPid = getCallingPid();
3459 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003460 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003461
Igor Murashkinbfc99152013-02-27 12:55:20 -08003462 Mutex::Autolock lock(mServiceLock);
3463
Ruben Brunkcc776712015-02-17 20:18:47 -08003464 {
3465 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003466 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003467 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003468 ALOGW("%s: Tried to add listener %p which was already subscribed",
3469 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003470 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003471 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003472 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003473
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003474 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003475 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3476 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003477 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003478 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003479 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003480 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003481 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3482 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3483 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003484 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003485 // The listener still needs to be added to the list of listeners, regardless of what
3486 // permissions the listener process has / whether it is a vendor listener. Since it might be
3487 // eligible to listen to other camera ids.
3488 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003489 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003490 }
3491
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003492 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003493 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003494 Mutex::Autolock lock(mCameraStatesLock);
3495 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003496 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3497 auto [deviceId, mappedCameraId] =
3498 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3499
3500 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003501 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003502 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3503 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003504 }
3505 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003506 // Remove the camera statuses that should be hidden from the client, we do
3507 // this after collecting the states in order to avoid holding
3508 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3509 // the same time.
3510 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3511 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003512 std::string cameraId = s.cameraId;
3513 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
3514 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM,
3515 clientUid);
3516 if (!cameraIdOptional.has_value()) {
3517 std::string msg =
3518 fmt::sprintf(
3519 "Camera %s: Invalid camera id for device id %d",
3520 s.cameraId.c_str(), s.deviceId);
3521 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3522 return true;
3523 }
3524 cameraId = cameraIdOptional.value();
3525 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3526 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3527 ALOGE("%s: Invalid camera id %s, skipping status update",
3528 __FUNCTION__, s.cameraId.c_str());
3529 return true;
3530 }
3531 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3532 clientUid);
3533 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003534
Biswarup Pal37a75182024-01-16 15:53:35 +00003535 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003536 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003537 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003538 // Add only default device cameras here, as virtual cameras currently don't support torch
3539 // anyway. Note that this is a simplification of the implementation here, and we should
3540 // change this when virtual cameras support torch.
3541 if (s.deviceId == kDefaultDeviceId) {
3542 idsChosenForCallback.insert(s.cameraId);
3543 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003544 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003545
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003546 /*
3547 * Immediately signal current torch status to this listener only
3548 * This may be a subset of all the devices, so don't include it in the response directly
3549 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003550 {
3551 Mutex::Autolock al(mTorchStatusMutex);
3552 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003553 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003554 // The camera id is visible to the client. Fine to send torch
3555 // callback.
3556 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003557 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3558 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003559 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003560 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003561 }
3562
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003563 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003564}
Ruben Brunkcc776712015-02-17 20:18:47 -08003565
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003566Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003567 ATRACE_CALL();
3568
Igor Murashkinbfc99152013-02-27 12:55:20 -08003569 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3570
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003571 if (listener == 0) {
3572 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003573 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003574 }
3575
Igor Murashkinbfc99152013-02-27 12:55:20 -08003576 Mutex::Autolock lock(mServiceLock);
3577
Ruben Brunkcc776712015-02-17 20:18:47 -08003578 {
3579 Mutex::Autolock lock(mStatusListenerLock);
3580 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003581 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003582 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003583 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003584 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003585 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003586 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003587 }
3588 }
3589
3590 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3591 __FUNCTION__, listener.get());
3592
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003593 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003594}
3595
Austin Borgered99f642023-06-01 16:51:35 -07003596Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003597
3598 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003599 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3600
3601 if (parameters == NULL) {
3602 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003603 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003604 }
3605
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003606 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003607
3608 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003609 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003610 // Error logged by caller
3611 return ret;
3612 }
3613
3614 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003615
Austin Borgered99f642023-06-01 16:51:35 -07003616 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003617
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003618 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003619}
3620
Austin Borgered99f642023-06-01 16:51:35 -07003621Status CameraService::supportsCameraApi(const std::string& unresolvedCameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003622 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003623 ATRACE_CALL();
3624
malikakashedb38962023-09-06 00:03:35 +00003625 const std::string cameraId = resolveCameraId(
Austin Borger22c5c852024-03-08 13:31:36 -08003626 unresolvedCameraId, getCallingUid());
malikakash82ed4352023-07-21 22:44:34 +00003627
Austin Borgered99f642023-06-01 16:51:35 -07003628 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003629
3630 switch (apiVersion) {
3631 case API_VERSION_1:
3632 case API_VERSION_2:
3633 break;
3634 default:
Austin Borgered99f642023-06-01 16:51:35 -07003635 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3636 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3637 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003638 }
3639
Austin Borger18b30a72022-10-27 12:20:29 -07003640 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -07003641 auto deviceVersionAndTransport = getDeviceVersion(cameraId, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003642 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003643 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3644 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3645 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003646 }
3647 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3648 int deviceVersion = deviceVersionAndTransport.first;
3649 switch (deviceVersion) {
3650 case CAMERA_DEVICE_API_VERSION_1_0:
3651 case CAMERA_DEVICE_API_VERSION_3_0:
3652 case CAMERA_DEVICE_API_VERSION_3_1:
3653 if (apiVersion == API_VERSION_2) {
3654 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003655 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003656 *isSupported = false;
3657 } else { // if (apiVersion == API_VERSION_1) {
3658 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003659 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003660 *isSupported = true;
3661 }
3662 break;
3663 case CAMERA_DEVICE_API_VERSION_3_2:
3664 case CAMERA_DEVICE_API_VERSION_3_3:
3665 case CAMERA_DEVICE_API_VERSION_3_4:
3666 case CAMERA_DEVICE_API_VERSION_3_5:
3667 case CAMERA_DEVICE_API_VERSION_3_6:
3668 case CAMERA_DEVICE_API_VERSION_3_7:
3669 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003670 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003671 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003672 break;
3673 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003674 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3675 deviceVersion, cameraId.c_str());
3676 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3677 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003678 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003679 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003680 } else {
3681 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003682 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003683 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003684}
3685
Austin Borgered99f642023-06-01 16:51:35 -07003686Status CameraService::isHiddenPhysicalCamera(const std::string& unresolvedCameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003687 /*out*/ bool *isSupported) {
3688 ATRACE_CALL();
3689
malikakashedb38962023-09-06 00:03:35 +00003690 const std::string cameraId = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08003691 getCallingUid());
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003692
Austin Borgered99f642023-06-01 16:51:35 -07003693 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3694 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003695
3696 return Status::ok();
3697}
3698
Cliff Wud8cae102021-03-11 01:37:42 +08003699Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003700 const std::string& packageName, const std::string& internalCamId,
3701 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003702 const sp<ICameraInjectionCallback>& callback,
3703 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003704 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003705 ATRACE_CALL();
3706
Austin Borgered99f642023-06-01 16:51:35 -07003707 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003708 const int pid = getCallingPid();
3709 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003710 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3711 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003712 "Permission Denial: no permission to inject camera");
3713 }
3714
3715 // Do not allow any camera injection that injects or replaces a virtual camera.
3716 auto [deviceIdForInternalCamera, _] =
3717 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3718 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3719 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3720 "Cannot replace a virtual camera");
3721 }
3722 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3723 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3724 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3725 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3726 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003727 }
3728
3729 ALOGV(
3730 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3731 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003732 __FUNCTION__, packageName.c_str(),
3733 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003734
Cliff Wud3a05312021-04-26 23:07:31 +08003735 {
3736 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003737 mInjectionInternalCamId = internalCamId;
3738 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003739 mInjectionStatusListener->addListener(callback);
3740 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003741 status_t res = NO_ERROR;
3742 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3743 // If the client already exists, we can directly connect to the camera device through the
3744 // client's injectCamera(), otherwise we need to wait until the client is established
3745 // (execute connectHelper()) before injecting the camera to the camera device.
3746 if (clientDescriptor != nullptr) {
3747 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003748 sp<BasicClient> clientSp = clientDescriptor->getValue();
3749 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3750 if(res != OK) {
3751 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3752 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003753 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003754 }
3755 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003756 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003757 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3758 }
3759 } else {
3760 mInjectionInitPending = true;
3761 }
3762 }
Cliff Wud8cae102021-03-11 01:37:42 +08003763
Cliff Wud3a05312021-04-26 23:07:31 +08003764 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003765}
3766
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003767Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003768 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003769 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3770 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3771 return Status::ok();
3772}
3773
Ruben Brunkcc776712015-02-17 20:18:47 -08003774void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003775 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003776 for (auto& i : mActiveClientManager.getAll()) {
3777 auto clientSp = i->getValue();
3778 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003779 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003780 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003781 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003782 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003783 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003784}
3785
Ruben Brunkcc776712015-02-17 20:18:47 -08003786bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003787 bool ret = false;
3788 {
3789 // Acquire mServiceLock and prevent other clients from connecting
3790 std::unique_ptr<AutoConditionLock> lock =
3791 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003792
Ruben Brunkcc776712015-02-17 20:18:47 -08003793 std::vector<sp<BasicClient>> evicted;
3794 for (auto& i : mActiveClientManager.getAll()) {
3795 auto clientSp = i->getValue();
3796 if (clientSp.get() == nullptr) {
3797 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3798 mActiveClientManager.remove(i);
3799 continue;
3800 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003801 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003802 mActiveClientManager.remove(i);
3803 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003804
Ruben Brunkcc776712015-02-17 20:18:47 -08003805 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003806 clientSp->notifyError(
3807 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003808 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003809 }
3810 }
3811
Ruben Brunkcc776712015-02-17 20:18:47 -08003812 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3813 // other clients from connecting in mServiceLockWrapper if held
3814 mServiceLock.unlock();
3815
Ruben Brunk36597b22015-03-20 22:15:57 -07003816 // Do not clear caller identity, remote caller should be client proccess
3817
Ruben Brunkcc776712015-02-17 20:18:47 -08003818 for (auto& i : evicted) {
3819 if (i.get() != nullptr) {
3820 i->disconnect();
3821 ret = true;
3822 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003823 }
3824
Ruben Brunkcc776712015-02-17 20:18:47 -08003825 // Reacquire mServiceLock
3826 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003827
Ruben Brunkcc776712015-02-17 20:18:47 -08003828 } // lock is destroyed, allow further connect calls
3829
3830 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003831}
3832
Ruben Brunkcc776712015-02-17 20:18:47 -08003833std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003834 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003835 std::shared_ptr<CameraState> state;
3836 {
3837 Mutex::Autolock lock(mCameraStatesLock);
3838 auto iter = mCameraStates.find(cameraId);
3839 if (iter != mCameraStates.end()) {
3840 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003841 }
3842 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003843 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003844}
3845
Austin Borgered99f642023-06-01 16:51:35 -07003846sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003847 // Remove from active clients list
3848 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3849 if (clientDescriptorPtr == nullptr) {
3850 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003851 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003852 return sp<BasicClient>{nullptr};
3853 }
3854
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003855 sp<BasicClient> client = clientDescriptorPtr->getValue();
3856 if (client.get() != nullptr) {
3857 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3858 }
3859 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003860}
3861
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003862void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003863 // Acquire mServiceLock and prevent other clients from connecting
3864 std::unique_ptr<AutoConditionLock> lock =
3865 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3866
Ruben Brunk6267b532015-04-30 17:44:07 -07003867 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003868 for (size_t i = 0; i < newUserIds.size(); i++) {
3869 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003870 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003871 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003872 return;
3873 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003874 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003875 }
3876
Ruben Brunka8ca9152015-04-07 14:23:40 -07003877
Ruben Brunk6267b532015-04-30 17:44:07 -07003878 if (newAllowedUsers == mAllowedUsers) {
3879 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3880 return;
3881 }
3882
3883 logUserSwitch(mAllowedUsers, newAllowedUsers);
3884
3885 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003886
3887 // Current user has switched, evict all current clients.
3888 std::vector<sp<BasicClient>> evicted;
3889 for (auto& i : mActiveClientManager.getAll()) {
3890 auto clientSp = i->getValue();
3891
3892 if (clientSp.get() == nullptr) {
3893 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3894 continue;
3895 }
3896
Ruben Brunk6267b532015-04-30 17:44:07 -07003897 // Don't evict clients that are still allowed.
3898 uid_t clientUid = clientSp->getClientUid();
3899 userid_t clientUserId = multiuser_get_user_id(clientUid);
3900 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3901 continue;
3902 }
3903
Ruben Brunk36597b22015-03-20 22:15:57 -07003904 evicted.push_back(clientSp);
3905
Ruben Brunk36597b22015-03-20 22:15:57 -07003906 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003907 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003908
Ruben Brunk36597b22015-03-20 22:15:57 -07003909 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003910 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003911 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003912 " to user switch.", i->getKey().c_str(),
3913 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003914 i->getOwnerId(), i->getPriority().getScore(),
3915 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003916
3917 }
3918
3919 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3920 // blocking other clients from connecting in mServiceLockWrapper if held.
3921 mServiceLock.unlock();
3922
3923 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08003924 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003925
3926 for (auto& i : evicted) {
3927 i->disconnect();
3928 }
3929
Austin Borger22c5c852024-03-08 13:31:36 -08003930 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003931
3932 // Reacquire mServiceLock
3933 mServiceLock.lock();
3934}
Ruben Brunkcc776712015-02-17 20:18:47 -08003935
Austin Borgered99f642023-06-01 16:51:35 -07003936void CameraService::logEvent(const std::string &event) {
3937 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003938 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003939 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003940 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003941 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003942 mEventLog.add(msg);
3943 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3944 // Error event not added to the dumpsys log before
3945 mEventLog.add(msg);
3946 sServiceErrorEventSet.insert(msg);
3947 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003948}
3949
Austin Borgered99f642023-06-01 16:51:35 -07003950void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3951 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003952 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003953 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3954 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003955}
3956
Austin Borgered99f642023-06-01 16:51:35 -07003957void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3958 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003959 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003960 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3961 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003962}
3963
Austin Borgered99f642023-06-01 16:51:35 -07003964void CameraService::logConnected(const std::string &cameraId, int clientPid,
3965 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003966 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003967 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3968 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003969}
3970
Austin Borgered99f642023-06-01 16:51:35 -07003971void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3972 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003973 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003974 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3975 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003976}
3977
Austin Borgered99f642023-06-01 16:51:35 -07003978void CameraService::logRejected(const std::string &cameraId, int clientPid,
3979 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003980 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003981 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3982 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003983}
3984
Austin Borgered99f642023-06-01 16:51:35 -07003985void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3986 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003987 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003988 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3989 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003990}
3991
Ruben Brunk6267b532015-04-30 17:44:07 -07003992void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3993 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003994 std::string newUsers = toString(newUserIds);
3995 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003996 if (oldUsers.size() == 0) {
3997 oldUsers = "<None>";
3998 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003999 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07004000 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
4001 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004002}
4003
Austin Borgered99f642023-06-01 16:51:35 -07004004void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004005 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004006 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004007}
4008
Austin Borgered99f642023-06-01 16:51:35 -07004009void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004010 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004011 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004012}
4013
Austin Borgered99f642023-06-01 16:51:35 -07004014void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004015 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004016 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07004017}
4018
Austin Borgered99f642023-06-01 16:51:35 -07004019void CameraService::logServiceError(const std::string &msg, int errorCode) {
4020 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
4021 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004022}
4023
Ruben Brunk36597b22015-03-20 22:15:57 -07004024status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4025 uint32_t flags) {
4026
Mathias Agopian65ab4712010-07-14 17:59:35 -07004027 // Permission checks
4028 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004029 case SHELL_COMMAND_TRANSACTION: {
4030 int in = data.readFileDescriptor();
4031 int out = data.readFileDescriptor();
4032 int err = data.readFileDescriptor();
4033 int argc = data.readInt32();
4034 Vector<String16> args;
4035 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
4036 args.add(data.readString16());
4037 }
4038 sp<IBinder> unusedCallback;
4039 sp<IResultReceiver> resultReceiver;
4040 status_t status;
4041 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
4042 return status;
4043 }
4044 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
4045 return status;
4046 }
4047 status = shellCommand(in, out, err, args);
4048 if (resultReceiver != nullptr) {
4049 resultReceiver->send(status);
4050 }
4051 return NO_ERROR;
4052 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004053 }
4054
4055 return BnCameraService::onTransact(code, data, reply, flags);
4056}
4057
Mathias Agopian65ab4712010-07-14 17:59:35 -07004058// We share the media players for shutter and recording sound for all clients.
4059// A reference count is kept to determine when we will actually release the
4060// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09004061sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
4062 sp<MediaPlayer> mp = new MediaPlayer();
4063 status_t error;
4064 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08004065 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09004066 error = mp->prepare();
4067 }
4068 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004069 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09004070 mp->disconnect();
4071 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004072 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004073 }
4074 return mp;
4075}
4076
username5755fea2018-12-27 09:48:08 +08004077void CameraService::increaseSoundRef() {
4078 Mutex::Autolock lock(mSoundLock);
4079 mSoundRef++;
4080}
4081
4082void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004083 ATRACE_CALL();
4084
username5755fea2018-12-27 09:48:08 +08004085 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
4086 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
4087 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
4088 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
4089 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4090 }
4091 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
4092 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4093 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4094 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004095 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08004096 }
4097 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4098 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4099 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4100 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4101 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004102 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004103}
4104
username5755fea2018-12-27 09:48:08 +08004105void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004106 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004107 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004108 if (--mSoundRef) return;
4109
4110 for (int i = 0; i < NUM_SOUNDS; i++) {
4111 if (mSoundPlayer[i] != 0) {
4112 mSoundPlayer[i]->disconnect();
4113 mSoundPlayer[i].clear();
4114 }
4115 }
4116}
4117
4118void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004119 ATRACE_CALL();
4120
Mathias Agopian65ab4712010-07-14 17:59:35 -07004121 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004122 if (kind < 0 || kind >= NUM_SOUNDS) {
4123 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4124 return;
4125 }
4126
Mathias Agopian65ab4712010-07-14 17:59:35 -07004127 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004128 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004129 sp<MediaPlayer> player = mSoundPlayer[kind];
4130 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004131 player->seekTo(0);
4132 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004133 }
4134}
4135
4136// ----------------------------------------------------------------------------
4137
4138CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004139 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004140 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004141 const std::string& clientPackageName, bool systemNativeClient,
4142 const std::optional<std::string>& clientFeatureId,
4143 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004144 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004145 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004146 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004147 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004148 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07004149 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004150 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004151 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004152 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004153 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004154 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004155{
Austin Borger22c5c852024-03-08 13:31:36 -08004156 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004157 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004158
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004159 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004160
username5755fea2018-12-27 09:48:08 +08004161 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004162
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004163 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004164}
4165
Mathias Agopian65ab4712010-07-14 17:59:35 -07004166// tear down the client
4167CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004168 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004169 mDestructionStarted = true;
4170
username5755fea2018-12-27 09:48:08 +08004171 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004172 // unconditionally disconnect. function is idempotent
4173 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004174}
4175
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004176sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4177
Igor Murashkin634a5152013-02-20 17:15:11 -08004178CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004179 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004180 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004181 const std::string& clientPackageName, bool nativeClient,
4182 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004183 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004184 int servicePid, bool overrideToPortrait):
Austin Borger249e6592024-03-10 22:28:11 -07004185 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004186 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004187 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004188 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4189 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004190 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004191 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004192 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07004193 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004194 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004195 mRemoteBinder(remoteCallback),
4196 mOpsActive(false),
4197 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004198{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004199 if (sCameraService == nullptr) {
4200 sCameraService = cameraService;
4201 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004202
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004203 // There are 2 scenarios in which a client won't have AppOps operations
4204 // (both scenarios : native clients)
4205 // 1) It's an system native client*, the package name will be empty
4206 // and it will return from this function in the previous if condition
4207 // (This is the same as the previously existing behavior).
4208 // 2) It is a system native client, but its package name has been
4209 // modified for debugging, however it still must not use AppOps since
4210 // the package name is not a real one.
4211 //
4212 // * system native client - native client with UID < AID_APP_START. It
4213 // doesn't exclude clients not on the system partition.
4214 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004215 mAppOpsManager = std::make_unique<AppOpsManager>();
4216 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004217
Charles Chenf075f082024-03-04 23:32:55 +00004218 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004219}
4220
4221CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004222 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004223 mDestructionStarted = true;
4224}
4225
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004226binder::Status CameraService::BasicClient::disconnect() {
4227 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004228 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004229 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004230 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004231 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004232
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004233 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004234 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004235 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004236 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004237
4238 sp<IBinder> remote = getRemote();
4239 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004240 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004241 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004242
4243 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004244 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004245 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004246 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004247 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004248
Igor Murashkincba2c162013-03-20 15:56:31 -07004249 // client shouldn't be able to call into us anymore
4250 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004251
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004252 const auto& mActivityManager = getActivityManager();
4253 if (mActivityManager) {
4254 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004255 getCallingUid(),
4256 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004257 }
4258
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004259 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004260}
4261
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004262status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4263 // No dumping of clients directly over Binder,
4264 // must go through CameraService::dump
4265 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004266 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004267 return OK;
4268}
4269
Austin Borgered99f642023-06-01 16:51:35 -07004270status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004271 // Can't watch tags directly, must go through CameraService::startWatchingTags
4272 return OK;
4273}
4274
4275status_t CameraService::BasicClient::stopWatchingTags(int) {
4276 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4277 return OK;
4278}
4279
4280status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4281 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4282 return OK;
4283}
4284
Austin Borgered99f642023-06-01 16:51:35 -07004285std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004286 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004287}
4288
Emilian Peev8b64f282021-03-25 16:49:57 -07004289int CameraService::BasicClient::getCameraFacing() const {
4290 return mCameraFacing;
4291}
4292
4293int CameraService::BasicClient::getCameraOrientation() const {
4294 return mOrientation;
4295}
Ruben Brunkcc776712015-02-17 20:18:47 -08004296
4297int CameraService::BasicClient::getClientPid() const {
4298 return mClientPid;
4299}
4300
Ruben Brunk6267b532015-04-30 17:44:07 -07004301uid_t CameraService::BasicClient::getClientUid() const {
4302 return mClientUid;
4303}
4304
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004305bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4306 // Defaults to API2.
4307 return level == API_2;
4308}
4309
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004310status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004311 {
4312 Mutex::Autolock l(mAudioRestrictionLock);
4313 mAudioRestriction = mode;
4314 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004315 sCameraService->updateAudioRestriction();
4316 return OK;
4317}
4318
4319int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004320 return sCameraService->updateAudioRestriction();
4321}
4322
4323int32_t CameraService::BasicClient::getAudioRestriction() const {
4324 Mutex::Autolock l(mAudioRestrictionLock);
4325 return mAudioRestriction;
4326}
4327
4328bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4329 switch (mode) {
4330 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4331 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4332 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4333 return true;
4334 default:
4335 return false;
4336 }
4337}
4338
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004339status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4340 if (mode == AppOpsManager::MODE_ERRORED) {
4341 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004342 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004343 return PERMISSION_DENIED;
4344 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4345 // If the calling Uid is trusted (a native service), the AppOpsManager could
4346 // return MODE_IGNORED. Do not treat such case as error.
4347 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4348 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004349
4350 bool isCameraPrivacyEnabled;
4351 if (flags::camera_privacy_allowlist()) {
4352 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4353 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4354 } else {
4355 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004356 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004357 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004358 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4359 // We prefer to successfully open the camera and perform camera muting
4360 // or blocking in connectHelper as handleAppOpMode can be called before the
4361 // connection has been fully established and at that time camera muting
4362 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004363 if (!isUidActive || !isCameraPrivacyEnabled) {
4364 ALOGI("Camera %s: Access for \"%s\" has been restricted",
Austin Borgered99f642023-06-01 16:51:35 -07004365 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004366 // Return the same error as for device policy manager rejection
4367 return -EACCES;
4368 }
4369 }
4370 return OK;
4371}
4372
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004373status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004374 ATRACE_CALL();
4375
Igor Murashkine6800ce2013-03-04 17:25:57 -08004376 {
4377 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004378 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004379 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004380 if (mAppOpsManager != nullptr) {
4381 // Notify app ops that the camera is not available
4382 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004383
4384 if (flags::watch_foreground_changes()) {
4385 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4386 toString16(mClientPackageName),
4387 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4388 } else {
4389 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004390 toString16(mClientPackageName), mOpsCallback);
Austin Borgerca1e0062023-06-28 11:32:55 -07004391 }
Igor Murashkine6800ce2013-03-04 17:25:57 -08004392
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004393 // Just check for camera acccess here on open - delay startOp until
4394 // camera frames start streaming in startCameraStreamingOps
4395 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004396 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004397 status_t res = handleAppOpMode(mode);
4398 if (res != OK) {
4399 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004400 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004401 }
4402
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004403 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004404
4405 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004406 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004407
Austin Borgerdddb7552023-03-30 17:53:01 -07004408 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004409
Shuzhen Wang695044d2020-03-06 09:02:23 -08004410 // Notify listeners of camera open/close status
4411 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4412
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004413 return OK;
4414}
4415
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004416status_t CameraService::BasicClient::startCameraStreamingOps() {
4417 ATRACE_CALL();
4418
4419 if (!mOpsActive) {
4420 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4421 return INVALID_OPERATION;
4422 }
4423 if (mOpsStreaming) {
4424 ALOGV("%s: Streaming already active!", __FUNCTION__);
4425 return OK;
4426 }
4427
4428 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004429 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004430
4431 if (mAppOpsManager != nullptr) {
4432 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004433 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4434 toString16(mClientFeatureId),
4435 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004436 status_t res = handleAppOpMode(mode);
4437 if (res != OK) {
4438 return res;
4439 }
4440 }
4441
4442 mOpsStreaming = true;
4443
4444 return OK;
4445}
4446
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004447status_t CameraService::BasicClient::noteAppOp() {
4448 ATRACE_CALL();
4449
4450 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004451 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004452
4453 // noteAppOp is only used for when camera mute is not supported, in order
4454 // to trigger the sensor privacy "Unblock" dialog
4455 if (mAppOpsManager != nullptr) {
4456 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004457 toString16(mClientPackageName), toString16(mClientFeatureId),
4458 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004459 status_t res = handleAppOpMode(mode);
4460 if (res != OK) {
4461 return res;
4462 }
4463 }
4464
4465 return OK;
4466}
4467
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004468status_t CameraService::BasicClient::finishCameraStreamingOps() {
4469 ATRACE_CALL();
4470
4471 if (!mOpsActive) {
4472 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4473 return INVALID_OPERATION;
4474 }
4475 if (!mOpsStreaming) {
4476 ALOGV("%s: Streaming not active!", __FUNCTION__);
4477 return OK;
4478 }
4479
4480 if (mAppOpsManager != nullptr) {
4481 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004482 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004483 mOpsStreaming = false;
4484 }
4485
4486 return OK;
4487}
4488
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004489status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004490 ATRACE_CALL();
4491
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004492 if (mOpsStreaming) {
4493 // Make sure we've notified everyone about camera stopping
4494 finishCameraStreamingOps();
4495 }
4496
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004497 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004498 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004499 mOpsActive = false;
4500
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004501 // This function is called when a client disconnects. This should
4502 // release the camera, but actually only if it was in a proper
4503 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004504 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004505 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004506
Ruben Brunkcc776712015-02-17 20:18:47 -08004507 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004508 sCameraService->updateStatus(StatusInternal::PRESENT,
4509 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004510 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004511 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004512 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4513 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004514 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004515 mOpsCallback.clear();
4516
Austin Borgerdddb7552023-03-30 17:53:01 -07004517 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004518
Shuzhen Wang695044d2020-03-06 09:02:23 -08004519 // Notify listeners of camera open/close status
4520 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4521
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004522 return OK;
4523}
4524
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004525void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004526 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004527 if (mAppOpsManager == nullptr) {
4528 return;
4529 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004530 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004531 if (op != AppOpsManager::OP_CAMERA) {
4532 ALOGW("Unexpected app ops notification received: %d", op);
4533 return;
4534 }
4535
4536 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004537 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004538 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004539 ALOGV("checkOp returns: %d, %s ", res,
4540 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4541 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4542 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4543 "UNKNOWN");
4544
Shuzhen Wang64900852021-02-05 09:03:29 -08004545 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004546 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4547 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004548 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004549 } else if (res == AppOpsManager::MODE_IGNORED) {
4550 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004551
Austin Borgerca1e0062023-06-28 11:32:55 -07004552 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4553 // If not visible, but still active, then we want to block instead of muting the camera.
4554 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4555 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4556
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004557 bool isCameraPrivacyEnabled;
4558 if (flags::camera_privacy_allowlist()) {
4559 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4560 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4561 } else {
4562 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004563 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004564 }
4565
4566 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004567 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4568 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4569 isCameraPrivacyEnabled);
4570 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4571 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4572 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004573 if (!mUidIsTrusted) {
Austin Borgerca1e0062023-06-28 11:32:55 -07004574 if (flags::watch_foreground_changes()) {
4575 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4576 setCameraMute(true);
4577 } else {
4578 block();
4579 }
4580 } else {
4581 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4582 setCameraMute(true);
4583 } else if (!isUidActive
4584 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4585 block();
4586 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004587 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004588 }
Evan Severson09ab4002021-02-10 14:15:19 -08004589 } else if (res == AppOpsManager::MODE_ALLOWED) {
4590 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004591 }
4592}
4593
Svet Ganova453d0d2018-01-11 15:37:58 -08004594void CameraService::BasicClient::block() {
4595 ATRACE_CALL();
4596
4597 // Reset the client PID to allow server-initiated disconnect,
4598 // and to prevent further calls by client.
Austin Borger22c5c852024-03-08 13:31:36 -08004599 mClientPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004600 CaptureResultExtras resultExtras; // a dummy result (invalid)
4601 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4602 disconnect();
4603}
4604
Mathias Agopian65ab4712010-07-14 17:59:35 -07004605// ----------------------------------------------------------------------------
4606
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004607void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004608 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004609 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004610 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4611 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4612 api1ErrorCode = CAMERA_ERROR_DISABLED;
4613 }
4614 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004615 } else {
4616 ALOGE("mRemoteCallback is NULL!!");
4617 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004618}
4619
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004620// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004621binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004622 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004623 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004624}
4625
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004626bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4627 return level == API_1;
4628}
4629
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004630CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4631 mClient(client) {
4632}
4633
4634void CameraService::Client::OpsCallback::opChanged(int32_t op,
4635 const String16& packageName) {
4636 sp<BasicClient> client = mClient.promote();
4637 if (client != NULL) {
4638 client->opChanged(op, packageName);
4639 }
4640}
4641
Mathias Agopian65ab4712010-07-14 17:59:35 -07004642// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004643// UidPolicy
4644// ----------------------------------------------------------------------------
4645
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004646void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004647 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004648 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004649
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004650 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004651 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004652 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004653 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004654 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4655 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004656 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004657 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004658 if (res == OK) {
4659 mRegistered = true;
4660 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004661 } else {
4662 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004663 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004664}
4665
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004666void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004667 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004668 return;
4669 }
4670
4671 registerWithActivityManager();
4672}
4673
4674void CameraService::UidPolicy::registerSelf() {
4675 // Use check service to see if the activity service is available
4676 // If not available then register for notifications, instead of blocking
4677 // till the service is ready
4678 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004679 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004680 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004681 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004682 } else {
4683 registerWithActivityManager();
4684 }
4685}
4686
Svet Ganova453d0d2018-01-11 15:37:58 -08004687void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004688 Mutex::Autolock _l(mUidLock);
4689
Steven Moreland2f348142019-07-02 15:59:07 -07004690 mAm.unregisterUidObserver(this);
4691 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004692 mRegistered = false;
4693 mActiveUids.clear();
4694 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004695}
4696
4697void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4698 onUidIdle(uid, disabled);
4699}
4700
4701void CameraService::UidPolicy::onUidActive(uid_t uid) {
4702 Mutex::Autolock _l(mUidLock);
4703 mActiveUids.insert(uid);
4704}
4705
4706void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4707 bool deleted = false;
4708 {
4709 Mutex::Autolock _l(mUidLock);
4710 if (mActiveUids.erase(uid) > 0) {
4711 deleted = true;
4712 }
4713 }
4714 if (deleted) {
4715 sp<CameraService> service = mService.promote();
4716 if (service != nullptr) {
4717 service->blockClientsForUid(uid);
4718 }
4719 }
4720}
4721
Emilian Peev53722fa2019-02-22 17:47:20 -08004722void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004723 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004724 bool procStateChange = false;
4725 {
4726 Mutex::Autolock _l(mUidLock);
4727 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4728 mMonitoredUids[uid].procState != procState) {
4729 mMonitoredUids[uid].procState = procState;
4730 procStateChange = true;
4731 }
4732 }
4733
4734 if (procStateChange) {
4735 sp<CameraService> service = mService.promote();
4736 if (service != nullptr) {
4737 service->notifyMonitoredUids();
4738 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004739 }
4740}
4741
Austin Borgerdddb7552023-03-30 17:53:01 -07004742/**
4743 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4744 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4745 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4746 * monitoredUids. If it is revised above some other monitoredUid, signal
4747 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4748 * foreground apps in split screen - state changes will capture all other cases.
4749 */
4750void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4751 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004752 {
4753 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004754 auto it = mMonitoredUids.find(uid);
4755
4756 if (it != mMonitoredUids.end()) {
4757 if (it->second.hasCamera) {
4758 for (auto &monitoredUid : mMonitoredUids) {
4759 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004760 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004761 notifyUidSet.emplace(monitoredUid.first);
4762 }
4763 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004764 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004765 notifyUidSet.emplace(uid);
4766 } else {
4767 for (auto &monitoredUid : mMonitoredUids) {
4768 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004769 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004770 notifyUidSet.emplace(uid);
4771 }
4772 }
4773 }
4774 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004775 }
4776 }
4777
Austin Borgerdddb7552023-03-30 17:53:01 -07004778 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004779 sp<CameraService> service = mService.promote();
4780 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004781 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004782 }
4783 }
4784}
4785
Austin Borgerdddb7552023-03-30 17:53:01 -07004786/**
4787 * Register a uid for monitoring, and note whether it owns a camera.
4788 */
4789void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004790 Mutex::Autolock _l(mUidLock);
4791 auto it = mMonitoredUids.find(uid);
4792 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004793 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004794 } else {
Austin Borger65577682022-02-17 00:25:43 +00004795 MonitoredUid monitoredUid;
4796 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004797 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004798 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004799 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004800 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004801 if (res != OK) {
4802 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4803 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004804 }
4805
4806 if (openCamera) {
4807 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004808 }
4809}
4810
Austin Borgerdddb7552023-03-30 17:53:01 -07004811/**
4812 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4813 */
4814void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004815 Mutex::Autolock _l(mUidLock);
4816 auto it = mMonitoredUids.find(uid);
4817 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004818 it->second.refCount--;
4819 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004820 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004821 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004822 if (res != OK) {
4823 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4824 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004825 } else if (closeCamera) {
4826 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004827 }
4828 } else {
4829 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4830 }
4831}
4832
Austin Borgered99f642023-06-01 16:51:35 -07004833bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004834 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004835 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004836}
4837
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004838static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4839static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004840
Austin Borgered99f642023-06-01 16:51:35 -07004841bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004842 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004843 // If activity manager is unreachable, assume everything is active
4844 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004845 return true;
4846 }
4847 auto it = mOverrideUids.find(uid);
4848 if (it != mOverrideUids.end()) {
4849 return it->second;
4850 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004851 bool active = mActiveUids.find(uid) != mActiveUids.end();
4852 if (!active) {
4853 // We want active UIDs to always access camera with their first attempt since
4854 // there is no guarantee the app is robustly written and would retry getting
4855 // the camera on failure. The inverse case is not a problem as we would take
4856 // camera away soon once we get the callback that the uid is no longer active.
4857 ActivityManager am;
4858 // Okay to access with a lock held as UID changes are dispatched without
4859 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004860 int64_t startTimeMillis = 0;
4861 do {
4862 // TODO: Fix this b/109950150!
4863 // Okay this is a hack. There is a race between the UID turning active and
4864 // activity being resumed. The proper fix is very risky, so we temporary add
4865 // some polling which should happen pretty rarely anyway as the race is hard
4866 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004867 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004868 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004869 if (active) {
4870 break;
4871 }
4872 if (startTimeMillis <= 0) {
4873 startTimeMillis = uptimeMillis();
4874 }
4875 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004876 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004877 if (remainingTimeMillis <= 0) {
4878 break;
4879 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004880 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4881
4882 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004883 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004884 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004885 } while (true);
4886
Svet Ganov7b4ab782018-03-25 12:48:10 -07004887 if (active) {
4888 // Now that we found out the UID is actually active, cache that
4889 mActiveUids.insert(uid);
4890 }
4891 }
4892 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004893}
4894
Varun Shahb42f1eb2019-04-16 14:45:13 -07004895int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4896 Mutex::Autolock _l(mUidLock);
4897 return getProcStateLocked(uid);
4898}
4899
4900int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4901 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4902 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004903 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004904 }
4905 return procState;
4906}
4907
Austin Borgered99f642023-06-01 16:51:35 -07004908void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4909 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004910 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004911}
4912
Austin Borgered99f642023-06-01 16:51:35 -07004913void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004914 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004915}
4916
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004917void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4918 Mutex::Autolock _l(mUidLock);
4919 ALOGV("UidPolicy: ActivityManager has died");
4920 mRegistered = false;
4921 mActiveUids.clear();
4922}
4923
Austin Borgered99f642023-06-01 16:51:35 -07004924void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004925 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004926 bool wasActive = false;
4927 bool isActive = false;
4928 {
4929 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004930 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004931 mOverrideUids.erase(uid);
4932 if (insert) {
4933 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4934 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004935 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004936 }
4937 if (wasActive != isActive && !isActive) {
4938 sp<CameraService> service = mService.promote();
4939 if (service != nullptr) {
4940 service->blockClientsForUid(uid);
4941 }
4942 }
4943}
4944
4945// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004946// SensorPrivacyPolicy
4947// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004948
4949void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4950{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004951 Mutex::Autolock _l(mSensorPrivacyLock);
4952 if (mRegistered) {
4953 return;
4954 }
Evan Severson09ab4002021-02-10 14:15:19 -08004955 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004956 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004957 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004958 mSpm.addToggleSensorPrivacyListener(this);
4959 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004960 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004961 if (flags::camera_privacy_allowlist()) {
4962 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
4963 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
4964 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4965 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004966 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004967 if (res == OK) {
4968 mRegistered = true;
4969 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4970 }
4971}
4972
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004973void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4974 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004975 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004976 return;
4977 }
4978
4979 registerWithSensorPrivacyManager();
4980}
4981
4982void CameraService::SensorPrivacyPolicy::registerSelf() {
4983 // Use checkservice to see if the sensor_privacy service is available
4984 // If service is not available then register for notification
4985 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004986 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004987 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004988 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004989 } else {
4990 registerWithSensorPrivacyManager();
4991 }
4992}
4993
Michael Grooverd1d435a2018-12-18 17:39:42 -08004994void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4995 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004996 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004997 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004998 mSpm.removeToggleSensorPrivacyListener(this);
4999 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005000 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005001 mRegistered = false;
5002 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
5003}
5004
5005bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005006 if (!mRegistered) {
5007 registerWithSensorPrivacyManager();
5008 }
5009
Michael Grooverd1d435a2018-12-18 17:39:42 -08005010 Mutex::Autolock _l(mSensorPrivacyLock);
5011 return mSensorPrivacyEnabled;
5012}
5013
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005014int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
5015 if (!mRegistered) {
5016 registerWithSensorPrivacyManager();
5017 }
5018
5019 Mutex::Autolock _l(mSensorPrivacyLock);
5020 return mCameraPrivacyState;
5021}
5022
Evan Seversond0b69922022-01-27 10:47:34 -08005023bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08005024 if (!hasCameraPrivacyFeature()) {
5025 return false;
5026 }
Evan Seversond0b69922022-01-27 10:47:34 -08005027 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08005028}
5029
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005030bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
5031 if (!hasCameraPrivacyFeature()) {
5032 return SensorPrivacyManager::DISABLED;
5033 }
5034 return mSpm.isCameraPrivacyEnabled(packageName);
5035}
5036
Evan Seversond0b69922022-01-27 10:47:34 -08005037binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005038 int toggleType, int sensor, bool enabled) {
5039 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
5040 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
5041 {
5042 Mutex::Autolock _l(mSensorPrivacyLock);
5043 mSensorPrivacyEnabled = enabled;
5044 }
5045 // if sensor privacy is enabled then block all clients from accessing the camera
5046 if (enabled) {
5047 sp<CameraService> service = mService.promote();
5048 if (service != nullptr) {
5049 service->blockAllClients();
5050 }
5051 }
5052 }
5053 return binder::Status::ok();
5054}
5055
5056binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
5057 int, int sensor, int state) {
5058 if (!flags::camera_privacy_allowlist()
5059 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
5060 return binder::Status::ok();
5061 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08005062 {
5063 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005064 mCameraPrivacyState = state;
5065 }
5066 sp<CameraService> service = mService.promote();
5067 if (!service) {
5068 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005069 }
5070 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005071 if (state == SensorPrivacyManager::ENABLED) {
5072 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08005073 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005074 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005075 }
5076 return binder::Status::ok();
5077}
5078
5079void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
5080 Mutex::Autolock _l(mSensorPrivacyLock);
5081 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
5082 mRegistered = false;
5083}
5084
Evan Severson09ab4002021-02-10 14:15:19 -08005085bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08005086 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
5087 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5088 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
5089 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5090 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08005091}
5092
Michael Grooverd1d435a2018-12-18 17:39:42 -08005093// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005094// CameraState
5095// ----------------------------------------------------------------------------
5096
Austin Borgered99f642023-06-01 16:51:35 -07005097CameraService::CameraState::CameraState(const std::string& id, int cost,
5098 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005099 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005100 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005101 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005102
5103CameraService::CameraState::~CameraState() {}
5104
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005105CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005106 Mutex::Autolock lock(mStatusLock);
5107 return mStatus;
5108}
5109
Austin Borgered99f642023-06-01 16:51:35 -07005110std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005111 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005112 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005113 return res;
5114}
5115
Ruben Brunkcc776712015-02-17 20:18:47 -08005116CameraParameters CameraService::CameraState::getShimParams() const {
5117 return mShimParams;
5118}
5119
5120void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5121 mShimParams = params;
5122}
5123
5124int CameraService::CameraState::getCost() const {
5125 return mCost;
5126}
5127
Austin Borgered99f642023-06-01 16:51:35 -07005128std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005129 return mConflicting;
5130}
5131
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005132SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5133 return mSystemCameraKind;
5134}
5135
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005136bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5137 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5138 != mPhysicalCameras.end();
5139}
5140
Austin Borgered99f642023-06-01 16:51:35 -07005141bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005142 Mutex::Autolock lock(mStatusLock);
5143 auto result = mUnavailablePhysicalIds.insert(physicalId);
5144 return result.second;
5145}
5146
Austin Borgered99f642023-06-01 16:51:35 -07005147bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005148 Mutex::Autolock lock(mStatusLock);
5149 auto count = mUnavailablePhysicalIds.erase(physicalId);
5150 return count > 0;
5151}
5152
Austin Borgered99f642023-06-01 16:51:35 -07005153void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005154 Mutex::Autolock lock(mStatusLock);
5155 mClientPackage = clientPackage;
5156}
5157
Austin Borgered99f642023-06-01 16:51:35 -07005158std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005159 Mutex::Autolock lock(mStatusLock);
5160 return mClientPackage;
5161}
5162
Ruben Brunkcc776712015-02-17 20:18:47 -08005163// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005164// ClientEventListener
5165// ----------------------------------------------------------------------------
5166
5167void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005168 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005169 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005170 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005171 if (basicClient.get() != nullptr) {
5172 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005173 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005174 static_cast<int>(basicClient->getClientUid()));
5175 }
5176}
5177
5178void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005179 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005180 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005181 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005182 if (basicClient.get() != nullptr) {
5183 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005184 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005185 static_cast<int>(basicClient->getClientUid()));
5186 }
5187}
5188
Ruben Brunk99e69712015-05-26 17:25:07 -07005189// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005190// CameraClientManager
5191// ----------------------------------------------------------------------------
5192
Ruben Brunk99e69712015-05-26 17:25:07 -07005193CameraService::CameraClientManager::CameraClientManager() {
5194 setListener(std::make_shared<ClientEventListener>());
5195}
5196
Ruben Brunkcc776712015-02-17 20:18:47 -08005197CameraService::CameraClientManager::~CameraClientManager() {}
5198
5199sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005200 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005201 auto descriptor = get(id);
5202 if (descriptor == nullptr) {
5203 return sp<BasicClient>{nullptr};
5204 }
5205 return descriptor->getValue();
5206}
5207
Austin Borgered99f642023-06-01 16:51:35 -07005208std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005209 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005210 std::ostringstream ret;
5211 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005212 bool hasAny = false;
5213 for (auto& i : all) {
5214 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005215 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005216 int32_t cost = i->getCost();
5217 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005218 int32_t score = i->getPriority().getScore();
5219 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005220 auto conflicting = i->getConflicting();
5221 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005222 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005223 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005224 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005225 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005226 uid_t clientUid = clientSp->getClientUid();
5227 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005228 }
Austin Borgered99f642023-06-01 16:51:35 -07005229 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5230 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005231
Ruben Brunk6267b532015-04-30 17:44:07 -07005232 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005233 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005234 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005235 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005236 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005237 }
5238
Austin Borgered99f642023-06-01 16:51:35 -07005239 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005240 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005241 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005242 }
Austin Borgered99f642023-06-01 16:51:35 -07005243 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005244 }
Austin Borgered99f642023-06-01 16:51:35 -07005245 if (hasAny) ret << "\n";
5246 ret << "]\n";
5247 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005248}
5249
5250CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005251 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5252 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005253 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005254
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005255 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005256 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005257
Austin Borgered99f642023-06-01 16:51:35 -07005258 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005259 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5260 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005261}
5262
5263CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005264 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005265 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005266 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005267 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005268 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5269 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005270}
5271
5272// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005273// InjectionStatusListener
5274// ----------------------------------------------------------------------------
5275
5276void CameraService::InjectionStatusListener::addListener(
5277 const sp<ICameraInjectionCallback>& callback) {
5278 Mutex::Autolock lock(mListenerLock);
5279 if (mCameraInjectionCallback) return;
5280 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5281 if (res == OK) {
5282 mCameraInjectionCallback = callback;
5283 }
5284}
5285
5286void CameraService::InjectionStatusListener::removeListener() {
5287 Mutex::Autolock lock(mListenerLock);
5288 if (mCameraInjectionCallback == nullptr) {
5289 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5290 return;
5291 }
5292 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5293 mCameraInjectionCallback = nullptr;
5294}
5295
5296void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005297 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005298 if (mCameraInjectionCallback == nullptr) {
5299 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5300 return;
5301 }
Cliff Wud3a05312021-04-26 23:07:31 +08005302
5303 switch (err) {
5304 case -ENODEV:
5305 mCameraInjectionCallback->onInjectionError(
5306 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5307 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005308 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005309 break;
5310 case -EBUSY:
5311 mCameraInjectionCallback->onInjectionError(
5312 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5313 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005314 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005315 break;
5316 case DEAD_OBJECT:
5317 mCameraInjectionCallback->onInjectionError(
5318 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5319 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005320 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005321 break;
5322 case INVALID_OPERATION:
5323 mCameraInjectionCallback->onInjectionError(
5324 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5325 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005326 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005327 break;
5328 case UNKNOWN_TRANSACTION:
5329 mCameraInjectionCallback->onInjectionError(
5330 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5331 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005332 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005333 break;
5334 default:
5335 mCameraInjectionCallback->onInjectionError(
5336 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5337 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005338 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005339 }
Cliff Wud8cae102021-03-11 01:37:42 +08005340}
5341
5342void CameraService::InjectionStatusListener::binderDied(
5343 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005344 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5345 auto parent = mParent.promote();
5346 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005347 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5348 if (clientDescriptor != nullptr) {
5349 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5350 baseClientPtr->stopInjection();
5351 }
Cliff Wu3b268182021-07-06 15:44:43 +08005352 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005353 }
5354}
5355
5356// ----------------------------------------------------------------------------
5357// CameraInjectionSession
5358// ----------------------------------------------------------------------------
5359
5360binder::Status CameraService::CameraInjectionSession::stopInjection() {
5361 Mutex::Autolock lock(mInjectionSessionLock);
5362 auto parent = mParent.promote();
5363 if (parent == nullptr) {
5364 ALOGE("CameraInjectionSession: Parent is gone");
5365 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5366 "Camera service encountered error");
5367 }
Cliff Wud3a05312021-04-26 23:07:31 +08005368
5369 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005370 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5371 if (clientDescriptor != nullptr) {
5372 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5373 res = baseClientPtr->stopInjection();
5374 if (res != OK) {
5375 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5376 " ret != NO_ERROR: %d", res);
5377 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5378 "Camera session encountered error");
5379 }
5380 }
Cliff Wu3b268182021-07-06 15:44:43 +08005381 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005382 return binder::Status::ok();
5383}
5384
5385// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005386
5387static const int kDumpLockRetries = 50;
5388static const int kDumpLockSleep = 60000;
5389
5390static bool tryLock(Mutex& mutex)
5391{
5392 bool locked = false;
5393 for (int i = 0; i < kDumpLockRetries; ++i) {
5394 if (mutex.tryLock() == NO_ERROR) {
5395 locked = true;
5396 break;
5397 }
5398 usleep(kDumpLockSleep);
5399 }
5400 return locked;
5401}
5402
Rucha Katakwardf223072021-06-15 10:21:00 -07005403void CameraService::cacheDump() {
5404 if (mMemFd != -1) {
5405 const Vector<String16> args;
5406 ATRACE_CALL();
5407 // Acquiring service lock here will avoid the deadlock since
5408 // cacheDump will not be called during the second disconnect.
5409 Mutex::Autolock lock(mServiceLock);
5410
5411 Mutex::Autolock l(mCameraStatesLock);
5412 // Start collecting the info for open sessions and store it in temp file.
5413 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005414 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005415 auto clientDescriptor = mActiveClientManager.get(cameraId);
5416 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005417 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005418 // Log the current open session info before device is disconnected.
5419 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5420 }
5421 }
5422 }
5423}
5424
Mathias Agopian65ab4712010-07-14 17:59:35 -07005425status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005426 ATRACE_CALL();
5427
Austin Borgered99f642023-06-01 16:51:35 -07005428 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005429 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005430 getCallingPid(),
5431 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005432 return NO_ERROR;
5433 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005434 bool locked = tryLock(mServiceLock);
5435 // failed to lock - CameraService is probably deadlocked
5436 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005437 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005438 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005439
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005440 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005441 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005442
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005443 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005444 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005445
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005446 if (locked) mServiceLock.unlock();
5447 return NO_ERROR;
5448 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005449 dprintf(fd, "\n== Service global info: ==\n\n");
5450 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005451 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005452 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5453 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005454 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5455 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5456 }
Austin Borgered99f642023-06-01 16:51:35 -07005457 std::string activeClientString = mActiveClientManager.toString();
5458 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5459 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005460 if (mStreamUseCaseOverrides.size() > 0) {
5461 dprintf(fd, "Active stream use case overrides:");
5462 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5463 dprintf(fd, " %" PRId64, useCaseOverride);
5464 }
5465 dprintf(fd, "\n");
5466 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005467
5468 dumpEventLog(fd);
5469
5470 bool stateLocked = tryLock(mCameraStatesLock);
5471 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005472 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005473 }
5474
Emilian Peevbd8c5032018-02-14 23:05:40 +00005475 int argSize = args.size();
5476 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005477 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005478 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005479 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005480 }
5481 break;
5482 }
5483 }
5484
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005485 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005486 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005487
Austin Borgered99f642023-06-01 16:51:35 -07005488 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005489
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005490 CameraParameters p = state.second->getShimParams();
5491 if (!p.isEmpty()) {
5492 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5493 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005494 }
5495
5496 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005497 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005498 // log the current open session info
5499 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005500 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005501 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005502 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005503
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005504 }
5505
5506 if (stateLocked) mCameraStatesLock.unlock();
5507
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005508 if (locked) mServiceLock.unlock();
5509
Emilian Peevf53f66e2017-04-11 14:29:43 +01005510 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005511
5512 dprintf(fd, "\n== Vendor tags: ==\n\n");
5513
5514 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5515 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005516 sp<VendorTagDescriptorCache> cache =
5517 VendorTagDescriptorCache::getGlobalVendorTagCache();
5518 if (cache == NULL) {
5519 dprintf(fd, "No vendor tags.\n");
5520 } else {
5521 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5522 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005523 } else {
5524 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5525 }
5526
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005527 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005528 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005529 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005530
5531 // Process dump arguments, if any
5532 int n = args.size();
5533 String16 verboseOption("-v");
5534 String16 unreachableOption("--unreachable");
5535 for (int i = 0; i < n; i++) {
5536 if (args[i] == verboseOption) {
5537 // change logging level
5538 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005539 std::string levelStr = toStdString(args[i+1]);
5540 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005541 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005542 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005543 } else if (args[i] == unreachableOption) {
5544 // Dump memory analysis
5545 // TODO - should limit be an argument parameter?
5546 UnreachableMemoryInfo info;
5547 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5548 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005549 dprintf(fd, "\n== Unable to dump unreachable memory. "
5550 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005551 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005552 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005553 std::string s = info.ToString(/*log_contents*/ true);
5554 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005555 }
5556 }
5557 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005558
5559 bool serviceLocked = tryLock(mServiceLock);
5560
5561 // Dump info from previous open sessions.
5562 // Reposition the offset to beginning of the file before reading
5563
5564 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5565 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5566 ssize_t size_read;
5567 char buf[4096];
5568 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5569 // Read data from file to a small buffer and write it to fd.
5570 write(fd, buf, size_read);
5571 if (size_read == -1) {
5572 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5573 break;
5574 }
5575 }
5576 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5577 } else {
5578 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5579 }
5580
5581 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005582 return NO_ERROR;
5583}
5584
Rucha Katakwardf223072021-06-15 10:21:00 -07005585void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005586 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005587 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005588 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005589 getFormattedCurrentTime().c_str(),
5590 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005591 dprintf(fd, " Client priority score: %d state: %d\n",
5592 clientDescriptor->getPriority().getScore(),
5593 clientDescriptor->getPriority().getState());
5594 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5595
5596 auto client = clientDescriptor->getValue();
5597 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005598 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005599
5600 client->dumpClient(fd, args);
5601}
5602
Austin Borgered99f642023-06-01 16:51:35 -07005603void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005604 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005605 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005606}
5607
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005608void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005609 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005610
5611 Mutex::Autolock l(mLogLock);
5612 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005613 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005614 }
5615
5616 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005617 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005618 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005619 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005620 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005621 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005622}
5623
Austin Borgered99f642023-06-01 16:51:35 -07005624void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005625 Mutex::Autolock lock(mLogLock);
5626 if (!isClientWatchedLocked(client)) { return; }
5627
5628 std::vector<std::string> dumpVector;
5629 client->dumpWatchedEventsToVector(dumpVector);
5630
5631 if (dumpVector.empty()) { return; }
5632
Austin Borgered99f642023-06-01 16:51:35 -07005633 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005634
Austin Borgered99f642023-06-01 16:51:35 -07005635 std::string currentTime = getFormattedCurrentTime();
5636 dumpString << "Cached @ ";
5637 dumpString << currentTime;
5638 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005639
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005640 size_t i = dumpVector.size();
5641
5642 // Store the string in reverse order (latest last)
5643 while (i > 0) {
5644 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005645 dumpString << cameraId;
5646 dumpString << ":";
5647 dumpString << client->getPackageName();
5648 dumpString << " ";
5649 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005650 }
5651
Austin Borgered99f642023-06-01 16:51:35 -07005652 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005653}
5654
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005655void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005656 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005657 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5658 if (mTorchClientMap[i] == who) {
5659 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005660 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005661 status_t res = mFlashlight->setTorchMode(cameraId, false);
5662 if (res) {
5663 ALOGE("%s: torch client died but couldn't turn off torch: "
5664 "%s (%d)", __FUNCTION__, strerror(-res), res);
5665 return;
5666 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005667 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005668 break;
5669 }
5670 }
5671}
5672
Ruben Brunkcc776712015-02-17 20:18:47 -08005673/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005674
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005675 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005676 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5677 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005678 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005679 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005680 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005681
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005682 // check torch client
5683 handleTorchClientBinderDied(who);
5684
5685 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005686 if(!evictClientIdByRemote(who)) {
5687 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005688 return;
5689 }
5690
Ruben Brunkcc776712015-02-17 20:18:47 -08005691 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5692 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005693}
5694
Austin Borgered99f642023-06-01 16:51:35 -07005695void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005696 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005697}
5698
Austin Borgered99f642023-06-01 16:51:35 -07005699void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005700 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005701 // Do not lock mServiceLock here or can get into a deadlock from
5702 // connect() -> disconnect -> updateStatus
5703
5704 auto state = getCameraState(cameraId);
5705
5706 if (state == nullptr) {
5707 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005708 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005709 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005710 }
5711
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005712 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5713 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5714 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005715 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005716 return;
5717 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005718
Biswarup Pal37a75182024-01-16 15:53:35 +00005719 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5720 CameraMetadata cameraInfo;
5721 status_t res = mCameraProviderManager->getCameraCharacteristics(
5722 cameraId, false, &cameraInfo, false);
5723 if (res != OK) {
5724 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5725 __FUNCTION__, cameraId.c_str());
5726 } else {
5727 int32_t deviceId = getDeviceId(cameraInfo);
5728 if (deviceId != kDefaultDeviceId) {
5729 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5730 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5731 static_cast<camera_metadata_enum_android_lens_facing_t>(
5732 lensFacingEntry.data.u8[0]);
5733 std::string mappedCameraId;
5734 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5735 mappedCameraId = kVirtualDeviceBackCameraId;
5736 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5737 mappedCameraId = kVirtualDeviceFrontCameraId;
5738 } else {
5739 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5740 __func__);
5741 }
5742 if (!mappedCameraId.empty()) {
5743 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5744 }
5745 }
5746 }
5747 }
5748
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005749 // Collect the logical cameras without holding mStatusLock in updateStatus
5750 // as that can lead to a deadlock(b/162192331).
5751 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005752 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005753 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005754 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005755 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005756 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005757 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5758 auto [deviceId, mappedCameraId] =
5759 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005760
Biswarup Pal37a75182024-01-16 15:53:35 +00005761 if (status != StatusInternal::ENUMERATING) {
5762 // Update torch status if it has a flash unit.
5763 Mutex::Autolock al(mTorchStatusMutex);
5764 TorchModeStatus torchStatus;
5765 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5766 NAME_NOT_FOUND) {
5767 TorchModeStatus newTorchStatus =
5768 status == StatusInternal::PRESENT ?
5769 TorchModeStatus::AVAILABLE_OFF :
5770 TorchModeStatus::NOT_AVAILABLE;
5771 if (torchStatus != newTorchStatus) {
5772 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5773 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005774 }
5775 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005776
Biswarup Pal37a75182024-01-16 15:53:35 +00005777 Mutex::Autolock lock(mStatusListenerLock);
5778 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5779 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005780
Biswarup Pal37a75182024-01-16 15:53:35 +00005781 for (auto& listener : mListenerList) {
5782 bool isVendorListener = listener->isVendorListener();
5783 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5784 listener->getListenerPid(), listener->getListenerUid())) {
5785 ALOGV("Skipping discovery callback for system-only camera device %s",
5786 cameraId.c_str());
5787 continue;
5788 }
5789
5790 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5791 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005792 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005793 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005794 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5795 ret.exceptionCode());
Biswarup Pal37a75182024-01-16 15:53:35 +00005796
5797 // Only cameras of the default device can be remapped to a different camera
5798 // (using remapCameraIds method), so do the following only if the camera is
5799 // associated with the default device.
5800 if (deviceId == kDefaultDeviceId) {
5801 // For the default device, also trigger the callbacks for cameras that were
5802 // remapped to the current cameraId for the specific package that this
5803 // listener belongs to.
5804 std::vector<std::string> remappedCameraIds =
5805 findOriginalIdsForRemappedCameraId(cameraId,
5806 listener->getListenerUid());
5807 for (auto &remappedCameraId: remappedCameraIds) {
5808 ret = listener->getListener()->onStatusChanged(
5809 mapToInterface(status), remappedCameraId, kDefaultDeviceId);
5810 listener->handleBinderStatus(ret,
5811 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
5812 __FUNCTION__, listener->getListenerUid(),
5813 listener->getListenerPid(), ret.exceptionCode());
5814 }
5815 }
malikakash82ed4352023-07-21 22:44:34 +00005816 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005817 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005818}
5819
Austin Borgered99f642023-06-01 16:51:35 -07005820void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5821 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005822 auto state = getCameraState(cameraId);
5823 if (state == nullptr) {
5824 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005825 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005826 return;
5827 }
5828 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005829 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005830 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005831 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005832 }
5833
Biswarup Pal37a75182024-01-16 15:53:35 +00005834 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5835 auto [deviceId, mappedCameraId] =
5836 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5837
Shuzhen Wang695044d2020-03-06 09:02:23 -08005838 Mutex::Autolock lock(mStatusListenerLock);
5839
5840 for (const auto& it : mListenerList) {
5841 if (!it->isOpenCloseCallbackAllowed()) {
5842 continue;
5843 }
5844
5845 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005846 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005847 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5848 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005849 } else {
Biswarup Pal37a75182024-01-16 15:53:35 +00005850 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005851 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005852
5853 it->handleBinderStatus(ret,
5854 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5855 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005856 }
5857}
5858
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005859template<class Func>
5860void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005861 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005862 std::initializer_list<StatusInternal> rejectSourceStates,
5863 Func onStatusUpdatedLocked) {
5864 Mutex::Autolock lock(mStatusLock);
5865 StatusInternal oldStatus = mStatus;
5866 mStatus = status;
5867
5868 if (oldStatus == status) {
5869 return;
5870 }
5871
5872 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005873 cameraId.c_str(), oldStatus, status);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005874
5875 if (oldStatus == StatusInternal::NOT_PRESENT &&
5876 (status != StatusInternal::PRESENT &&
5877 status != StatusInternal::ENUMERATING)) {
5878
5879 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5880 __FUNCTION__);
5881 mStatus = oldStatus;
5882 return;
5883 }
5884
5885 /**
5886 * Sometimes we want to conditionally do a transition.
5887 * For example if a client disconnects, we want to go to PRESENT
5888 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5889 */
5890 for (auto& rejectStatus : rejectSourceStates) {
5891 if (oldStatus == rejectStatus) {
5892 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005893 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005894 mStatus = oldStatus;
5895 return;
5896 }
5897 }
5898
5899 onStatusUpdatedLocked(cameraId, status);
5900}
5901
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005902status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005903 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005904 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005905 if (!status) {
5906 return BAD_VALUE;
5907 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005908 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5909 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005910 // invalid camera ID or the camera doesn't have a flash unit
5911 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005912 }
5913
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005914 *status = mTorchStatusMap.valueAt(index);
5915 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005916}
5917
Austin Borgered99f642023-06-01 16:51:35 -07005918status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005919 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005920 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5921 if (index == NAME_NOT_FOUND) {
5922 return BAD_VALUE;
5923 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005924 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005925
5926 return OK;
5927}
5928
Austin Borgered99f642023-06-01 16:51:35 -07005929std::list<std::string> CameraService::getLogicalCameras(
5930 const std::string& physicalCameraId) {
5931 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005932 Mutex::Autolock lock(mCameraStatesLock);
5933 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005934 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5935 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005936 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005937 }
5938 return retList;
5939}
5940
5941void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005942 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00005943 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005944 // mStatusListenerLock is expected to be locked
5945 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005946 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005947 // Note: we check only the deviceKind of the physical camera id
5948 // since, logical camera ids and their physical camera ids are
5949 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005950 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5951 listener->getListenerPid(), listener->getListenerUid())) {
5952 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005953 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005954 continue;
5955 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005956 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00005957 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005958 listener->handleBinderStatus(ret,
5959 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5960 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5961 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005962 }
5963 }
5964}
5965
Svet Ganova453d0d2018-01-11 15:37:58 -08005966void CameraService::blockClientsForUid(uid_t uid) {
5967 const auto clients = mActiveClientManager.getAll();
5968 for (auto& current : clients) {
5969 if (current != nullptr) {
5970 const auto basicClient = current->getValue();
5971 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5972 basicClient->block();
5973 }
5974 }
5975 }
5976}
5977
Michael Grooverd1d435a2018-12-18 17:39:42 -08005978void CameraService::blockAllClients() {
5979 const auto clients = mActiveClientManager.getAll();
5980 for (auto& current : clients) {
5981 if (current != nullptr) {
5982 const auto basicClient = current->getValue();
5983 if (basicClient.get() != nullptr) {
5984 basicClient->block();
5985 }
5986 }
5987 }
5988}
5989
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005990void CameraService::blockPrivacyEnabledClients() {
5991 const auto clients = mActiveClientManager.getAll();
5992 for (auto& current : clients) {
5993 if (current != nullptr) {
5994 const auto basicClient = current->getValue();
5995 if (basicClient.get() != nullptr) {
5996 std::string pkgName = basicClient->getPackageName();
5997 bool cameraPrivacyEnabled =
5998 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
5999 if (cameraPrivacyEnabled) {
6000 basicClient->block();
6001 }
6002 }
6003 }
6004 }
6005}
6006
Svet Ganova453d0d2018-01-11 15:37:58 -08006007// NOTE: This is a remote API - make sure all args are validated
6008status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006009 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006010 return PERMISSION_DENIED;
6011 }
6012 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
6013 return BAD_VALUE;
6014 }
Austin Borgered99f642023-06-01 16:51:35 -07006015 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006016 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006017 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006018 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006019 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006020 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07006021 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006022 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07006023 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006024 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07006025 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006026 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07006027 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006028 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07006029 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006030 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07006031 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006032 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07006033 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006034 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07006035 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006036 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07006037 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006038 handleClearStreamUseCaseOverrides();
6039 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07006040 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006041 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07006042 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006043 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07006044 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00006045 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07006046 } else if (args.size() >= 4 && args[0] == toString16("remap-camera-id")) {
malikakash82ed4352023-07-21 22:44:34 +00006047 return handleCameraIdRemapping(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006048 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006049 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006050 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08006051 }
6052 printHelp(err);
6053 return BAD_VALUE;
6054}
6055
malikakash82ed4352023-07-21 22:44:34 +00006056status_t CameraService::handleCameraIdRemapping(const Vector<String16>& args, int err) {
6057 uid_t uid = IPCThreadState::self()->getCallingUid();
6058 if (uid != AID_ROOT) {
6059 dprintf(err, "Must be adb root\n");
6060 return PERMISSION_DENIED;
6061 }
6062 if (args.size() != 4) {
6063 dprintf(err, "Expected format: remap-camera-id <PACKAGE> <Id0> <Id1>\n");
6064 return BAD_VALUE;
6065 }
Austin Borgered99f642023-06-01 16:51:35 -07006066 std::string packageName = toStdString(args[1]);
6067 std::string cameraIdToReplace = toStdString(args[2]);
6068 std::string cameraIdNew = toStdString(args[3]);
malikakash82ed4352023-07-21 22:44:34 +00006069 remapCameraIds({{packageName, {{cameraIdToReplace, cameraIdNew}}}});
6070 return OK;
6071}
6072
Svet Ganova453d0d2018-01-11 15:37:58 -08006073status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006074 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006075
Svet Ganova453d0d2018-01-11 15:37:58 -08006076 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07006077 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006078 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07006079 } else if ((args[2] != toString16("idle"))) {
6080 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08006081 return BAD_VALUE;
6082 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006083
6084 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006085 if (args.size() >= 5 && args[3] == toString16("--user")) {
6086 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006087 }
6088
6089 uid_t uid;
6090 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
6091 return BAD_VALUE;
6092 }
6093
6094 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08006095 return NO_ERROR;
6096}
6097
6098status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006099 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006100
6101 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006102 if (args.size() >= 4 && args[2] == toString16("--user")) {
6103 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006104 }
6105
6106 uid_t uid;
6107 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006108 return BAD_VALUE;
6109 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006110
6111 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08006112 return NO_ERROR;
6113}
6114
6115status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006116 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006117
6118 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006119 if (args.size() >= 4 && args[2] == toString16("--user")) {
6120 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006121 }
6122
6123 uid_t uid;
6124 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006125 return BAD_VALUE;
6126 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006127
6128 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006129 return dprintf(out, "active\n");
6130 } else {
6131 return dprintf(out, "idle\n");
6132 }
6133}
6134
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006135status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006136 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006137 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
6138 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
6139 Mutex::Autolock lock(mServiceLock);
6140
6141 mOverrideRotateAndCropMode = rotateValue;
6142
6143 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6144
6145 const auto clients = mActiveClientManager.getAll();
6146 for (auto& current : clients) {
6147 if (current != nullptr) {
6148 const auto basicClient = current->getValue();
6149 if (basicClient.get() != nullptr) {
6150 basicClient->setRotateAndCropOverride(rotateValue);
6151 }
6152 }
6153 }
6154
6155 return OK;
6156}
6157
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006158status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6159 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006160 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006161 if ((*end != '\0') ||
6162 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6163 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6164 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6165 return BAD_VALUE;
6166 }
6167
6168 Mutex::Autolock lock(mServiceLock);
6169 mOverrideAutoframingMode = autoframingValue;
6170
6171 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6172
6173 const auto clients = mActiveClientManager.getAll();
6174 for (auto& current : clients) {
6175 if (current != nullptr) {
6176 const auto basicClient = current->getValue();
6177 if (basicClient.get() != nullptr) {
6178 basicClient->setAutoframingOverride(autoframingValue);
6179 }
6180 }
6181 }
6182
6183 return OK;
6184}
6185
Ravneetaeb20dc2022-03-30 05:33:03 +00006186status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006187 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006188
6189 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6190
6191 Mutex::Autolock lock(mServiceLock);
6192
6193 mCameraServiceWatchdogEnabled = enableWatchdog;
6194
6195 const auto clients = mActiveClientManager.getAll();
6196 for (auto& current : clients) {
6197 if (current != nullptr) {
6198 const auto basicClient = current->getValue();
6199 if (basicClient.get() != nullptr) {
6200 basicClient->setCameraServiceWatchdog(enableWatchdog);
6201 }
6202 }
6203 }
6204
6205 return OK;
6206}
6207
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006208status_t CameraService::handleGetRotateAndCrop(int out) {
6209 Mutex::Autolock lock(mServiceLock);
6210
6211 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6212}
6213
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006214status_t CameraService::handleGetAutoframing(int out) {
6215 Mutex::Autolock lock(mServiceLock);
6216
6217 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6218}
6219
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006220status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6221 char *endPtr;
6222 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006223 std::string maskString = toStdString(args[1]);
6224 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006225
6226 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006227 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006228 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6229
6230 Mutex::Autolock lock(mServiceLock);
6231
6232 mImageDumpMask = maskValue;
6233
6234 return OK;
6235}
6236
6237status_t CameraService::handleGetImageDumpMask(int out) {
6238 Mutex::Autolock lock(mServiceLock);
6239
6240 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6241}
6242
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006243status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006244 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006245 if (errno != 0) return BAD_VALUE;
6246
6247 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6248 Mutex::Autolock lock(mServiceLock);
6249
6250 mOverrideCameraMuteMode = (muteValue == 1);
6251
6252 const auto clients = mActiveClientManager.getAll();
6253 for (auto& current : clients) {
6254 if (current != nullptr) {
6255 const auto basicClient = current->getValue();
6256 if (basicClient.get() != nullptr) {
6257 if (basicClient->supportsCameraMute()) {
6258 basicClient->setCameraMute(mOverrideCameraMuteMode);
6259 }
6260 }
6261 }
6262 }
6263
6264 return OK;
6265}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006266
Shuzhen Wang16610a62022-12-15 22:38:07 -08006267status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6268 std::vector<int64_t> useCasesOverride;
6269 for (size_t i = 1; i < args.size(); i++) {
6270 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006271 std::string arg = toStdString(args[i]);
6272 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006273 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006274 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006275 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006276 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006277 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006278 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006279 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006280 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006281 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006282 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006283 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006284 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006285 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6286 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006287 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006288 return BAD_VALUE;
6289 }
6290 useCasesOverride.push_back(useCase);
6291 }
6292
6293 Mutex::Autolock lock(mServiceLock);
6294 mStreamUseCaseOverrides = std::move(useCasesOverride);
6295
6296 return OK;
6297}
6298
6299void CameraService::handleClearStreamUseCaseOverrides() {
6300 Mutex::Autolock lock(mServiceLock);
6301 mStreamUseCaseOverrides.clear();
6302}
6303
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006304status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6305 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006306 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006307 if ((*end != '\0') ||
6308 (zoomOverrideValue != -1 &&
6309 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6310 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6311 return BAD_VALUE;
6312 }
6313
6314 Mutex::Autolock lock(mServiceLock);
6315 mZoomOverrideValue = zoomOverrideValue;
6316
6317 const auto clients = mActiveClientManager.getAll();
6318 for (auto& current : clients) {
6319 if (current != nullptr) {
6320 const auto basicClient = current->getValue();
6321 if (basicClient.get() != nullptr) {
6322 if (basicClient->supportsZoomOverride()) {
6323 basicClient->setZoomOverride(mZoomOverrideValue);
6324 }
6325 }
6326 }
6327 }
6328
6329 return OK;
6330}
6331
Avichal Rakesh84147132021-11-11 17:47:11 -08006332status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006333 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006334 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006335 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006336 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006337 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006338 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006339 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006340 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006341 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006342 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006343 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006344 dprintf(outFd, "Camera service watch commands:\n"
6345 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6346 " starts watching the provided tags for clients with provided package\n"
6347 " recognizes tag shorthands like '3a'\n"
6348 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006349 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006350 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006351 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006352 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006353 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006354 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006355 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006356}
6357
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006358status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6359 Mutex::Autolock lock(mLogLock);
6360 size_t tagsIdx; // index of '-m'
6361 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006362 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006363 if (tagsIdx < args.size() - 1) {
6364 tags = args[tagsIdx + 1];
6365 } else {
6366 dprintf(outFd, "No tags provided.\n");
6367 return BAD_VALUE;
6368 }
6369
6370 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006371 // watch all clients if no clients are provided
6372 String16 clients = toString16(kWatchAllClientsFlag);
6373 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006374 clientsIdx++);
6375 if (clientsIdx < args.size() - 1) {
6376 clients = args[clientsIdx + 1];
6377 }
Austin Borgered99f642023-06-01 16:51:35 -07006378 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006379
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006380 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006381 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006382
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006383 bool serviceLock = tryLock(mServiceLock);
6384 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006385 auto cameraClients = mActiveClientManager.getAll();
6386 for (const auto &clientDescriptor: cameraClients) {
6387 if (clientDescriptor == nullptr) { continue; }
6388 sp<BasicClient> client = clientDescriptor->getValue();
6389 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006390
6391 if (isClientWatchedLocked(client.get())) {
6392 client->startWatchingTags(mMonitorTags, outFd);
6393 numWatchedClients++;
6394 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006395 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006396 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6397
6398 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006399 return OK;
6400}
6401
6402status_t CameraService::stopWatchingTags(int outFd) {
6403 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006404 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006405 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006406
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006407 mWatchedClientPackages.clear();
6408 mWatchedClientsDumpCache.clear();
6409
6410 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006411 auto cameraClients = mActiveClientManager.getAll();
6412 for (const auto &clientDescriptor : cameraClients) {
6413 if (clientDescriptor == nullptr) { continue; }
6414 sp<BasicClient> client = clientDescriptor->getValue();
6415 if (client.get() == nullptr) { continue; }
6416 client->stopWatchingTags(outFd);
6417 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006418 dprintf(outFd, "Stopped watching all clients.\n");
6419 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006420 return OK;
6421}
6422
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006423status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6424 Mutex::Autolock lock(mLogLock);
6425 size_t clearedSize = mWatchedClientsDumpCache.size();
6426 mWatchedClientsDumpCache.clear();
6427 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6428 return OK;
6429}
6430
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006431status_t CameraService::printWatchedTags(int outFd) {
6432 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006433 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006434
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006435 bool printedSomething = false; // tracks if any monitoring information was printed
6436 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006437
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006438 bool serviceLock = tryLock(mServiceLock);
6439 // get all watched clients that are currently connected
6440 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6441 if (clientDescriptor == nullptr) { continue; }
6442
6443 sp<BasicClient> client = clientDescriptor->getValue();
6444 if (client.get() == nullptr) { continue; }
6445 if (!isClientWatchedLocked(client.get())) { continue; }
6446
6447 std::vector<std::string> dumpVector;
6448 client->dumpWatchedEventsToVector(dumpVector);
6449
6450 size_t printIdx = dumpVector.size();
6451 if (printIdx == 0) {
6452 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006453 }
6454
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006455 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006456 const std::string &cameraId = clientDescriptor->getKey();
6457 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006458 while(printIdx > 0) {
6459 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006460 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006461 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006462 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006463 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006464 printedSomething = true;
6465
6466 connectedMonitoredClients.emplace(client->getPackageName());
6467 }
6468 if (serviceLock) { mServiceLock.unlock(); }
6469
6470 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6471 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006472 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006473 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6474 continue;
6475 }
6476
Austin Borgered99f642023-06-01 16:51:35 -07006477 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006478 dprintf(outFd, "%s\n", kv.second.c_str());
6479 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006480 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006481
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006482 if (!printedSomething) {
6483 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006484 }
6485
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006486 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006487}
6488
Avichal Rakesh84147132021-11-11 17:47:11 -08006489// Print all events in vector `events' that came after lastPrintedEvent
6490void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006491 const std::string &cameraId,
6492 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006493 const std::vector<std::string> &events,
6494 const std::string &lastPrintedEvent) {
6495 if (events.empty()) { return; }
6496
6497 // index of lastPrintedEvent in events.
6498 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6499 size_t lastPrintedIdx;
6500 for (lastPrintedIdx = 0;
6501 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6502 lastPrintedIdx++);
6503
6504 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6505
Avichal Rakesh84147132021-11-11 17:47:11 -08006506 // print events in chronological order (latest event last)
6507 size_t idxToPrint = lastPrintedIdx;
6508 do {
6509 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006510 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6511 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006512 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006513}
6514
6515// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6516// command should be interrupted if the user presses the return key, or if user loses any way to
6517// signal interrupt.
6518// If timeoutMs == 0, this function will always return false
6519bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6520 struct timeval startTime;
6521 int startTimeError = gettimeofday(&startTime, nullptr);
6522 if (startTimeError) {
6523 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6524 return true;
6525 }
6526
6527 const nfds_t numFds = 1;
6528 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6529
6530 struct timeval currTime;
6531 char buffer[2];
6532 while(true) {
6533 int currTimeError = gettimeofday(&currTime, nullptr);
6534 if (currTimeError) {
6535 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6536 return true;
6537 }
6538
6539 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6540 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6541 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6542
6543 if (remainingTimeMs <= 0) {
6544 // No user interrupt within timeoutMs, don't interrupt watch command
6545 return false;
6546 }
6547
6548 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6549 if (numFdsUpdated < 0) {
6550 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6551 return true;
6552 }
6553
6554 if (numFdsUpdated == 0) {
6555 // No user input within timeoutMs, don't interrupt watch command
6556 return false;
6557 }
6558
6559 if (!(pollFd.revents & POLLIN)) {
6560 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6561 return true;
6562 }
6563
6564 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6565 if (sizeRead < 0) {
6566 dprintf(outFd, "Error reading user input. Exiting.\n");
6567 return true;
6568 }
6569
6570 if (sizeRead == 0) {
6571 // Reached end of input fd (can happen if input is piped)
6572 // User has no way to signal an interrupt, so interrupt here
6573 return true;
6574 }
6575
6576 if (buffer[0] == '\n') {
6577 // User pressed return, interrupt watch command.
6578 return true;
6579 }
6580 }
6581}
6582
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006583status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6584 int inFd, int outFd) {
6585 // Figure out refresh interval, if present in args
6586 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006587 if (args.size() > 2) {
6588 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006589 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006590 intervalIdx++);
6591
6592 size_t intervalValIdx = intervalIdx + 1;
6593 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006594 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006595 if (errno) { return BAD_VALUE; }
6596 }
6597 }
6598
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006599 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6600 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006601
Avichal Rakesh84147132021-11-11 17:47:11 -08006602 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006603 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006604
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006605 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006606 bool serviceLock = tryLock(mServiceLock);
6607 auto cameraClients = mActiveClientManager.getAll();
6608 if (serviceLock) { mServiceLock.unlock(); }
6609
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006610 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006611 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006612 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006613
6614 sp<BasicClient> client = clientDescriptor->getValue();
6615 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006616 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006617
Austin Borgered99f642023-06-01 16:51:35 -07006618 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006619 // This also initializes the map entries with an empty string
6620 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6621
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006622 std::vector<std::string> latestEvents;
6623 client->dumpWatchedEventsToVector(latestEvents);
6624
6625 if (!latestEvents.empty()) {
6626 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006627 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006628 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006629 latestEvents,
6630 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006631 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006632 }
6633 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006634 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006635 break;
6636 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006637 }
6638 return OK;
6639}
6640
Austin Borgered99f642023-06-01 16:51:35 -07006641void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006642 mWatchedClientPackages.clear();
6643
Austin Borgered99f642023-06-01 16:51:35 -07006644 std::istringstream iss(clients);
6645 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006646
Austin Borgered99f642023-06-01 16:51:35 -07006647 while (std::getline(iss, nextClient, ',')) {
6648 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006649 // Don't need to track any other package if 'all' is present
6650 mWatchedClientPackages.clear();
6651 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6652 break;
6653 }
6654
6655 // track package names
6656 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006657 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006658}
6659
Svet Ganova453d0d2018-01-11 15:37:58 -08006660status_t CameraService::printHelp(int out) {
6661 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006662 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6663 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6664 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006665 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6666 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6667 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006668 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6669 " Valid values 0=false, 1=true, 2=auto\n"
6670 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006671 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6672 " Valid values 0=OFF, 1=ON for JPEG\n"
6673 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006674 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006675 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6676 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6677 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6678 " on. In case the number of usecases is smaller than the number of streams, the\n"
6679 " last use case is assigned to all the remaining streams. In case of multiple\n"
6680 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6681 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6682 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6683 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006684 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6685 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006686 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6687 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006688 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
malikakash73125c62023-07-21 22:44:34 +00006689 " remap-camera-id <PACKAGE> <Id0> <Id1> remaps camera ids. Must use adb root\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006690 " help print this message\n");
6691}
6692
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006693bool CameraService::isClientWatched(const BasicClient *client) {
6694 Mutex::Autolock lock(mLogLock);
6695 return isClientWatchedLocked(client);
6696}
6697
6698bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6699 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6700 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6701}
6702
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006703int32_t CameraService::updateAudioRestriction() {
6704 Mutex::Autolock lock(mServiceLock);
6705 return updateAudioRestrictionLocked();
6706}
6707
6708int32_t CameraService::updateAudioRestrictionLocked() {
6709 int32_t mode = 0;
6710 // iterate through all active client
6711 for (const auto& i : mActiveClientManager.getAll()) {
6712 const auto clientSp = i->getValue();
6713 mode |= clientSp->getAudioRestriction();
6714 }
6715
6716 bool modeChanged = (mAudioRestriction != mode);
6717 mAudioRestriction = mode;
6718 if (modeChanged) {
6719 mAppOps.setCameraAudioRestriction(mode);
6720 }
6721 return mode;
6722}
6723
Austin Borgered99f642023-06-01 16:51:35 -07006724status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006725 sp<BasicClient> clientSp) {
6726 std::unique_ptr<AutoConditionLock> lock =
6727 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6728 status_t res = NO_ERROR;
6729 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006730 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006731 mInjectionStatusListener->notifyInjectionError(
6732 externalCamId, UNKNOWN_TRANSACTION);
6733 clientSp->notifyError(
6734 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6735 CaptureResultExtras());
6736
6737 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6738 // other clients from connecting in mServiceLockWrapper if held
6739 mServiceLock.unlock();
6740
6741 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006742 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006743 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006744 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006745
6746 // Reacquire mServiceLock
6747 mServiceLock.lock();
6748 }
6749
6750 return res;
6751}
6752
Cliff Wud3a05312021-04-26 23:07:31 +08006753void CameraService::clearInjectionParameters() {
6754 {
6755 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006756 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006757 mInjectionInternalCamId = "";
6758 }
6759 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006760 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006761}
6762
Biswarup Pal37a75182024-01-16 15:53:35 +00006763} // namespace android