blob: 95355c9282dc59525db23455240e686acbc666ed [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(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700918 const std::string& unresolvedCameraId, int targetSdkVersion,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700919 const SessionConfiguration& sessionConfiguration,
Biswarup Pal37a75182024-01-16 15:53:35 +0000920 int32_t deviceId, int32_t devicePolicy,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700921 /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700922 ATRACE_CALL();
923
924 if (!flags::feature_combination_query()) {
925 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
926 "Camera subsystem doesn't support this method!");
927 }
928 if (!mInitialized) {
929 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
930 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
931 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
932 }
933
Biswarup Pal37a75182024-01-16 15:53:35 +0000934 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
935 devicePolicy, getCallingUid());
936 if (!cameraIdOptional.has_value()) {
937 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
938 unresolvedCameraId.c_str(), deviceId);
939 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
940 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
941 }
942 std::string cameraId = cameraIdOptional.value();
943
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700944 if (supported == nullptr) {
945 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
946 unresolvedCameraId.c_str());
947 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
948 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
949 }
950
951 if (shouldRejectSystemCameraConnection(cameraId)) {
952 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
953 "session configuration with parameters support for system only device %s: ",
954 cameraId.c_str());
955 }
956
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700957 bool overrideForPerfClass = flags::calculate_perf_override_during_session_support() &&
958 SessionConfigurationUtils::targetPerfClassPrimaryCamera(
959 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
960
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700961 return isSessionConfigurationWithParametersSupportedUnsafe(cameraId, sessionConfiguration,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700962 overrideForPerfClass, supported);
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700963}
964
965Status CameraService::isSessionConfigurationWithParametersSupportedUnsafe(
966 const std::string& cameraId, const SessionConfiguration& sessionConfiguration,
967 bool overrideForPerfClass, /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700968 *supported = false;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700969 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(
970 cameraId, sessionConfiguration, overrideForPerfClass,
971 /*checkSessionParams=*/true, supported);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700972 binder::Status res;
973 switch (ret) {
974 case OK:
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700975 // Expected. Do Nothing.
976 return Status::ok();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700977 case INVALID_OPERATION: {
978 std::string msg = fmt::sprintf(
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700979 "Camera %s: Session configuration with parameters supported query not "
980 "supported!",
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700981 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700982 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
983 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
984 *supported = false;
985 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700986 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700987 break;
988 case NAME_NOT_FOUND: {
989 std::string msg = fmt::sprintf("Camera %s: Unknown camera ID.", cameraId.c_str());
990 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
991 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
992 *supported = false;
993 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
994 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700995 break;
996 default: {
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700997 std::string msg = fmt::sprintf(
998 "Unable to retrieve session configuration support for camera "
999 "device %s: Error: %s (%d)",
1000 cameraId.c_str(), strerror(-ret), ret);
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001001 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001002 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1003 *supported = false;
1004 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001005 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001006 break;
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001007 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001008}
1009
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001010Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +00001011 int targetSdkVersion, bool overrideToPortrait,
1012 const SessionConfiguration& sessionConfiguration, int32_t deviceId, int32_t devicePolicy,
1013 /*out*/ CameraMetadata* outMetadata) {
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001014 ATRACE_CALL();
1015
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001016 if (outMetadata == nullptr) {
1017 std::string msg =
1018 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
1019 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1020 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1021 }
1022
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001023 if (!mInitialized) {
1024 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1025 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
1026 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
1027 }
1028
Biswarup Pal37a75182024-01-16 15:53:35 +00001029 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001030 devicePolicy, getCallingUid());
Biswarup Pal37a75182024-01-16 15:53:35 +00001031 if (!cameraIdOptional.has_value()) {
1032 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001033 unresolvedCameraId.c_str(), deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001034 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1035 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1036 }
1037 std::string cameraId = cameraIdOptional.value();
1038
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001039 if (shouldRejectSystemCameraConnection(cameraId)) {
1040 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1041 "Unable to retrieve camera"
1042 "characteristics for system only device %s: ",
1043 cameraId.c_str());
1044 }
1045
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001046 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1047 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001048 if (flags::check_session_support_before_session_char()) {
1049 bool sessionConfigSupported;
1050 Status res = isSessionConfigurationWithParametersSupportedUnsafe(
1051 cameraId, sessionConfiguration, overrideForPerfClass, &sessionConfigSupported);
1052 if (!res.isOk()) {
1053 // isSessionConfigurationWithParametersSupportedUnsafe should log what went wrong and
1054 // report the correct Status to send to the client. Simply forward the error to
1055 // the client.
1056 outMetadata->clear();
1057 return res;
1058 }
1059 if (!sessionConfigSupported) {
1060 std::string msg = fmt::sprintf(
1061 "Session configuration not supported for camera device %s.", cameraId.c_str());
1062 outMetadata->clear();
1063 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1064 }
1065 }
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001066
1067 status_t ret = mCameraProviderManager->getSessionCharacteristics(
1068 cameraId, sessionConfiguration, overrideForPerfClass, overrideToPortrait, outMetadata);
1069
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001070 switch (ret) {
1071 case OK:
1072 // Expected, no handling needed.
1073 break;
1074 case INVALID_OPERATION: {
1075 std::string msg = fmt::sprintf(
1076 "Camera %s: Session characteristics query not supported!",
1077 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001078 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001079 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1080 outMetadata->clear();
1081 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1082 }
1083 break;
1084 case NAME_NOT_FOUND: {
1085 std::string msg = fmt::sprintf(
1086 "Camera %s: Unknown camera ID.",
1087 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001088 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001089 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1090 outMetadata->clear();
1091 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001092 }
1093 break;
1094 default: {
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001095 std::string msg = fmt::sprintf(
1096 "Unable to retrieve session characteristics for camera device %s: "
1097 "Error: %s (%d)",
1098 cameraId.c_str(), strerror(-ret), ret);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001099 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001100 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1101 outMetadata->clear();
1102 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001103 }
1104 }
1105
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001106 return filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
1107}
1108
1109Status CameraService::filterSensitiveMetadataIfNeeded(
1110 const std::string& cameraId, CameraMetadata* metadata) {
1111 int callingPid = getCallingPid();
1112 int callingUid = getCallingUid();
1113
1114 if (callingPid == getpid()) {
1115 // Caller is cameraserver; no need to remove keys
1116 return Status::ok();
1117 }
1118
1119 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1120 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1121 ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
1122 metadata->clear();
1123 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1124 "Unable to retrieve camera kind for device %s", cameraId.c_str());
1125 }
1126 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
1127 // Attempting to query system only camera without system camera permission would have
1128 // failed the shouldRejectSystemCameraConnection in the caller. So if we get here
1129 // for a system only camera, then the caller has the required permission.
1130 // No need to remove keys
1131 return Status::ok();
1132 }
1133
1134 std::vector<int32_t> tagsRemoved;
1135 bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid);
1136 if (hasCameraPermission) {
1137 // Caller has camera permission; no need to remove keys
1138 return Status::ok();
1139 }
1140
1141 status_t ret = metadata->removePermissionEntries(
1142 mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1143 if (ret != OK) {
1144 metadata->clear();
1145 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1146 "Failed to remove camera characteristics needing camera permission "
1147 "for device %s:%s (%d)",
1148 cameraId.c_str(), strerror(-ret), ret);
1149 }
1150
1151 if (!tagsRemoved.empty()) {
1152 ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1153 tagsRemoved.data(), tagsRemoved.size());
1154 if (ret != OK) {
1155 metadata->clear();
1156 return STATUS_ERROR_FMT(
1157 ERROR_INVALID_OPERATION,
1158 "Failed to insert camera keys needing permission for device %s: %s (%d)",
1159 cameraId.c_str(), strerror(-ret), ret);
1160 }
1161 }
1162 return Status::ok();
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001163}
1164
malikakash82ed4352023-07-21 22:44:34 +00001165Status CameraService::parseCameraIdRemapping(
1166 const hardware::CameraIdRemapping& cameraIdRemapping,
malikakash214f6e62023-08-10 23:50:56 +00001167 /* out */ TCameraIdRemapping* cameraIdRemappingMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001168 std::string packageName;
1169 std::string cameraIdToReplace, updatedCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001170 for (const auto& packageIdRemapping: cameraIdRemapping.packageIdRemappings) {
malikakash82ed4352023-07-21 22:44:34 +00001171 packageName = packageIdRemapping.packageName;
malikakash0894f5b2023-08-10 22:46:47 +00001172 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001173 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1174 "CameraIdRemapping: Package name cannot be empty");
1175 }
malikakash214f6e62023-08-10 23:50:56 +00001176 if (packageIdRemapping.cameraIdsToReplace.size()
1177 != packageIdRemapping.updatedCameraIds.size()) {
malikakash82ed4352023-07-21 22:44:34 +00001178 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1179 "CameraIdRemapping: Mismatch in CameraId Remapping lists sizes for package %s",
malikakash73125c62023-07-21 22:44:34 +00001180 packageName.c_str());
malikakash82ed4352023-07-21 22:44:34 +00001181 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001182 for (size_t i = 0; i < packageIdRemapping.cameraIdsToReplace.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -07001183 cameraIdToReplace = packageIdRemapping.cameraIdsToReplace[i];
1184 updatedCameraId = packageIdRemapping.updatedCameraIds[i];
malikakash0894f5b2023-08-10 22:46:47 +00001185 if (cameraIdToReplace.empty() || updatedCameraId.empty()) {
malikakash214f6e62023-08-10 23:50:56 +00001186 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1187 "CameraIdRemapping: Camera Id cannot be empty for package %s",
Austin Borgered99f642023-06-01 16:51:35 -07001188 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001189 }
1190 if (cameraIdToReplace == updatedCameraId) {
1191 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1192 "CameraIdRemapping: CameraIdToReplace cannot be the same"
1193 " as updatedCameraId for %s",
Austin Borgered99f642023-06-01 16:51:35 -07001194 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001195 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001196
1197 // Do not allow any camera remapping that involves a virtual camera.
1198 auto [deviceIdForCameraToReplace, _] =
1199 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1200 cameraIdToReplace);
1201 if (deviceIdForCameraToReplace != kDefaultDeviceId) {
1202 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1203 "CameraIdRemapping: CameraIdToReplace cannot be a virtual camera");
1204 }
1205 [[maybe_unused]] auto [deviceIdForUpdatedCamera, unusedMappedCameraId] =
1206 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(updatedCameraId);
1207 if (deviceIdForUpdatedCamera != kDefaultDeviceId) {
1208 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1209 "CameraIdRemapping: UpdatedCameraId cannot be a virtual camera");
1210 }
1211
malikakash214f6e62023-08-10 23:50:56 +00001212 (*cameraIdRemappingMap)[packageName][cameraIdToReplace] = updatedCameraId;
malikakash82ed4352023-07-21 22:44:34 +00001213 }
1214 }
1215 return Status::ok();
1216}
1217
1218void CameraService::remapCameraIds(const TCameraIdRemapping& cameraIdRemapping) {
1219 // Acquire mServiceLock and prevent other clients from connecting
1220 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1221 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1222
malikakashedb38962023-09-06 00:03:35 +00001223 // Collect all existing clients for camera Ids that are being
1224 // remapped in the new cameraIdRemapping, but only if they were being used by a
1225 // targeted packageName.
malikakash82ed4352023-07-21 22:44:34 +00001226 std::vector<sp<BasicClient>> clientsToDisconnect;
Austin Borgered99f642023-06-01 16:51:35 -07001227 std::vector<std::string> cameraIdsToUpdate;
malikakash82ed4352023-07-21 22:44:34 +00001228 for (const auto& [packageName, injectionMap] : cameraIdRemapping) {
1229 for (auto& [id0, id1] : injectionMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001230 ALOGI("%s: UPDATE:= %s: %s: %s", __FUNCTION__, packageName.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001231 id0.c_str(), id1.c_str());
1232 auto clientDescriptor = mActiveClientManager.get(id0);
1233 if (clientDescriptor != nullptr) {
1234 sp<BasicClient> clientSp = clientDescriptor->getValue();
1235 if (clientSp->getPackageName() == packageName) {
malikakashedb38962023-09-06 00:03:35 +00001236 // This camera is being used by a targeted packageName and
1237 // being remapped to a new camera Id. We should disconnect it.
malikakash82ed4352023-07-21 22:44:34 +00001238 clientsToDisconnect.push_back(clientSp);
1239 cameraIdsToUpdate.push_back(id0);
1240 }
1241 }
1242 }
1243 }
1244
malikakashedb38962023-09-06 00:03:35 +00001245 for (auto& clientSp : clientsToDisconnect) {
malikakashf4c80f22023-09-25 21:50:28 +00001246 // Notify the clients about the disconnection.
1247 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
malikakashedb38962023-09-06 00:03:35 +00001248 CaptureResultExtras{});
1249 }
malikakash82ed4352023-07-21 22:44:34 +00001250
1251 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1252 // blocking other clients from connecting in mServiceLockWrapper if held.
1253 mServiceLock.unlock();
1254
malikakashedb38962023-09-06 00:03:35 +00001255 // Clear calling identity for disconnect() PID checks.
Austin Borger22c5c852024-03-08 13:31:36 -08001256 int64_t token = clearCallingIdentity();
malikakashedb38962023-09-06 00:03:35 +00001257
malikakash82ed4352023-07-21 22:44:34 +00001258 // Disconnect clients.
1259 for (auto& clientSp : clientsToDisconnect) {
malikakashedb38962023-09-06 00:03:35 +00001260 // This also triggers a call to updateStatus() which also reads mCameraIdRemapping
1261 // and requires mCameraIdRemappingLock.
malikakash82ed4352023-07-21 22:44:34 +00001262 clientSp->disconnect();
1263 }
1264
malikakashedb38962023-09-06 00:03:35 +00001265 // Invoke destructors (which call disconnect()) now while we don't hold the mServiceLock.
1266 clientsToDisconnect.clear();
1267
Austin Borger22c5c852024-03-08 13:31:36 -08001268 restoreCallingIdentity(token);
malikakash82ed4352023-07-21 22:44:34 +00001269 mServiceLock.lock();
malikakashedb38962023-09-06 00:03:35 +00001270
1271 {
1272 Mutex::Autolock lock(mCameraIdRemappingLock);
1273 // Update mCameraIdRemapping.
1274 mCameraIdRemapping.clear();
1275 mCameraIdRemapping.insert(cameraIdRemapping.begin(), cameraIdRemapping.end());
1276 }
malikakash82ed4352023-07-21 22:44:34 +00001277}
1278
malikakash22af94c2023-12-04 18:13:14 +00001279Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001280 const std::string& cameraId,
1281 const CameraMetadata& sessionParams) {
1282 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001283 const int pid = getCallingPid();
1284 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001285 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1286 __FUNCTION__, pid, uid);
1287 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1288 "Permission Denial: no permission to inject session params");
1289 }
1290
Biswarup Pal37a75182024-01-16 15:53:35 +00001291 // Do not allow session params injection for a virtual camera.
1292 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1293 if (deviceId != kDefaultDeviceId) {
1294 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1295 "Cannot inject session params for a virtual camera");
1296 }
1297
malikakash22af94c2023-12-04 18:13:14 +00001298 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1299 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1300
1301 auto clientDescriptor = mActiveClientManager.get(cameraId);
1302 if (clientDescriptor == nullptr) {
1303 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1304 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1305 "No active client for camera id %s", cameraId.c_str());
1306 }
1307
1308 sp<BasicClient> clientSp = clientDescriptor->getValue();
1309 status_t res = clientSp->injectSessionParams(sessionParams);
1310
1311 if (res != OK) {
1312 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1313 "Error injecting session params into camera \"%s\": %s (%d)",
1314 cameraId.c_str(), strerror(-res), res);
1315 }
1316 return Status::ok();
1317}
1318
Austin Borgered99f642023-06-01 16:51:35 -07001319std::vector<std::string> CameraService::findOriginalIdsForRemappedCameraId(
1320 const std::string& inputCameraId, int clientUid) {
1321 std::string packageName = getPackageNameFromUid(clientUid);
1322 std::vector<std::string> cameraIds;
malikakash82ed4352023-07-21 22:44:34 +00001323 Mutex::Autolock lock(mCameraIdRemappingLock);
1324 if (auto packageMapIter = mCameraIdRemapping.find(packageName);
1325 packageMapIter != mCameraIdRemapping.end()) {
1326 for (auto& [id0, id1]: packageMapIter->second) {
1327 if (id1 == inputCameraId) {
1328 cameraIds.push_back(id0);
1329 }
1330 }
1331 }
1332 return cameraIds;
1333}
1334
Austin Borgered99f642023-06-01 16:51:35 -07001335std::string CameraService::resolveCameraId(
1336 const std::string& inputCameraId,
malikakashedb38962023-09-06 00:03:35 +00001337 int clientUid,
Austin Borgered99f642023-06-01 16:51:35 -07001338 const std::string& packageName) {
1339 std::string packageNameVal = packageName;
malikakashedb38962023-09-06 00:03:35 +00001340 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001341 packageNameVal = getPackageNameFromUid(clientUid);
1342 }
malikakash65d20692023-09-07 01:06:33 +00001343 if (clientUid < AID_APP_START || packageNameVal.empty()) {
malikakashedb38962023-09-06 00:03:35 +00001344 // We shouldn't remap cameras for processes with system/vendor UIDs.
1345 return inputCameraId;
1346 }
malikakash82ed4352023-07-21 22:44:34 +00001347 Mutex::Autolock lock(mCameraIdRemappingLock);
1348 if (auto packageMapIter = mCameraIdRemapping.find(packageNameVal);
1349 packageMapIter != mCameraIdRemapping.end()) {
malikakash82ed4352023-07-21 22:44:34 +00001350 auto packageMap = packageMapIter->second;
1351 if (auto replacementIdIter = packageMap.find(inputCameraId);
1352 replacementIdIter != packageMap.end()) {
malikakashedb38962023-09-06 00:03:35 +00001353 ALOGI("%s: resolveCameraId: remapping cameraId %s for %s to %s",
malikakash82ed4352023-07-21 22:44:34 +00001354 __FUNCTION__, inputCameraId.c_str(),
malikakashedb38962023-09-06 00:03:35 +00001355 packageNameVal.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001356 replacementIdIter->second.c_str());
1357 return replacementIdIter->second;
1358 }
1359 }
1360 return inputCameraId;
1361}
1362
Biswarup Pal37a75182024-01-16 15:53:35 +00001363std::optional<std::string> CameraService::resolveCameraId(
1364 const std::string& inputCameraId,
1365 int32_t deviceId,
1366 int32_t devicePolicy,
1367 int clientUid,
1368 const std::string& packageName) {
1369 if ((deviceId == kDefaultDeviceId)
1370 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1371 auto [storedDeviceId, _] =
1372 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1373 if (storedDeviceId != kDefaultDeviceId) {
1374 // Trying to access a virtual camera from default-policy device context, we should fail.
1375 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1376 inputCameraId.c_str(), deviceId);
1377 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1378 return std::nullopt;
1379 }
1380 return resolveCameraId(inputCameraId, clientUid, packageName);
1381 }
1382
1383 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1384}
1385
1386Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait, int32_t deviceId,
1387 int32_t devicePolicy, CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001388 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001389 Mutex::Autolock l(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001390 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId, deviceId, devicePolicy);
1391 if (cameraIdStr.empty()) {
1392 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
1393 cameraId, deviceId);
1394 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1395 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1396 }
malikakashedb38962023-09-06 00:03:35 +00001397
Austin Borgered99f642023-06-01 16:51:35 -07001398 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001399 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1400 "characteristics for system only device %s: ", cameraIdStr.c_str());
1401 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001402
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001403 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001404 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001405 return STATUS_ERROR(ERROR_DISCONNECTED,
1406 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001407 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001408 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001409 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001410 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1411 if (hasSystemCameraPermissions) {
1412 cameraIdBound = mNumberOfCameras;
1413 }
1414 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001415 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1416 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001417 }
1418
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001419 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001420 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001421 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borgered99f642023-06-01 16:51:35 -07001422 cameraIdStr, overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001423 if (err != OK) {
1424 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1425 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1426 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001427 logServiceError(std::string("Error retrieving camera info from device ")
1428 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001429 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001430
Ruben Brunkcc776712015-02-17 20:18:47 -08001431 return ret;
1432}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001433
Biswarup Pal37a75182024-01-16 15:53:35 +00001434std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1435 int32_t deviceId, int32_t devicePolicy) {
1436 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1437 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1438 std::optional<std::string> cameraIdOptional =
1439 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1440 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1441 }
1442
1443 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001444 auto callingPid = getCallingPid();
1445 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001446 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1447 callingPid, callingUid, /* checkCameraPermissions= */ false);
1448 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001449 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001450 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001451 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1452 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1453 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001454 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001455 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001456
Biswarup Pal37a75182024-01-16 15:53:35 +00001457 std::string unresolvedCameraId = (*cameraIds)[cameraIdInt];
1458 return resolveCameraId(unresolvedCameraId, getCallingUid());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001459}
1460
Biswarup Pal37a75182024-01-16 15:53:35 +00001461std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1462 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001463 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001464 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001465}
1466
Austin Borgered99f642023-06-01 16:51:35 -07001467Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +00001468 int targetSdkVersion, bool overrideToPortrait, int32_t deviceId, int32_t devicePolicy,
1469 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001470 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001471
Zhijun He2b59be82013-09-25 10:14:30 -07001472 if (!cameraInfo) {
1473 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001474 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001475 }
1476
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001477 if (!mInitialized) {
1478 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001479 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001480 return STATUS_ERROR(ERROR_DISCONNECTED,
1481 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001482 }
1483
Biswarup Pal37a75182024-01-16 15:53:35 +00001484 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
1485 devicePolicy, getCallingUid());
1486 if (!cameraIdOptional.has_value()) {
1487 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1488 unresolvedCameraId.c_str(), deviceId);
1489 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1490 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1491 }
1492 std::string cameraId = cameraIdOptional.value();
1493
Austin Borgered99f642023-06-01 16:51:35 -07001494 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001495 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001496 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001497 }
1498
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001499 bool overrideForPerfClass =
1500 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001501 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001502 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borgered99f642023-06-01 16:51:35 -07001503 cameraId, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001504 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001505 if (res == NAME_NOT_FOUND) {
1506 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001507 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001508 strerror(-res), res);
1509 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001510 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1511 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001512 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001513 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001514 strerror(-res), res);
1515 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001516 }
Emilian Peeve20c6372018-08-14 18:45:53 +01001517
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001518 return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -07001519}
1520
Biswarup Pal37a75182024-01-16 15:53:35 +00001521Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId, int32_t deviceId,
1522 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001523 ATRACE_CALL();
1524 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001525
Biswarup Pal37a75182024-01-16 15:53:35 +00001526 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
1527 devicePolicy, getCallingUid());
1528 if (!cameraIdOptional.has_value()) {
1529 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1530 unresolvedCameraId.c_str(), deviceId);
1531 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1532 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1533 }
1534 std::string cameraId = cameraIdOptional.value();
1535
Rucha Katakwar38284522021-11-10 11:25:21 -08001536 if (!mInitialized) {
1537 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1538 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1539 }
1540
Biswarup Pal37a75182024-01-16 15:53:35 +00001541 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001542 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1543 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1544 }
1545
Austin Borgered99f642023-06-01 16:51:35 -07001546 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001547 if (res != OK) {
1548 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001549 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001550 strerror(-res), res);
1551 }
1552 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1553 return Status::ok();
1554}
1555
Austin Borgered99f642023-06-01 16:51:35 -07001556std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001557 time_t now = time(nullptr);
1558 char formattedTime[64];
1559 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001560 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001561}
1562
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001563Status CameraService::getCameraVendorTagDescriptor(
1564 /*out*/
1565 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001566 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001567 if (!mInitialized) {
1568 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001569 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001570 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001571 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1572 if (globalDescriptor != nullptr) {
1573 *desc = *(globalDescriptor.get());
1574 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001575 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001576}
1577
Emilian Peev71c73a22017-03-21 16:35:51 +00001578Status CameraService::getCameraVendorTagCache(
1579 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1580 ATRACE_CALL();
1581 if (!mInitialized) {
1582 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1583 return STATUS_ERROR(ERROR_DISCONNECTED,
1584 "Camera subsystem not available");
1585 }
1586 sp<VendorTagDescriptorCache> globalCache =
1587 VendorTagDescriptorCache::getGlobalVendorTagCache();
1588 if (globalCache != nullptr) {
1589 *cache = *(globalCache.get());
1590 }
1591 return Status::ok();
1592}
1593
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001594void CameraService::clearCachedVariables() {
1595 BasicClient::BasicClient::sCameraService = nullptr;
1596}
1597
Austin Borgered99f642023-06-01 16:51:35 -07001598std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001599 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001600 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001601
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001602 int deviceVersion = 0;
1603
Emilian Peevf53f66e2017-04-11 14:29:43 +01001604 status_t res;
1605 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001606 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001607 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001608 if (res != OK || transport == IPCTransport::INVALID) {
1609 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001610 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001611 return std::make_pair(-1, IPCTransport::INVALID) ;
1612 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001613 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001614
Emilian Peevf53f66e2017-04-11 14:29:43 +01001615 hardware::CameraInfo info;
1616 if (facing) {
Austin Borgered99f642023-06-01 16:51:35 -07001617 res = mCameraProviderManager->getCameraInfo(cameraId, overrideToPortrait,
Austin Borger18b30a72022-10-27 12:20:29 -07001618 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001619 if (res != OK) {
1620 return std::make_pair(-1, IPCTransport::INVALID);
1621 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001622 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001623 if (orientation) {
1624 *orientation = info.orientation;
1625 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001626 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001627
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001628 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001629}
1630
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001631Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001632 switch(err) {
1633 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001634 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001635 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001636 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1637 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001638 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001639 return STATUS_ERROR(ERROR_DISCONNECTED,
1640 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001641 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001642 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1643 "Camera HAL encountered error %d: %s",
1644 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001645 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001646}
1647
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001648Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001649 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1650 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001651 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001652 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001653 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
malikakash73125c62023-07-21 22:44:34 +00001654 bool forceSlowJpegMode, const std::string& originalCameraId,
1655 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001656 // For HIDL devices
1657 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1658 // Create CameraClient based on device version reported by the HAL.
1659 int deviceVersion = deviceVersionAndTransport.first;
1660 switch(deviceVersion) {
1661 case CAMERA_DEVICE_API_VERSION_1_0:
1662 ALOGE("Camera using old HAL version: %d", deviceVersion);
1663 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1664 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001665 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001666 break;
1667 case CAMERA_DEVICE_API_VERSION_3_0:
1668 case CAMERA_DEVICE_API_VERSION_3_1:
1669 case CAMERA_DEVICE_API_VERSION_3_2:
1670 case CAMERA_DEVICE_API_VERSION_3_3:
1671 case CAMERA_DEVICE_API_VERSION_3_4:
1672 case CAMERA_DEVICE_API_VERSION_3_5:
1673 case CAMERA_DEVICE_API_VERSION_3_6:
1674 case CAMERA_DEVICE_API_VERSION_3_7:
1675 break;
1676 default:
1677 // Should not be reachable
1678 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1679 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1680 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001681 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001682 }
1683 }
1684 if (effectiveApiLevel == API_1) { // Camera1 API route
1685 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001686 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001687 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001688 api1CameraId, facing, sensorOrientation,
Chengfei Taobe683db2023-01-31 18:52:49 +00001689 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait,
1690 forceSlowJpegMode);
1691 ALOGI("%s: Camera1 API (legacy), override to portrait %d, forceSlowJpegMode %d",
1692 __FUNCTION__, overrideToPortrait, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001693 } else { // Camera2 API route
1694 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1695 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001696 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001697 cameraService->mCameraServiceProxyWrapper,
1698 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001699 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
malikakash82ed4352023-07-21 22:44:34 +00001700 overrideForPerfClass, overrideToPortrait, originalCameraId);
Austin Borger18b30a72022-10-27 12:20:29 -07001701 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001702 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001703 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001704}
1705
Austin Borgered99f642023-06-01 16:51:35 -07001706std::string CameraService::toString(std::set<userid_t> intSet) {
1707 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001708 bool first = true;
1709 for (userid_t i : intSet) {
1710 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001711 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001712 first = false;
1713 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001714 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001715 }
1716 }
Austin Borgered99f642023-06-01 16:51:35 -07001717 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001718}
1719
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001720int32_t CameraService::mapToInterface(TorchModeStatus status) {
1721 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1722 switch (status) {
1723 case TorchModeStatus::NOT_AVAILABLE:
1724 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1725 break;
1726 case TorchModeStatus::AVAILABLE_OFF:
1727 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1728 break;
1729 case TorchModeStatus::AVAILABLE_ON:
1730 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1731 break;
1732 default:
1733 ALOGW("Unknown new flash status: %d", status);
1734 }
1735 return serviceStatus;
1736}
1737
1738CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1739 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1740 switch (status) {
1741 case CameraDeviceStatus::NOT_PRESENT:
1742 serviceStatus = StatusInternal::NOT_PRESENT;
1743 break;
1744 case CameraDeviceStatus::PRESENT:
1745 serviceStatus = StatusInternal::PRESENT;
1746 break;
1747 case CameraDeviceStatus::ENUMERATING:
1748 serviceStatus = StatusInternal::ENUMERATING;
1749 break;
1750 default:
1751 ALOGW("Unknown new HAL device status: %d", status);
1752 }
1753 return serviceStatus;
1754}
1755
1756int32_t CameraService::mapToInterface(StatusInternal status) {
1757 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1758 switch (status) {
1759 case StatusInternal::NOT_PRESENT:
1760 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1761 break;
1762 case StatusInternal::PRESENT:
1763 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1764 break;
1765 case StatusInternal::ENUMERATING:
1766 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1767 break;
1768 case StatusInternal::NOT_AVAILABLE:
1769 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1770 break;
1771 case StatusInternal::UNKNOWN:
1772 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1773 break;
1774 default:
1775 ALOGW("Unknown new internal device status: %d", status);
1776 }
1777 return serviceStatus;
1778}
1779
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001780Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001781 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001782
Austin Borgered99f642023-06-01 16:51:35 -07001783 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001784 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001785 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001786 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001787 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1788 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001789 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Chengfei Taobe683db2023-01-31 18:52:49 +00001790 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true,
Austin Borgered99f642023-06-01 16:51:35 -07001791 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001792 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001793 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001794 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001795 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001796}
1797
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001798Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001799 /*out*/
1800 CameraParameters* parameters) {
1801
1802 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1803
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001804 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001805
1806 if (parameters == NULL) {
1807 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001808 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001809 }
1810
malikakashedb38962023-09-06 00:03:35 +00001811 std::string unresolvedCameraId = std::to_string(cameraId);
1812 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08001813 getCallingUid());
Ruben Brunkcc776712015-02-17 20:18:47 -08001814
1815 // Check if we already have parameters
1816 {
1817 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001818 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001819 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001820 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001821 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001822 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001823 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001824 }
1825 CameraParameters p = cameraState->getShimParams();
1826 if (!p.isEmpty()) {
1827 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001828 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001829 }
1830 }
1831
Austin Borger22c5c852024-03-08 13:31:36 -08001832 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001833 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001834 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001835 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001836 // Error already logged by callee
1837 return ret;
1838 }
1839
1840 // Check for parameters again
1841 {
1842 // Scope for service lock
1843 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001844 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001845 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001846 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001847 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001848 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001849 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001850 CameraParameters p = cameraState->getShimParams();
1851 if (!p.isEmpty()) {
1852 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001853 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001854 }
1855 }
1856
Ruben Brunkcc776712015-02-17 20:18:47 -08001857 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1858 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001859 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001860}
1861
Austin Borgered99f642023-06-01 16:51:35 -07001862Status CameraService::validateConnectLocked(const std::string& cameraId,
1863 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001864 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001865
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001866#ifdef __BRILLO__
1867 UNUSED(clientName8);
1868 UNUSED(clientUid);
1869 UNUSED(clientPid);
1870 UNUSED(originalClientPid);
1871#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001872 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1873 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001874 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001875 return allowed;
1876 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001877#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001878
Austin Borger22c5c852024-03-08 13:31:36 -08001879 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001880
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001881 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001882 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1883 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001884 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001885 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001886 }
1887
Ruben Brunkcc776712015-02-17 20:18:47 -08001888 if (getCameraState(cameraId) == nullptr) {
1889 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001890 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001891 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001892 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001893 }
1894
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001895 status_t err = checkIfDeviceIsUsable(cameraId);
1896 if (err != NO_ERROR) {
1897 switch(err) {
1898 case -ENODEV:
1899 case -EBUSY:
1900 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001901 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001902 default:
1903 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001904 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001905 }
1906 }
1907 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001908}
1909
Austin Borgered99f642023-06-01 16:51:35 -07001910Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1911 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001912 /*out*/int& originalClientPid) const {
Austin Borger22c5c852024-03-08 13:31:36 -08001913 int callingPid = getCallingPid();
1914 int callingUid = getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001915
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001916 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001917 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001918 clientUid = callingUid;
1919 } else if (!isTrustedCallingUid(callingUid)) {
1920 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1921 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001922 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1923 "Untrusted caller (calling PID %d, UID %d) trying to "
1924 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001925 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001926 clientName.c_str(), clientPid, clientUid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001927 }
1928
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001929 // Check if we can trust clientPid
1930 if (clientPid == USE_CALLING_PID) {
1931 clientPid = callingPid;
1932 } else if (!isTrustedCallingUid(callingUid)) {
1933 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1934 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001935 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1936 "Untrusted caller (calling PID %d, UID %d) trying to "
1937 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001938 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001939 clientName.c_str(), clientPid, clientUid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001940 }
1941
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001942 if (shouldRejectSystemCameraConnection(cameraId)) {
1943 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1944 cameraId.c_str());
1945 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001946 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001947 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001948 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1949 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001950 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001951 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001952 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001953
1954 }
1955
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001956 // If it's not calling from cameraserver, check the permission if the
1957 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1958 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001959 bool checkPermissionForCamera =
1960 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001961 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001962 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001963 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001964 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1965 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001966 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001967 }
1968
Svet Ganova453d0d2018-01-11 15:37:58 -08001969 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001970 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001971 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001972 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1973 clientPid, clientUid);
1974 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001975 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1976 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001977 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001978 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001979 }
1980
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001981 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1982 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1983 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1984 if ((!isAutomotivePrivilegedClient(callingUid) ||
1985 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1986 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001987 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1988 return STATUS_ERROR_FMT(ERROR_DISABLED,
1989 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001990 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001991 }
1992
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001993 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1994 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001995 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001996 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001997
Ruben Brunk6267b532015-04-30 17:44:07 -07001998 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001999
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002000 // For non-system clients : Only allow clients who are being used by the current foreground
2001 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08002002 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08002003 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002004 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
2005 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07002006 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002007 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2008 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002009 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07002010 }
2011
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07002012 if (flags::camera_hsum_permission()) {
2013 // If the System User tries to access the camera when the device is running in
2014 // headless system user mode, ensure that client has the required permission
2015 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07002016 if (isHeadlessSystemUserMode()
2017 && (clientUserId == USER_SYSTEM)
2018 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07002019 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
2020 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2021 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
2022 User without camera headless system user permission",
Austin Borger249e6592024-03-10 22:28:11 -07002023 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07002024 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07002025 }
2026
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002027 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002028}
2029
Austin Borgered99f642023-06-01 16:51:35 -07002030status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08002031 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08002032 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08002033 if (cameraState == nullptr) {
2034 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07002035 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002036 return -ENODEV;
2037 }
2038
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002039 StatusInternal currentStatus = cameraState->getStatus();
2040 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002041 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07002042 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002043 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002044 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002045 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07002046 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002047 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07002048 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002049
Ruben Brunkcc776712015-02-17 20:18:47 -08002050 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08002051}
2052
Ruben Brunkcc776712015-02-17 20:18:47 -08002053void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002054 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08002055
Ruben Brunkcc776712015-02-17 20:18:47 -08002056 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002057 auto clientDescriptor =
2058 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002059 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08002060 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
2061
2062 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002063 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08002064
2065 if (evicted.size() > 0) {
2066 // This should never happen - clients should already have been removed in disconnect
2067 for (auto& i : evicted) {
2068 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07002069 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002070 }
2071
2072 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
2073 __FUNCTION__);
2074 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002075
2076 // And register a death notification for the client callback. Do
2077 // this last to avoid Binder policy where a nested Binder
2078 // transaction might be pre-empted to service the client death
2079 // notification if the client process dies before linkToDeath is
2080 // invoked.
2081 sp<IBinder> remoteCallback = client->getRemote();
2082 if (remoteCallback != nullptr) {
2083 remoteCallback->linkToDeath(this);
2084 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002085}
2086
Austin Borgered99f642023-06-01 16:51:35 -07002087status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
2088 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
2089 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08002090 /*out*/
2091 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07002092 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002093 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08002094 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002095 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08002096 DescriptorPtr clientDescriptor;
2097 {
2098 if (effectiveApiLevel == API_1) {
2099 // If we are using API1, any existing client for this camera ID with the same remote
2100 // should be returned rather than evicted to allow MediaRecorder to work properly.
2101
2102 auto current = mActiveClientManager.get(cameraId);
2103 if (current != nullptr) {
2104 auto clientSp = current->getValue();
2105 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002106 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07002107 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002108 " API level, evicting prior client...");
2109 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002110 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002111 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002112 *client = clientSp;
2113 return NO_ERROR;
2114 }
2115 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002116 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002117 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08002118
Ruben Brunkcc776712015-02-17 20:18:47 -08002119 // Get state for the given cameraId
2120 auto state = getCameraState(cameraId);
2121 if (state == nullptr) {
2122 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07002123 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002124 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07002125 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002126 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002127
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002128 sp<IServiceManager> sm = defaultServiceManager();
2129 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08002130 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002131 // If processinfo service is not available and the client is automotive privileged
2132 // client used for safety critical uses cases such as rear-view and surround-view which
2133 // needs to be available before android boot completes, then use the hardcoded values
2134 // for the process state and priority score. As this scenario is before android system
2135 // services are up and client is native client, hence using NATIVE_ADJ as the priority
2136 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
2137 // visible on the top.
2138 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2139 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2140 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
2141 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
2142 } else {
2143 // Get current active client PIDs
2144 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
2145 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002146
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002147 std::vector<int> priorityScores(ownerPids.size());
2148 std::vector<int> states(ownerPids.size());
2149
2150 // Get priority scores of all active PIDs
2151 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
2152 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
2153 if (err != OK) {
2154 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
2155 return err;
2156 }
2157
2158 // Update all active clients' priorities
2159 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
2160 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
2161 pidToPriorityMap.emplace(ownerPids[i],
2162 resource_policy::ClientPriority(priorityScores[i], states[i],
2163 /* isVendorClient won't get copied over*/ false,
2164 /* oomScoreOffset won't get copied over*/ 0));
2165 }
2166 mActiveClientManager.updatePriorities(pidToPriorityMap);
2167
2168 int32_t actualScore = priorityScores[priorityScores.size() - 1];
2169 int32_t actualState = states[states.size() - 1];
2170
2171 // Make descriptor for incoming client. We store the oomScoreOffset
2172 // since we might need it later on new handleEvictionsLocked and
2173 // ProcessInfoService would not take that into account.
2174 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2175 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2176 state->getConflicting(), actualScore, clientPid, actualState,
2177 oomScoreOffset, systemNativeClient);
2178 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002179
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002180 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
2181
Ruben Brunkcc776712015-02-17 20:18:47 -08002182 // Find clients that would be evicted
2183 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
2184
2185 // If the incoming client was 'evicted,' higher priority clients have the camera in the
2186 // background, so we cannot do evictions
2187 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2188 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2189 " priority).", clientPid);
2190
2191 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002192 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002193 auto incompatibleClients =
2194 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2195
Austin Borgered99f642023-06-01 16:51:35 -07002196 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2197 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2198 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002199 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002200
2201 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002202 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002203 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002204 i->getKey().c_str(),
2205 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002206 i->getOwnerId(), i->getPriority().getScore(),
2207 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002208 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002209 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2210 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002211 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002212 }
2213
2214 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002215 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002216 mEventLog.add(msg);
2217
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002218 auto current = mActiveClientManager.get(cameraId);
2219 if (current != nullptr) {
2220 return -EBUSY; // CAMERA_IN_USE
2221 } else {
2222 return -EUSERS; // MAX_CAMERAS_IN_USE
2223 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002224 }
2225
2226 for (auto& i : evicted) {
2227 sp<BasicClient> clientSp = i->getValue();
2228 if (clientSp.get() == nullptr) {
2229 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2230
2231 // TODO: Remove this
2232 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2233 __FUNCTION__);
2234 mActiveClientManager.remove(i);
2235 continue;
2236 }
2237
2238 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002239 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002240 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002241
Ruben Brunkcc776712015-02-17 20:18:47 -08002242 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002243 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002244 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2245 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002246 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002247 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002248 i->getPriority().getState(), cameraId.c_str(),
2249 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002250 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002251
2252 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002253 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002254 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002255 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002256 }
2257
Ruben Brunkcc776712015-02-17 20:18:47 -08002258 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2259 // other clients from connecting in mServiceLockWrapper if held
2260 mServiceLock.unlock();
2261
2262 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002263 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002264
2265 // Destroy evicted clients
2266 for (auto& i : evictedClients) {
2267 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002268 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002269 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002270
Austin Borger22c5c852024-03-08 13:31:36 -08002271 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002272
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002273 for (const auto& i : evictedClients) {
2274 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002275 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002276 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2277 if (ret == TIMED_OUT) {
2278 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002279 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2280 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002281 return -EBUSY;
2282 }
2283 if (ret != NO_ERROR) {
2284 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002285 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2286 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002287 return ret;
2288 }
2289 }
2290
2291 evictedClients.clear();
2292
Ruben Brunkcc776712015-02-17 20:18:47 -08002293 // Once clients have been disconnected, relock
2294 mServiceLock.lock();
2295
2296 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2297 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2298 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002299 }
2300
Ruben Brunkcc776712015-02-17 20:18:47 -08002301 *partial = clientDescriptor;
2302 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002303}
2304
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002305Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002306 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002307 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07002308 const std::string& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002309 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08002310 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002311 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07002312 bool overrideToPortrait,
Chengfei Taobe683db2023-01-31 18:52:49 +00002313 bool forceSlowJpegMode,
Biswarup Pal37a75182024-01-16 15:53:35 +00002314 int32_t deviceId,
2315 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002316 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002317 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002318 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002319 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002320
Biswarup Pal37a75182024-01-16 15:53:35 +00002321 std::string cameraIdStr = cameraIdIntToStr(api1CameraId, deviceId, devicePolicy);
2322 if (cameraIdStr.empty()) {
2323 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
2324 api1CameraId, deviceId);
2325 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2326 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2327 }
malikakashedb38962023-09-06 00:03:35 +00002328
Ruben Brunkcc776712015-02-17 20:18:47 -08002329 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002330 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
2331 clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002332 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002333 overrideToPortrait, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002334
Biswarup Pal37a75182024-01-16 15:53:35 +00002335 if (!ret.isOk()) {
2336 logRejected(cameraIdStr, getCallingPid(), clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002337 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002338 }
2339
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002340 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002341
2342 const sp<IServiceManager> sm(defaultServiceManager());
2343 const auto& mActivityManager = getActivityManager();
2344 if (mActivityManager) {
2345 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002346 getCallingUid(),
2347 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002348 }
2349
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002350 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002351}
2352
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002353bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2354 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002355 // If the client is not a vendor client, don't add listener if
2356 // a) the camera is a publicly hidden secure camera OR
2357 // b) the camera is a system only camera and the client doesn't
2358 // have android.permission.SYSTEM_CAMERA permissions.
2359 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2360 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002361 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002362 return true;
2363 }
2364 return false;
2365}
2366
Austin Borgered99f642023-06-01 16:51:35 -07002367bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002368 // Rules for rejection:
2369 // 1) If cameraserver tries to access this camera device, accept the
2370 // connection.
2371 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002372 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002373 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2374 // and the serving thread is a non hwbinder thread, the client must have
2375 // android.permission.SYSTEM_CAMERA permissions to connect.
2376
Austin Borger22c5c852024-03-08 13:31:36 -08002377 int cPid = getCallingPid();
2378 int cUid = getCallingUid();
2379 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002380 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2381 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002382 // This isn't a known camera ID, so it's not a system camera
2383 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2384 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002385 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002386
2387 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002388 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002389 return false;
2390 }
2391 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002392 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002393 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2394 return true;
2395 }
2396 // (3) Here we only check for permissions if it is a system only camera device. This is since
2397 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2398 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2399 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002400 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002401 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002402 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2403 cameraId.c_str());
2404 return true;
2405 }
2406
2407 return false;
2408}
2409
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002410Status CameraService::connectDevice(
2411 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002412 const std::string& unresolvedCameraId,
2413 const std::string& clientPackageName,
2414 const std::optional<std::string>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002415 int clientUid, int oomScoreOffset, int targetSdkVersion,
Biswarup Pal37a75182024-01-16 15:53:35 +00002416 bool overrideToPortrait, int32_t deviceId, int32_t devicePolicy,
Ruben Brunkcc776712015-02-17 20:18:47 -08002417 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002418 sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002419 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002420 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002421 sp<CameraDeviceClient> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002422 std::string clientPackageNameAdj = clientPackageName;
Austin Borger22c5c852024-03-08 13:31:36 -08002423 int callingPid = getCallingPid();
2424 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002425 bool systemNativeClient = false;
Austin Borger22c5c852024-03-08 13:31:36 -08002426 if (callerHasSystemUid() && (clientPackageNameAdj.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002427 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borgered99f642023-06-01 16:51:35 -07002428 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002429 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002430 }
Austin Borger249e6592024-03-10 22:28:11 -07002431
Biswarup Pal37a75182024-01-16 15:53:35 +00002432 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
2433 devicePolicy, callingUid, clientPackageNameAdj);
2434 if (!cameraIdOptional.has_value()) {
2435 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
2436 unresolvedCameraId.c_str(), deviceId);
2437 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2438 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2439 }
2440 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002441
2442 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002443 std::string msg =
2444 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
2445 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
2446 cameraId.c_str());
2447 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2448 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002449 }
2450
Austin Borger9bfa0a72022-08-03 17:50:40 -07002451 userid_t clientUserId = multiuser_get_user_id(clientUid);
Austin Borger9bfa0a72022-08-03 17:50:40 -07002452 if (clientUid == USE_CALLING_UID) {
2453 clientUserId = multiuser_get_user_id(callingUid);
2454 }
2455
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002456 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2457 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002458 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2459 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002460 std::string msg = "Camera disabled by device policy";
2461 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2462 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002463 }
2464
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002465 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002466 if (oomScoreOffset > 0
2467 && !hasPermissionsForSystemCamera(cameraId, callingPid,
Austin Borger249e6592024-03-10 22:28:11 -07002468 callingUid)
2469 && !isTrustedCallingUid(callingUid)) {
Austin Borgered99f642023-06-01 16:51:35 -07002470 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002471 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07002472 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2473 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2474 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002475 }
2476
Austin Borgered99f642023-06-01 16:51:35 -07002477 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
2478 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002479 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
malikakash73125c62023-07-21 22:44:34 +00002480 targetSdkVersion, overrideToPortrait, /*forceSlowJpegMode*/false, unresolvedCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002481 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002482
Biswarup Pal37a75182024-01-16 15:53:35 +00002483 if (!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002484 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002485 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002486 }
2487
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002488 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002489 Mutex::Autolock lock(mServiceLock);
2490
2491 // Clear the previous cached logs and reposition the
2492 // file offset to beginning of the file to log new data.
2493 // If either truncate or lseek fails, close the previous file and create a new one.
2494 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2495 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2496 // Close the previous memfd.
2497 close(mMemFd);
2498 // If failure to wipe the data, then create a new file and
2499 // assign the new value to mMemFd.
2500 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2501 if (mMemFd == -1) {
2502 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2503 }
2504 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002505 const sp<IServiceManager> sm(defaultServiceManager());
2506 const auto& mActivityManager = getActivityManager();
2507 if (mActivityManager) {
2508 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002509 callingUid,
2510 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002511 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002512 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002513}
2514
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002515bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2516 int callingPid, int callingUid) {
2517 if (!isAutomotiveDevice()) {
2518 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2519 }
2520
2521 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2522 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2523 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2524 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2525 "using camera %s", callingUid, cam_id.c_str());
2526 return false;
2527 }
2528
2529 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2530 return true;
2531 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2532 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002533 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2534 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002535 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2536 return false;
2537 } else {
2538 return true;
2539 }
2540 }
2541 return false;
2542}
2543
Austin Borgered99f642023-06-01 16:51:35 -07002544std::string CameraService::getPackageNameFromUid(int clientUid) {
2545 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002546
Avichal Rakesh5788fec2024-03-15 14:39:20 -07002547 sp<IPermissionController> permCtrl;
2548 if (flags::cache_permission_services()) {
2549 permCtrl = getPermissionController();
2550 } else {
2551 sp<IServiceManager> sm = defaultServiceManager();
2552#pragma clang diagnostic push
2553#pragma clang diagnostic ignored "-Wdeprecated-declarations"
2554 // Using deprecated function to preserve functionality until the
2555 // cache_permission_services flag is removed.
2556 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
2557#pragma clang diagnostic pop
2558 if (binder == 0) {
2559 ALOGE("Cannot get permission service");
2560 permCtrl = nullptr;
2561 } else {
2562 permCtrl = interface_cast<IPermissionController>(binder);
2563 }
2564 }
2565
2566 if (permCtrl == nullptr) {
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002567 // Return empty package name and the further interaction
2568 // with camera will likely fail
2569 return packageName;
2570 }
2571
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002572 Vector<String16> packages;
2573
2574 permCtrl->getPackagesForUid(clientUid, packages);
2575
2576 if (packages.isEmpty()) {
2577 ALOGE("No packages for calling UID %d", clientUid);
2578 // Return empty package name and the further interaction
2579 // with camera will likely fail
2580 return packageName;
2581 }
2582
2583 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002584 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002585
2586 return packageName;
2587}
2588
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002589template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002590Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2591 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2592 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002593 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002594 bool overrideToPortrait, bool forceSlowJpegMode, const std::string& originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002595 /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002596 binder::Status ret = binder::Status::ok();
2597
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002598 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002599 std::string clientPackageName;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002600 int packageUid = (clientUid == USE_CALLING_UID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002601 getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002602 if (clientPackageNameMaybe.size() <= 0) {
2603 // NDK calls don't come with package names, but we need one for various cases.
2604 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2605 // do exist. For all authentication cases, all packages under the same UID get the
2606 // same permissions, so picking any associated package name is sufficient. For some
2607 // other cases, this may give inaccurate names for clients in logs.
2608 isNonSystemNdk = true;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002609 clientPackageName = getPackageNameFromUid(packageUid);
2610 } else {
2611 clientPackageName = clientPackageNameMaybe;
2612 }
2613
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002614 int originalClientPid = 0;
2615
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002616 int packagePid = (clientPid == USE_CALLING_PID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002617 getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002618 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002619 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002620 static_cast<int>(effectiveApiLevel));
2621
Shuzhen Wang316781a2020-08-18 18:11:01 -07002622 nsecs_t openTimeNs = systemTime();
2623
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002624 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002625 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002626 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002627
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002628 {
2629 // Acquire mServiceLock and prevent other clients from connecting
2630 std::unique_ptr<AutoConditionLock> lock =
2631 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2632
2633 if (lock == nullptr) {
2634 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2635 , clientPid);
2636 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2637 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002638 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002639 }
2640
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002641 // Enforce client permissions and do basic validity checks
Biswarup Pal37a75182024-01-16 15:53:35 +00002642 if (!(ret = validateConnectLocked(cameraId, clientPackageName,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002643 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2644 return ret;
2645 }
2646
2647 // Check the shim parameters after acquiring lock, if they have already been updated and
2648 // we were doing a shim update, return immediately
2649 if (shimUpdateOnly) {
2650 auto cameraState = getCameraState(cameraId);
2651 if (cameraState != nullptr) {
2652 if (!cameraState->getShimParams().isEmpty()) return ret;
2653 }
2654 }
2655
2656 status_t err;
2657
2658 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002659 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002660 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002661 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2662 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002663 switch (err) {
2664 case -ENODEV:
2665 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2666 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002667 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002668 case -EBUSY:
2669 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2670 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002671 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002672 case -EUSERS:
2673 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2674 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002675 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002676 default:
2677 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2678 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002679 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002680 }
2681 }
2682
2683 if (clientTmp.get() != nullptr) {
2684 // Handle special case for API1 MediaRecorder where the existing client is returned
2685 device = static_cast<CLIENT*>(clientTmp.get());
2686 return ret;
2687 }
2688
2689 // give flashlight a chance to close devices if necessary.
2690 mFlashlight->prepareDeviceOpen(cameraId);
2691
Austin Borger18b30a72022-10-27 12:20:29 -07002692 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002693 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07002694 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
2695 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002696 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002697 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002698 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002699 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002700 }
2701
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002702 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002703 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002704 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002705 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002706 clientFeatureId, cameraId, api1CameraId, facing,
2707 orientation, clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002708 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
malikakash82ed4352023-07-21 22:44:34 +00002709 overrideToPortrait, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002710 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002711 return ret;
2712 }
2713 client = static_cast<CLIENT*>(tmp.get());
2714
2715 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2716 __FUNCTION__);
2717
Austin Borgered99f642023-06-01 16:51:35 -07002718 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002719 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002720 if (err != OK) {
2721 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002722 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002723 mServiceLock.unlock();
2724 client->disconnect();
2725 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002726 switch(err) {
2727 case BAD_VALUE:
2728 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002729 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002730 case -EBUSY:
2731 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002732 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002733 case -EUSERS:
2734 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2735 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002736 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002737 case PERMISSION_DENIED:
2738 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002739 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002740 case -EACCES:
2741 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002742 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002743 case -ENODEV:
2744 default:
2745 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002746 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002747 strerror(-err), err);
2748 }
2749 }
2750
2751 // Update shim paremeters for legacy clients
2752 if (effectiveApiLevel == API_1) {
2753 // Assume we have always received a Client subclass for API1
2754 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2755 String8 rawParams = shimClient->getParameters();
2756 CameraParameters params(rawParams);
2757
2758 auto cameraState = getCameraState(cameraId);
2759 if (cameraState != nullptr) {
2760 cameraState->setShimParams(params);
2761 } else {
2762 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002763 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002764 }
2765 }
2766
Ravneetaeb20dc2022-03-30 05:33:03 +00002767 // Enable/disable camera service watchdog
2768 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2769
Emilian Peev6d45db82024-01-18 20:11:54 +00002770 CameraMetadata chars;
2771 bool rotateAndCropSupported = true;
2772 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
2773 &chars, overrideToPortrait);
2774 if (err == OK) {
2775 auto availableRotateCropEntry = chars.find(
2776 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2777 if (availableRotateCropEntry.count <= 1) {
2778 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002779 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002780 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002781 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2782 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002783 }
2784
Emilian Peev6d45db82024-01-18 20:11:54 +00002785 if (rotateAndCropSupported) {
2786 // Set rotate-and-crop override behavior
2787 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2788 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
2789 } else if (overrideToPortrait && portraitRotation != 0) {
2790 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2791 switch (portraitRotation) {
2792 case 90:
2793 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2794 break;
2795 case 180:
2796 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2797 break;
2798 case 270:
2799 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2800 break;
2801 default:
2802 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2803 break;
2804 }
2805 client->setRotateAndCropOverride(rotateAndCropMode);
2806 } else {
2807 client->setRotateAndCropOverride(
2808 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2809 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2810 }
2811 }
2812
2813 bool autoframingSupported = true;
2814 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2815 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2816 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2817 autoframingSupported = false;
2818 }
2819
2820 if (autoframingSupported) {
2821 // Set autoframing override behaviour
2822 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2823 client->setAutoframingOverride(mOverrideAutoframingMode);
2824 } else {
2825 client->setAutoframingOverride(
2826 mCameraServiceProxyWrapper->getAutoframingOverride(
2827 clientPackageName));
2828 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002829 }
2830
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002831 bool isCameraPrivacyEnabled;
2832 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002833 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002834 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2835 toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2836 } else {
2837 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002838 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002839 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002840
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002841 if (client->supportsCameraMute()) {
2842 client->setCameraMute(
2843 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2844 } else if (isCameraPrivacyEnabled) {
2845 // no camera mute supported, but privacy is on! => disconnect
2846 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2847 client->getPackageName().c_str(), cameraId.c_str());
2848 // Do not hold mServiceLock while disconnecting clients, but
2849 // retain the condition blocking other clients from connecting
2850 // in mServiceLockWrapper if held.
2851 mServiceLock.unlock();
2852 // Clear caller identity temporarily so client disconnect PID
2853 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002854 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002855 // Note AppOp to trigger the "Unblock" dialog
2856 client->noteAppOp();
2857 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002858 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002859 // Reacquire mServiceLock
2860 mServiceLock.lock();
2861
2862 return STATUS_ERROR_FMT(ERROR_DISABLED,
2863 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002864 }
2865
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002866 if (shimUpdateOnly) {
2867 // If only updating legacy shim parameters, immediately disconnect client
2868 mServiceLock.unlock();
2869 client->disconnect();
2870 mServiceLock.lock();
2871 } else {
2872 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002873 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002874 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002875
2876 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002877 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002878 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002879 } // lock is destroyed, allow further connect calls
2880
2881 // Important: release the mutex here so the client can call back into the service from its
2882 // destructor (can be at the end of the call)
2883 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002884
2885 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002886 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002887 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002888
Cliff Wud3a05312021-04-26 23:07:31 +08002889 {
2890 Mutex::Autolock lock(mInjectionParametersLock);
2891 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2892 mInjectionInitPending = false;
2893 status_t res = NO_ERROR;
2894 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2895 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002896 sp<BasicClient> clientSp = clientDescriptor->getValue();
2897 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2898 if(res != OK) {
2899 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2900 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002901 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002902 }
2903 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002904 if (res != OK) {
2905 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2906 }
2907 } else {
2908 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002909 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002910 res = NO_INIT;
2911 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2912 }
2913 }
2914 }
2915
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002916 return ret;
2917}
2918
Austin Borgered99f642023-06-01 16:51:35 -07002919status_t CameraService::addOfflineClient(const std::string &cameraId,
2920 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002921 if (offlineClient.get() == nullptr) {
2922 return BAD_VALUE;
2923 }
2924
2925 {
2926 // Acquire mServiceLock and prevent other clients from connecting
2927 std::unique_ptr<AutoConditionLock> lock =
2928 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2929
2930 if (lock == nullptr) {
2931 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2932 , __FUNCTION__, offlineClient->getClientPid());
2933 return TIMED_OUT;
2934 }
2935
2936 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2937 if (onlineClientDesc.get() == nullptr) {
2938 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2939 cameraId.c_str());
2940 return BAD_VALUE;
2941 }
2942
2943 // Offline clients do not evict or conflict with other online devices. Resource sharing
2944 // conflicts are handled by the camera provider which will either succeed or fail before
2945 // reaching this method.
2946 const auto& onlinePriority = onlineClientDesc->getPriority();
2947 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2948 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002949 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002950 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002951 // native clients don't have offline processing support.
2952 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002953 if (offlineClientDesc == nullptr) {
2954 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2955 return BAD_VALUE;
2956 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002957
2958 // Allow only one offline device per camera
2959 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2960 if (!incompatibleClients.empty()) {
2961 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2962 return BAD_VALUE;
2963 }
2964
Austin Borgered99f642023-06-01 16:51:35 -07002965 std::string monitorTags = isClientWatched(offlineClient.get())
2966 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002967 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002968 if (err != OK) {
2969 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2970 return err;
2971 }
2972
2973 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2974 if (evicted.size() > 0) {
2975 for (auto& i : evicted) {
2976 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002977 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002978 }
2979
2980 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2981 "properly", __FUNCTION__);
2982
2983 return BAD_VALUE;
2984 }
2985
2986 logConnectedOffline(offlineClientDesc->getKey(),
2987 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002988 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002989
2990 sp<IBinder> remoteCallback = offlineClient->getRemote();
2991 if (remoteCallback != nullptr) {
2992 remoteCallback->linkToDeath(this);
2993 }
2994 } // lock is destroyed, allow further connect calls
2995
2996 return OK;
2997}
2998
Austin Borgered99f642023-06-01 16:51:35 -07002999Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +00003000 int32_t torchStrength, const sp<IBinder>& clientBinder, int32_t deviceId,
3001 int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08003002 Mutex::Autolock lock(mServiceLock);
3003
3004 ATRACE_CALL();
3005 if (clientBinder == nullptr) {
3006 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
3007 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
3008 "Torch client binder in null.");
3009 }
3010
Austin Borger22c5c852024-03-08 13:31:36 -08003011 int uid = getCallingUid();
Biswarup Pal37a75182024-01-16 15:53:35 +00003012 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
3013 devicePolicy, uid);
3014 if (!cameraIdOptional.has_value()) {
3015 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
3016 unresolvedCameraId.c_str(), deviceId);
3017 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3018 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3019 }
3020 std::string cameraId = cameraIdOptional.value();
3021
Austin Borgered99f642023-06-01 16:51:35 -07003022 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08003023 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07003024 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003025 }
3026
3027 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07003028 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08003029 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07003030 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003031 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003032 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003033 }
3034
3035 StatusInternal cameraStatus = state->getStatus();
3036 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
3037 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07003038 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08003039 (int)cameraStatus);
3040 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003041 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003042 }
3043
3044 {
3045 Mutex::Autolock al(mTorchStatusMutex);
3046 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003047 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08003048 if (err != OK) {
3049 if (err == NAME_NOT_FOUND) {
3050 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003051 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003052 }
3053 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003054 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003055 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
3056 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003057 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08003058 }
3059
3060 if (status == TorchModeStatus::NOT_AVAILABLE) {
3061 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
3062 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003063 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003064 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3065 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003066 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003067 } else {
3068 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003069 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003070 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3071 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003072 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003073 }
3074 }
3075 }
3076
3077 {
3078 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003079 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08003080 }
3081 // Check if the current torch strength level is same as the new one.
3082 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07003083 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003084
Austin Borgered99f642023-06-01 16:51:35 -07003085 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003086
3087 if (err != OK) {
3088 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003089 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08003090 switch (err) {
3091 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003092 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
3093 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003094 errorCode = ERROR_ILLEGAL_ARGUMENT;
3095 break;
3096 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003097 msg = fmt::sprintf("Camera \"%s\" is in use",
3098 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003099 errorCode = ERROR_CAMERA_IN_USE;
3100 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08003101 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07003102 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08003103 "valid range.", torchStrength);
3104 errorCode = ERROR_ILLEGAL_ARGUMENT;
3105 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08003106 default:
Austin Borgered99f642023-06-01 16:51:35 -07003107 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08003108 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08003109 }
Austin Borgered99f642023-06-01 16:51:35 -07003110 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3111 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003112 }
3113
3114 {
3115 // update the link to client's death
3116 // Store the last client that turns on each camera's torch mode.
3117 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003118 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08003119 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003120 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08003121 } else {
3122 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
3123 mTorchClientMap.replaceValueAt(index, clientBinder);
3124 }
3125 clientBinder->linkToDeath(this);
3126 }
3127
Austin Borger22c5c852024-03-08 13:31:36 -08003128 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08003129 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07003130 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08003131 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07003132 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003133 }
3134 return Status::ok();
3135}
3136
malikakash73125c62023-07-21 22:44:34 +00003137Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Biswarup Pal37a75182024-01-16 15:53:35 +00003138 const sp<IBinder>& clientBinder, int32_t deviceId, int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003139 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003140
3141 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07003142 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003143 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003144 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
3145 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003146 }
3147
Austin Borger22c5c852024-03-08 13:31:36 -08003148 int uid = getCallingUid();
Biswarup Pal37a75182024-01-16 15:53:35 +00003149 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
3150 devicePolicy, uid);
3151 if (!cameraIdOptional.has_value()) {
3152 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
3153 unresolvedCameraId.c_str(), deviceId);
3154 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3155 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3156 }
3157 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003158
Austin Borgered99f642023-06-01 16:51:35 -07003159 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003160 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07003161 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003162 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003163 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07003164 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003165 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07003166 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003167 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003168 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003169 }
3170
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003171 StatusInternal cameraStatus = state->getStatus();
3172 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003173 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07003174 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
3175 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003176 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003177 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003178 }
3179
3180 {
3181 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003182 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003183 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003184 if (err != OK) {
3185 if (err == NAME_NOT_FOUND) {
3186 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003187 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003188 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003189 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003190 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003191 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07003192 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003193 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003194 }
3195
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003196 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003197 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003198 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003199 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003200 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3201 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003202 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003203 } else {
3204 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003205 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003206 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3207 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003208 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003209 }
3210 }
3211 }
3212
Ruben Brunk99e69712015-05-26 17:25:07 -07003213 {
3214 // Update UID map - this is used in the torch status changed callbacks, so must be done
3215 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003216 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003217 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003218 }
3219
Austin Borgered99f642023-06-01 16:51:35 -07003220 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003221
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003222 if (err != OK) {
3223 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003224 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003225 switch (err) {
3226 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003227 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3228 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003229 errorCode = ERROR_ILLEGAL_ARGUMENT;
3230 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003231 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003232 msg = fmt::sprintf("Camera \"%s\" is in use",
3233 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003234 errorCode = ERROR_CAMERA_IN_USE;
3235 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003236 default:
Austin Borgered99f642023-06-01 16:51:35 -07003237 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003238 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003239 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003240 errorCode = ERROR_INVALID_OPERATION;
3241 }
Austin Borgered99f642023-06-01 16:51:35 -07003242 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3243 logServiceError(msg, errorCode);
3244 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003245 }
3246
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003247 {
3248 // update the link to client's death
3249 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003250 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003251 if (enabled) {
3252 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003253 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003254 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003255 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003256 mTorchClientMap.replaceValueAt(index, clientBinder);
3257 }
3258 clientBinder->linkToDeath(this);
3259 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003260 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003261 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003262 }
3263
Austin Borger22c5c852024-03-08 13:31:36 -08003264 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003265 std::string torchState = enabled ? "on" : "off";
3266 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3267 torchState.c_str(), clientPid);
3268 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003269 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003270}
3271
Austin Borgered99f642023-06-01 16:51:35 -07003272void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3273 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3274 mTorchUidMap[cameraId].first = uid;
3275 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003276 } else {
3277 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003278 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003279 }
3280}
3281
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003282Status CameraService::notifySystemEvent(int32_t eventId,
3283 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003284 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003285 const int selfPid = getpid();
3286
3287 // Permission checks
3288 if (pid != selfPid) {
3289 // Ensure we're being called by system_server, or similar process with
3290 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003291 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003292 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003293 ALOGE("Permission Denial: cannot send updates to camera service about system"
3294 " events from pid=%d, uid=%d", pid, uid);
3295 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003296 "No permission to send updates to camera service about system events"
3297 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003298 }
3299 }
3300
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003301 ATRACE_CALL();
3302
Ruben Brunk36597b22015-03-20 22:15:57 -07003303 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003304 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003305 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003306 // from a system server crash
3307 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003308 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003309 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003310 break;
3311 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003312 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3313 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003314 if (args.size() != 1) {
3315 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3316 "USB Device Event requires 1 argument");
3317 }
3318
Valentin Iftime29e2e152021-08-13 15:17:33 +02003319 // Notify CameraProviderManager for lazy HALs
3320 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3321 std::to_string(args[0]));
3322 break;
3323 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003324 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003325 default: {
3326 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3327 eventId);
3328 break;
3329 }
3330 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003331 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003332}
3333
Emilian Peev53722fa2019-02-22 17:47:20 -08003334void CameraService::notifyMonitoredUids() {
3335 Mutex::Autolock lock(mStatusListenerLock);
3336
3337 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003338 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003339 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3340 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003341 }
3342}
3343
Austin Borgerdddb7552023-03-30 17:53:01 -07003344void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3345 Mutex::Autolock lock(mStatusListenerLock);
3346
3347 for (const auto& it : mListenerList) {
3348 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3349 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3350 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3351 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3352 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3353 }
3354 }
3355}
3356
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003357Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003358 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003359 const int selfPid = getpid();
3360
3361 // Permission checks
3362 if (pid != selfPid) {
3363 // Ensure we're being called by system_server, or similar process with
3364 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003365 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003366 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003367 ALOGE("Permission Denial: cannot send updates to camera service about device"
3368 " state changes from pid=%d, uid=%d", pid, uid);
3369 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3370 "No permission to send updates to camera service about device state"
3371 " changes from pid=%d, uid=%d", pid, uid);
3372 }
3373 }
3374
3375 ATRACE_CALL();
3376
Austin Borger18b30a72022-10-27 12:20:29 -07003377 {
3378 Mutex::Autolock lock(mServiceLock);
3379 mDeviceState = newState;
3380 }
3381
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003382 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003383
3384 return Status::ok();
3385}
3386
Emilian Peev8b64f282021-03-25 16:49:57 -07003387Status CameraService::notifyDisplayConfigurationChange() {
3388 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003389 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003390 const int selfPid = getpid();
3391
3392 // Permission checks
3393 if (callingPid != selfPid) {
3394 // Ensure we're being called by system_server, or similar process with
3395 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003396 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003397 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003398 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3399 " changes from pid=%d, uid=%d", callingPid, uid);
3400 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3401 "No permission to send updates to camera service about orientation"
3402 " changes from pid=%d, uid=%d", callingPid, uid);
3403 }
3404 }
3405
3406 Mutex::Autolock lock(mServiceLock);
3407
3408 // Don't do anything if rotate-and-crop override via cmd is active
3409 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3410
3411 const auto clients = mActiveClientManager.getAll();
3412 for (auto& current : clients) {
3413 if (current != nullptr) {
3414 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003415 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3416 basicClient->setRotateAndCropOverride(
3417 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3418 basicClient->getPackageName(),
3419 basicClient->getCameraFacing(),
3420 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003421 }
3422 }
3423 }
3424
3425 return Status::ok();
3426}
3427
Biswarup Pal37a75182024-01-16 15:53:35 +00003428// TODO(b/291736219): This to be made device-aware.
Emilian Peev8b64f282021-03-25 16:49:57 -07003429Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003430 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3431 ATRACE_CALL();
3432 if (!concurrentCameraIds) {
3433 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3434 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3435 }
3436
3437 if (!mInitialized) {
3438 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003439 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003440 return STATUS_ERROR(ERROR_DISCONNECTED,
3441 "Camera subsystem is not available");
3442 }
3443 // First call into the provider and get the set of concurrent camera
3444 // combinations
3445 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003446 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003447 for (auto &combination : concurrentCameraCombinations) {
3448 std::vector<std::string> validCombination;
3449 for (auto &cameraId : combination) {
3450 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003451 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003452 if (state == nullptr) {
3453 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3454 continue;
3455 }
3456 StatusInternal status = state->getStatus();
3457 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3458 continue;
3459 }
Austin Borgered99f642023-06-01 16:51:35 -07003460 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003461 continue;
3462 }
3463 validCombination.push_back(cameraId);
3464 }
3465 if (validCombination.size() != 0) {
3466 concurrentCameraIds->push_back(std::move(validCombination));
3467 }
3468 }
3469 return Status::ok();
3470}
3471
3472Status CameraService::isConcurrentSessionConfigurationSupported(
3473 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003474 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003475 if (!isSupported) {
3476 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3477 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3478 }
3479
3480 if (!mInitialized) {
3481 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3482 return STATUS_ERROR(ERROR_DISCONNECTED,
3483 "Camera subsystem is not available");
3484 }
3485
3486 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003487 int callingPid = getCallingPid();
3488 int callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003489 bool hasCameraPermission = ((callingPid == getpid()) ||
3490 hasPermissionsForCamera(callingPid, callingUid));
3491 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003492 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3493 "android.permission.CAMERA needed to call"
3494 "isConcurrentSessionConfigurationSupported");
3495 }
3496
3497 status_t res =
3498 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003499 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3500 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003501 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003502 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003503 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003504 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3505 "support %s (%d)", strerror(-res), res);
3506 }
3507 return Status::ok();
3508}
3509
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003510Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3511 /*out*/
3512 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003513 return addListenerHelper(listener, cameraStatuses);
3514}
3515
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003516binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3517 std::vector<hardware::CameraStatus>* cameraStatuses) {
3518 return addListenerHelper(listener, cameraStatuses, false, true);
3519}
3520
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003521Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3522 /*out*/
3523 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003524 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003525 ATRACE_CALL();
3526
Igor Murashkinbfc99152013-02-27 12:55:20 -08003527 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003528
Ruben Brunk3450ba72015-06-16 11:00:37 -07003529 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003530 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003531 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003532 }
3533
Austin Borger22c5c852024-03-08 13:31:36 -08003534 auto clientPid = getCallingPid();
3535 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003536 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003537
Igor Murashkinbfc99152013-02-27 12:55:20 -08003538 Mutex::Autolock lock(mServiceLock);
3539
Ruben Brunkcc776712015-02-17 20:18:47 -08003540 {
3541 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003542 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003543 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003544 ALOGW("%s: Tried to add listener %p which was already subscribed",
3545 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003546 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003547 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003548 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003549
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003550 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003551 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3552 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003553 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003554 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003555 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003556 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003557 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3558 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3559 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003560 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003561 // The listener still needs to be added to the list of listeners, regardless of what
3562 // permissions the listener process has / whether it is a vendor listener. Since it might be
3563 // eligible to listen to other camera ids.
3564 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003565 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003566 }
3567
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003568 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003569 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003570 Mutex::Autolock lock(mCameraStatesLock);
3571 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003572 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3573 auto [deviceId, mappedCameraId] =
3574 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3575
3576 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003577 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003578 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3579 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003580 }
3581 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003582 // Remove the camera statuses that should be hidden from the client, we do
3583 // this after collecting the states in order to avoid holding
3584 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3585 // the same time.
3586 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3587 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003588 std::string cameraId = s.cameraId;
3589 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
3590 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM,
3591 clientUid);
3592 if (!cameraIdOptional.has_value()) {
3593 std::string msg =
3594 fmt::sprintf(
3595 "Camera %s: Invalid camera id for device id %d",
3596 s.cameraId.c_str(), s.deviceId);
3597 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3598 return true;
3599 }
3600 cameraId = cameraIdOptional.value();
3601 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3602 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3603 ALOGE("%s: Invalid camera id %s, skipping status update",
3604 __FUNCTION__, s.cameraId.c_str());
3605 return true;
3606 }
3607 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3608 clientUid);
3609 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003610
Biswarup Pal37a75182024-01-16 15:53:35 +00003611 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003612 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003613 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003614 // Add only default device cameras here, as virtual cameras currently don't support torch
3615 // anyway. Note that this is a simplification of the implementation here, and we should
3616 // change this when virtual cameras support torch.
3617 if (s.deviceId == kDefaultDeviceId) {
3618 idsChosenForCallback.insert(s.cameraId);
3619 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003620 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003621
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003622 /*
3623 * Immediately signal current torch status to this listener only
3624 * This may be a subset of all the devices, so don't include it in the response directly
3625 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003626 {
3627 Mutex::Autolock al(mTorchStatusMutex);
3628 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003629 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003630 // The camera id is visible to the client. Fine to send torch
3631 // callback.
3632 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003633 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3634 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003635 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003636 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003637 }
3638
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003639 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003640}
Ruben Brunkcc776712015-02-17 20:18:47 -08003641
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003642Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003643 ATRACE_CALL();
3644
Igor Murashkinbfc99152013-02-27 12:55:20 -08003645 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3646
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003647 if (listener == 0) {
3648 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003649 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003650 }
3651
Igor Murashkinbfc99152013-02-27 12:55:20 -08003652 Mutex::Autolock lock(mServiceLock);
3653
Ruben Brunkcc776712015-02-17 20:18:47 -08003654 {
3655 Mutex::Autolock lock(mStatusListenerLock);
3656 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003657 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003658 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003659 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003660 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003661 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003662 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003663 }
3664 }
3665
3666 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3667 __FUNCTION__, listener.get());
3668
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003669 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003670}
3671
Austin Borgered99f642023-06-01 16:51:35 -07003672Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003673
3674 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003675 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3676
3677 if (parameters == NULL) {
3678 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003679 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003680 }
3681
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003682 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003683
3684 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003685 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003686 // Error logged by caller
3687 return ret;
3688 }
3689
3690 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003691
Austin Borgered99f642023-06-01 16:51:35 -07003692 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003693
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003694 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003695}
3696
Austin Borgered99f642023-06-01 16:51:35 -07003697Status CameraService::supportsCameraApi(const std::string& unresolvedCameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003698 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003699 ATRACE_CALL();
3700
malikakashedb38962023-09-06 00:03:35 +00003701 const std::string cameraId = resolveCameraId(
Austin Borger22c5c852024-03-08 13:31:36 -08003702 unresolvedCameraId, getCallingUid());
malikakash82ed4352023-07-21 22:44:34 +00003703
Austin Borgered99f642023-06-01 16:51:35 -07003704 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003705
3706 switch (apiVersion) {
3707 case API_VERSION_1:
3708 case API_VERSION_2:
3709 break;
3710 default:
Austin Borgered99f642023-06-01 16:51:35 -07003711 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3712 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3713 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003714 }
3715
Austin Borger18b30a72022-10-27 12:20:29 -07003716 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -07003717 auto deviceVersionAndTransport = getDeviceVersion(cameraId, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003718 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003719 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3720 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3721 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003722 }
3723 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3724 int deviceVersion = deviceVersionAndTransport.first;
3725 switch (deviceVersion) {
3726 case CAMERA_DEVICE_API_VERSION_1_0:
3727 case CAMERA_DEVICE_API_VERSION_3_0:
3728 case CAMERA_DEVICE_API_VERSION_3_1:
3729 if (apiVersion == API_VERSION_2) {
3730 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003731 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003732 *isSupported = false;
3733 } else { // if (apiVersion == API_VERSION_1) {
3734 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003735 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003736 *isSupported = true;
3737 }
3738 break;
3739 case CAMERA_DEVICE_API_VERSION_3_2:
3740 case CAMERA_DEVICE_API_VERSION_3_3:
3741 case CAMERA_DEVICE_API_VERSION_3_4:
3742 case CAMERA_DEVICE_API_VERSION_3_5:
3743 case CAMERA_DEVICE_API_VERSION_3_6:
3744 case CAMERA_DEVICE_API_VERSION_3_7:
3745 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003746 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003747 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003748 break;
3749 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003750 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3751 deviceVersion, cameraId.c_str());
3752 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3753 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003754 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003755 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003756 } else {
3757 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003758 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003759 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003760}
3761
Austin Borgered99f642023-06-01 16:51:35 -07003762Status CameraService::isHiddenPhysicalCamera(const std::string& unresolvedCameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003763 /*out*/ bool *isSupported) {
3764 ATRACE_CALL();
3765
malikakashedb38962023-09-06 00:03:35 +00003766 const std::string cameraId = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08003767 getCallingUid());
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003768
Austin Borgered99f642023-06-01 16:51:35 -07003769 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3770 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003771
3772 return Status::ok();
3773}
3774
Cliff Wud8cae102021-03-11 01:37:42 +08003775Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003776 const std::string& packageName, const std::string& internalCamId,
3777 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003778 const sp<ICameraInjectionCallback>& callback,
3779 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003780 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003781 ATRACE_CALL();
3782
Austin Borgered99f642023-06-01 16:51:35 -07003783 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003784 const int pid = getCallingPid();
3785 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003786 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3787 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003788 "Permission Denial: no permission to inject camera");
3789 }
3790
3791 // Do not allow any camera injection that injects or replaces a virtual camera.
3792 auto [deviceIdForInternalCamera, _] =
3793 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3794 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3795 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3796 "Cannot replace a virtual camera");
3797 }
3798 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3799 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3800 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3801 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3802 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003803 }
3804
3805 ALOGV(
3806 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3807 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003808 __FUNCTION__, packageName.c_str(),
3809 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003810
Cliff Wud3a05312021-04-26 23:07:31 +08003811 {
3812 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003813 mInjectionInternalCamId = internalCamId;
3814 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003815 mInjectionStatusListener->addListener(callback);
3816 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003817 status_t res = NO_ERROR;
3818 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3819 // If the client already exists, we can directly connect to the camera device through the
3820 // client's injectCamera(), otherwise we need to wait until the client is established
3821 // (execute connectHelper()) before injecting the camera to the camera device.
3822 if (clientDescriptor != nullptr) {
3823 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003824 sp<BasicClient> clientSp = clientDescriptor->getValue();
3825 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3826 if(res != OK) {
3827 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3828 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003829 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003830 }
3831 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003832 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003833 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3834 }
3835 } else {
3836 mInjectionInitPending = true;
3837 }
3838 }
Cliff Wud8cae102021-03-11 01:37:42 +08003839
Cliff Wud3a05312021-04-26 23:07:31 +08003840 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003841}
3842
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003843Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003844 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003845 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3846 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3847 return Status::ok();
3848}
3849
Ruben Brunkcc776712015-02-17 20:18:47 -08003850void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003851 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003852 for (auto& i : mActiveClientManager.getAll()) {
3853 auto clientSp = i->getValue();
3854 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003855 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003856 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003857 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003858 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003859 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003860}
3861
Ruben Brunkcc776712015-02-17 20:18:47 -08003862bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003863 bool ret = false;
3864 {
3865 // Acquire mServiceLock and prevent other clients from connecting
3866 std::unique_ptr<AutoConditionLock> lock =
3867 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003868
Ruben Brunkcc776712015-02-17 20:18:47 -08003869 std::vector<sp<BasicClient>> evicted;
3870 for (auto& i : mActiveClientManager.getAll()) {
3871 auto clientSp = i->getValue();
3872 if (clientSp.get() == nullptr) {
3873 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3874 mActiveClientManager.remove(i);
3875 continue;
3876 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003877 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003878 mActiveClientManager.remove(i);
3879 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003880
Ruben Brunkcc776712015-02-17 20:18:47 -08003881 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003882 clientSp->notifyError(
3883 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003884 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003885 }
3886 }
3887
Ruben Brunkcc776712015-02-17 20:18:47 -08003888 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3889 // other clients from connecting in mServiceLockWrapper if held
3890 mServiceLock.unlock();
3891
Ruben Brunk36597b22015-03-20 22:15:57 -07003892 // Do not clear caller identity, remote caller should be client proccess
3893
Ruben Brunkcc776712015-02-17 20:18:47 -08003894 for (auto& i : evicted) {
3895 if (i.get() != nullptr) {
3896 i->disconnect();
3897 ret = true;
3898 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003899 }
3900
Ruben Brunkcc776712015-02-17 20:18:47 -08003901 // Reacquire mServiceLock
3902 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003903
Ruben Brunkcc776712015-02-17 20:18:47 -08003904 } // lock is destroyed, allow further connect calls
3905
3906 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003907}
3908
Ruben Brunkcc776712015-02-17 20:18:47 -08003909std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003910 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003911 std::shared_ptr<CameraState> state;
3912 {
3913 Mutex::Autolock lock(mCameraStatesLock);
3914 auto iter = mCameraStates.find(cameraId);
3915 if (iter != mCameraStates.end()) {
3916 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003917 }
3918 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003919 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003920}
3921
Austin Borgered99f642023-06-01 16:51:35 -07003922sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003923 // Remove from active clients list
3924 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3925 if (clientDescriptorPtr == nullptr) {
3926 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003927 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003928 return sp<BasicClient>{nullptr};
3929 }
3930
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003931 sp<BasicClient> client = clientDescriptorPtr->getValue();
3932 if (client.get() != nullptr) {
3933 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3934 }
3935 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003936}
3937
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003938void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003939 // Acquire mServiceLock and prevent other clients from connecting
3940 std::unique_ptr<AutoConditionLock> lock =
3941 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3942
Ruben Brunk6267b532015-04-30 17:44:07 -07003943 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003944 for (size_t i = 0; i < newUserIds.size(); i++) {
3945 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003946 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003947 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003948 return;
3949 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003950 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003951 }
3952
Ruben Brunka8ca9152015-04-07 14:23:40 -07003953
Ruben Brunk6267b532015-04-30 17:44:07 -07003954 if (newAllowedUsers == mAllowedUsers) {
3955 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3956 return;
3957 }
3958
3959 logUserSwitch(mAllowedUsers, newAllowedUsers);
3960
3961 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003962
3963 // Current user has switched, evict all current clients.
3964 std::vector<sp<BasicClient>> evicted;
3965 for (auto& i : mActiveClientManager.getAll()) {
3966 auto clientSp = i->getValue();
3967
3968 if (clientSp.get() == nullptr) {
3969 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3970 continue;
3971 }
3972
Ruben Brunk6267b532015-04-30 17:44:07 -07003973 // Don't evict clients that are still allowed.
3974 uid_t clientUid = clientSp->getClientUid();
3975 userid_t clientUserId = multiuser_get_user_id(clientUid);
3976 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3977 continue;
3978 }
3979
Ruben Brunk36597b22015-03-20 22:15:57 -07003980 evicted.push_back(clientSp);
3981
Ruben Brunk36597b22015-03-20 22:15:57 -07003982 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003983 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003984
Ruben Brunk36597b22015-03-20 22:15:57 -07003985 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003986 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003987 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003988 " to user switch.", i->getKey().c_str(),
3989 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003990 i->getOwnerId(), i->getPriority().getScore(),
3991 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003992
3993 }
3994
3995 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3996 // blocking other clients from connecting in mServiceLockWrapper if held.
3997 mServiceLock.unlock();
3998
3999 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08004000 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07004001
4002 for (auto& i : evicted) {
4003 i->disconnect();
4004 }
4005
Austin Borger22c5c852024-03-08 13:31:36 -08004006 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07004007
4008 // Reacquire mServiceLock
4009 mServiceLock.lock();
4010}
Ruben Brunkcc776712015-02-17 20:18:47 -08004011
Austin Borgered99f642023-06-01 16:51:35 -07004012void CameraService::logEvent(const std::string &event) {
4013 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07004014 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07004015 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07004016 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07004017 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07004018 mEventLog.add(msg);
4019 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
4020 // Error event not added to the dumpsys log before
4021 mEventLog.add(msg);
4022 sServiceErrorEventSet.insert(msg);
4023 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004024}
4025
Austin Borgered99f642023-06-01 16:51:35 -07004026void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
4027 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004028 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004029 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
4030 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004031}
4032
Austin Borgered99f642023-06-01 16:51:35 -07004033void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
4034 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004035 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004036 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
4037 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004038}
4039
Austin Borgered99f642023-06-01 16:51:35 -07004040void CameraService::logConnected(const std::string &cameraId, int clientPid,
4041 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004042 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004043 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
4044 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004045}
4046
Austin Borgered99f642023-06-01 16:51:35 -07004047void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
4048 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004049 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004050 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
4051 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004052}
4053
Austin Borgered99f642023-06-01 16:51:35 -07004054void CameraService::logRejected(const std::string &cameraId, int clientPid,
4055 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004056 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07004057 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
4058 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004059}
4060
Austin Borgered99f642023-06-01 16:51:35 -07004061void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
4062 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07004063 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07004064 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
4065 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07004066}
4067
Ruben Brunk6267b532015-04-30 17:44:07 -07004068void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
4069 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07004070 std::string newUsers = toString(newUserIds);
4071 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004072 if (oldUsers.size() == 0) {
4073 oldUsers = "<None>";
4074 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07004075 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07004076 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
4077 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004078}
4079
Austin Borgered99f642023-06-01 16:51:35 -07004080void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004081 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004082 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004083}
4084
Austin Borgered99f642023-06-01 16:51:35 -07004085void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004086 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004087 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004088}
4089
Austin Borgered99f642023-06-01 16:51:35 -07004090void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004091 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004092 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07004093}
4094
Austin Borgered99f642023-06-01 16:51:35 -07004095void CameraService::logServiceError(const std::string &msg, int errorCode) {
4096 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
4097 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004098}
4099
Ruben Brunk36597b22015-03-20 22:15:57 -07004100status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4101 uint32_t flags) {
4102
Mathias Agopian65ab4712010-07-14 17:59:35 -07004103 // Permission checks
4104 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004105 case SHELL_COMMAND_TRANSACTION: {
4106 int in = data.readFileDescriptor();
4107 int out = data.readFileDescriptor();
4108 int err = data.readFileDescriptor();
4109 int argc = data.readInt32();
4110 Vector<String16> args;
4111 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
4112 args.add(data.readString16());
4113 }
4114 sp<IBinder> unusedCallback;
4115 sp<IResultReceiver> resultReceiver;
4116 status_t status;
4117 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
4118 return status;
4119 }
4120 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
4121 return status;
4122 }
4123 status = shellCommand(in, out, err, args);
4124 if (resultReceiver != nullptr) {
4125 resultReceiver->send(status);
4126 }
4127 return NO_ERROR;
4128 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004129 }
4130
4131 return BnCameraService::onTransact(code, data, reply, flags);
4132}
4133
Mathias Agopian65ab4712010-07-14 17:59:35 -07004134// We share the media players for shutter and recording sound for all clients.
4135// A reference count is kept to determine when we will actually release the
4136// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09004137sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
4138 sp<MediaPlayer> mp = new MediaPlayer();
4139 status_t error;
4140 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08004141 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09004142 error = mp->prepare();
4143 }
4144 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004145 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09004146 mp->disconnect();
4147 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004148 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004149 }
4150 return mp;
4151}
4152
username5755fea2018-12-27 09:48:08 +08004153void CameraService::increaseSoundRef() {
4154 Mutex::Autolock lock(mSoundLock);
4155 mSoundRef++;
4156}
4157
4158void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004159 ATRACE_CALL();
4160
username5755fea2018-12-27 09:48:08 +08004161 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
4162 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
4163 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
4164 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
4165 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4166 }
4167 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
4168 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4169 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4170 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004171 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08004172 }
4173 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4174 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4175 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4176 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4177 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004178 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004179}
4180
username5755fea2018-12-27 09:48:08 +08004181void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004182 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004183 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004184 if (--mSoundRef) return;
4185
4186 for (int i = 0; i < NUM_SOUNDS; i++) {
4187 if (mSoundPlayer[i] != 0) {
4188 mSoundPlayer[i]->disconnect();
4189 mSoundPlayer[i].clear();
4190 }
4191 }
4192}
4193
4194void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004195 ATRACE_CALL();
4196
Mathias Agopian65ab4712010-07-14 17:59:35 -07004197 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004198 if (kind < 0 || kind >= NUM_SOUNDS) {
4199 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4200 return;
4201 }
4202
Mathias Agopian65ab4712010-07-14 17:59:35 -07004203 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004204 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004205 sp<MediaPlayer> player = mSoundPlayer[kind];
4206 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004207 player->seekTo(0);
4208 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004209 }
4210}
4211
4212// ----------------------------------------------------------------------------
4213
4214CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004215 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004216 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004217 const std::string& clientPackageName, bool systemNativeClient,
4218 const std::optional<std::string>& clientFeatureId,
4219 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004220 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004221 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004222 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004223 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004224 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07004225 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004226 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004227 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004228 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004229 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004230 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004231{
Austin Borger22c5c852024-03-08 13:31:36 -08004232 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004233 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004234
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004235 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004236
username5755fea2018-12-27 09:48:08 +08004237 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004238
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004239 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004240}
4241
Mathias Agopian65ab4712010-07-14 17:59:35 -07004242// tear down the client
4243CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004244 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004245 mDestructionStarted = true;
4246
username5755fea2018-12-27 09:48:08 +08004247 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004248 // unconditionally disconnect. function is idempotent
4249 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004250}
4251
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004252sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4253
Igor Murashkin634a5152013-02-20 17:15:11 -08004254CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004255 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004256 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004257 const std::string& clientPackageName, bool nativeClient,
4258 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004259 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004260 int servicePid, bool overrideToPortrait):
Austin Borger249e6592024-03-10 22:28:11 -07004261 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004262 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004263 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004264 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4265 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004266 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004267 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004268 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07004269 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004270 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004271 mRemoteBinder(remoteCallback),
4272 mOpsActive(false),
4273 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004274{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004275 if (sCameraService == nullptr) {
4276 sCameraService = cameraService;
4277 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004278
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004279 // There are 2 scenarios in which a client won't have AppOps operations
4280 // (both scenarios : native clients)
4281 // 1) It's an system native client*, the package name will be empty
4282 // and it will return from this function in the previous if condition
4283 // (This is the same as the previously existing behavior).
4284 // 2) It is a system native client, but its package name has been
4285 // modified for debugging, however it still must not use AppOps since
4286 // the package name is not a real one.
4287 //
4288 // * system native client - native client with UID < AID_APP_START. It
4289 // doesn't exclude clients not on the system partition.
4290 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004291 mAppOpsManager = std::make_unique<AppOpsManager>();
4292 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004293
Charles Chenf075f082024-03-04 23:32:55 +00004294 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004295}
4296
4297CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004298 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004299 mDestructionStarted = true;
4300}
4301
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004302binder::Status CameraService::BasicClient::disconnect() {
4303 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004304 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004305 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004306 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004307 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004308
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004309 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004310 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004311 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004312 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004313
4314 sp<IBinder> remote = getRemote();
4315 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004316 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004317 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004318
4319 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004320 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004321 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004322 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004323 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004324
Igor Murashkincba2c162013-03-20 15:56:31 -07004325 // client shouldn't be able to call into us anymore
4326 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004327
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004328 const auto& mActivityManager = getActivityManager();
4329 if (mActivityManager) {
4330 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004331 getCallingUid(),
4332 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004333 }
4334
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004335 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004336}
4337
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004338status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4339 // No dumping of clients directly over Binder,
4340 // must go through CameraService::dump
4341 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004342 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004343 return OK;
4344}
4345
Austin Borgered99f642023-06-01 16:51:35 -07004346status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004347 // Can't watch tags directly, must go through CameraService::startWatchingTags
4348 return OK;
4349}
4350
4351status_t CameraService::BasicClient::stopWatchingTags(int) {
4352 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4353 return OK;
4354}
4355
4356status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4357 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4358 return OK;
4359}
4360
Austin Borgered99f642023-06-01 16:51:35 -07004361std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004362 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004363}
4364
Emilian Peev8b64f282021-03-25 16:49:57 -07004365int CameraService::BasicClient::getCameraFacing() const {
4366 return mCameraFacing;
4367}
4368
4369int CameraService::BasicClient::getCameraOrientation() const {
4370 return mOrientation;
4371}
Ruben Brunkcc776712015-02-17 20:18:47 -08004372
4373int CameraService::BasicClient::getClientPid() const {
4374 return mClientPid;
4375}
4376
Ruben Brunk6267b532015-04-30 17:44:07 -07004377uid_t CameraService::BasicClient::getClientUid() const {
4378 return mClientUid;
4379}
4380
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004381bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4382 // Defaults to API2.
4383 return level == API_2;
4384}
4385
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004386status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004387 {
4388 Mutex::Autolock l(mAudioRestrictionLock);
4389 mAudioRestriction = mode;
4390 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004391 sCameraService->updateAudioRestriction();
4392 return OK;
4393}
4394
4395int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004396 return sCameraService->updateAudioRestriction();
4397}
4398
4399int32_t CameraService::BasicClient::getAudioRestriction() const {
4400 Mutex::Autolock l(mAudioRestrictionLock);
4401 return mAudioRestriction;
4402}
4403
4404bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4405 switch (mode) {
4406 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4407 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4408 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4409 return true;
4410 default:
4411 return false;
4412 }
4413}
4414
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004415status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4416 if (mode == AppOpsManager::MODE_ERRORED) {
4417 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004418 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004419 return PERMISSION_DENIED;
4420 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4421 // If the calling Uid is trusted (a native service), the AppOpsManager could
4422 // return MODE_IGNORED. Do not treat such case as error.
4423 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4424 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004425
4426 bool isCameraPrivacyEnabled;
4427 if (flags::camera_privacy_allowlist()) {
4428 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4429 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4430 } else {
4431 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004432 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004433 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004434 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4435 // We prefer to successfully open the camera and perform camera muting
4436 // or blocking in connectHelper as handleAppOpMode can be called before the
4437 // connection has been fully established and at that time camera muting
4438 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004439 if (!isUidActive || !isCameraPrivacyEnabled) {
4440 ALOGI("Camera %s: Access for \"%s\" has been restricted",
Austin Borgered99f642023-06-01 16:51:35 -07004441 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004442 // Return the same error as for device policy manager rejection
4443 return -EACCES;
4444 }
4445 }
4446 return OK;
4447}
4448
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004449status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004450 ATRACE_CALL();
4451
Igor Murashkine6800ce2013-03-04 17:25:57 -08004452 {
4453 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004454 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004455 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004456 if (mAppOpsManager != nullptr) {
4457 // Notify app ops that the camera is not available
4458 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004459
4460 if (flags::watch_foreground_changes()) {
4461 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4462 toString16(mClientPackageName),
4463 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4464 } else {
4465 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004466 toString16(mClientPackageName), mOpsCallback);
Austin Borgerca1e0062023-06-28 11:32:55 -07004467 }
Igor Murashkine6800ce2013-03-04 17:25:57 -08004468
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004469 // Just check for camera acccess here on open - delay startOp until
4470 // camera frames start streaming in startCameraStreamingOps
4471 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004472 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004473 status_t res = handleAppOpMode(mode);
4474 if (res != OK) {
4475 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004476 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004477 }
4478
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004479 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004480
4481 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004482 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004483
Austin Borgerdddb7552023-03-30 17:53:01 -07004484 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004485
Shuzhen Wang695044d2020-03-06 09:02:23 -08004486 // Notify listeners of camera open/close status
4487 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4488
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004489 return OK;
4490}
4491
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004492status_t CameraService::BasicClient::startCameraStreamingOps() {
4493 ATRACE_CALL();
4494
4495 if (!mOpsActive) {
4496 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4497 return INVALID_OPERATION;
4498 }
4499 if (mOpsStreaming) {
4500 ALOGV("%s: Streaming already active!", __FUNCTION__);
4501 return OK;
4502 }
4503
4504 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004505 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004506
4507 if (mAppOpsManager != nullptr) {
4508 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004509 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4510 toString16(mClientFeatureId),
4511 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004512 status_t res = handleAppOpMode(mode);
4513 if (res != OK) {
4514 return res;
4515 }
4516 }
4517
4518 mOpsStreaming = true;
4519
4520 return OK;
4521}
4522
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004523status_t CameraService::BasicClient::noteAppOp() {
4524 ATRACE_CALL();
4525
4526 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004527 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004528
4529 // noteAppOp is only used for when camera mute is not supported, in order
4530 // to trigger the sensor privacy "Unblock" dialog
4531 if (mAppOpsManager != nullptr) {
4532 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004533 toString16(mClientPackageName), toString16(mClientFeatureId),
4534 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004535 status_t res = handleAppOpMode(mode);
4536 if (res != OK) {
4537 return res;
4538 }
4539 }
4540
4541 return OK;
4542}
4543
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004544status_t CameraService::BasicClient::finishCameraStreamingOps() {
4545 ATRACE_CALL();
4546
4547 if (!mOpsActive) {
4548 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4549 return INVALID_OPERATION;
4550 }
4551 if (!mOpsStreaming) {
4552 ALOGV("%s: Streaming not active!", __FUNCTION__);
4553 return OK;
4554 }
4555
4556 if (mAppOpsManager != nullptr) {
4557 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004558 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004559 mOpsStreaming = false;
4560 }
4561
4562 return OK;
4563}
4564
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004565status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004566 ATRACE_CALL();
4567
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004568 if (mOpsStreaming) {
4569 // Make sure we've notified everyone about camera stopping
4570 finishCameraStreamingOps();
4571 }
4572
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004573 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004574 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004575 mOpsActive = false;
4576
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004577 // This function is called when a client disconnects. This should
4578 // release the camera, but actually only if it was in a proper
4579 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004580 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004581 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004582
Ruben Brunkcc776712015-02-17 20:18:47 -08004583 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004584 sCameraService->updateStatus(StatusInternal::PRESENT,
4585 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004586 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004587 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004588 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4589 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004590 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004591 mOpsCallback.clear();
4592
Austin Borgerdddb7552023-03-30 17:53:01 -07004593 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004594
Shuzhen Wang695044d2020-03-06 09:02:23 -08004595 // Notify listeners of camera open/close status
4596 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4597
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004598 return OK;
4599}
4600
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004601void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004602 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004603 if (mAppOpsManager == nullptr) {
4604 return;
4605 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004606 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004607 if (op != AppOpsManager::OP_CAMERA) {
4608 ALOGW("Unexpected app ops notification received: %d", op);
4609 return;
4610 }
4611
4612 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004613 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004614 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004615 ALOGV("checkOp returns: %d, %s ", res,
4616 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4617 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4618 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4619 "UNKNOWN");
4620
Shuzhen Wang64900852021-02-05 09:03:29 -08004621 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004622 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4623 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004624 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004625 } else if (res == AppOpsManager::MODE_IGNORED) {
4626 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004627
Austin Borgerca1e0062023-06-28 11:32:55 -07004628 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4629 // If not visible, but still active, then we want to block instead of muting the camera.
4630 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4631 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4632
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004633 bool isCameraPrivacyEnabled;
4634 if (flags::camera_privacy_allowlist()) {
4635 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4636 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4637 } else {
4638 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004639 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004640 }
4641
4642 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004643 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4644 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4645 isCameraPrivacyEnabled);
4646 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4647 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4648 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004649 if (!mUidIsTrusted) {
Austin Borgerca1e0062023-06-28 11:32:55 -07004650 if (flags::watch_foreground_changes()) {
4651 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4652 setCameraMute(true);
4653 } else {
4654 block();
4655 }
4656 } else {
4657 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4658 setCameraMute(true);
4659 } else if (!isUidActive
4660 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4661 block();
4662 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004663 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004664 }
Evan Severson09ab4002021-02-10 14:15:19 -08004665 } else if (res == AppOpsManager::MODE_ALLOWED) {
4666 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004667 }
4668}
4669
Svet Ganova453d0d2018-01-11 15:37:58 -08004670void CameraService::BasicClient::block() {
4671 ATRACE_CALL();
4672
4673 // Reset the client PID to allow server-initiated disconnect,
4674 // and to prevent further calls by client.
Austin Borger22c5c852024-03-08 13:31:36 -08004675 mClientPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004676 CaptureResultExtras resultExtras; // a dummy result (invalid)
4677 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4678 disconnect();
4679}
4680
Mathias Agopian65ab4712010-07-14 17:59:35 -07004681// ----------------------------------------------------------------------------
4682
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004683void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004684 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004685 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004686 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4687 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4688 api1ErrorCode = CAMERA_ERROR_DISABLED;
4689 }
4690 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004691 } else {
4692 ALOGE("mRemoteCallback is NULL!!");
4693 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004694}
4695
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004696// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004697binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004698 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004699 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004700}
4701
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004702bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4703 return level == API_1;
4704}
4705
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004706CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4707 mClient(client) {
4708}
4709
4710void CameraService::Client::OpsCallback::opChanged(int32_t op,
4711 const String16& packageName) {
4712 sp<BasicClient> client = mClient.promote();
4713 if (client != NULL) {
4714 client->opChanged(op, packageName);
4715 }
4716}
4717
Mathias Agopian65ab4712010-07-14 17:59:35 -07004718// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004719// UidPolicy
4720// ----------------------------------------------------------------------------
4721
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004722void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004723 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004724 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004725
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004726 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004727 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004728 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004729 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004730 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4731 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004732 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004733 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004734 if (res == OK) {
4735 mRegistered = true;
4736 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004737 } else {
4738 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004739 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004740}
4741
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004742void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004743 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004744 return;
4745 }
4746
4747 registerWithActivityManager();
4748}
4749
4750void CameraService::UidPolicy::registerSelf() {
4751 // Use check service to see if the activity service is available
4752 // If not available then register for notifications, instead of blocking
4753 // till the service is ready
4754 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004755 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004756 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004757 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004758 } else {
4759 registerWithActivityManager();
4760 }
4761}
4762
Svet Ganova453d0d2018-01-11 15:37:58 -08004763void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004764 Mutex::Autolock _l(mUidLock);
4765
Steven Moreland2f348142019-07-02 15:59:07 -07004766 mAm.unregisterUidObserver(this);
4767 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004768 mRegistered = false;
4769 mActiveUids.clear();
4770 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004771}
4772
4773void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4774 onUidIdle(uid, disabled);
4775}
4776
4777void CameraService::UidPolicy::onUidActive(uid_t uid) {
4778 Mutex::Autolock _l(mUidLock);
4779 mActiveUids.insert(uid);
4780}
4781
4782void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4783 bool deleted = false;
4784 {
4785 Mutex::Autolock _l(mUidLock);
4786 if (mActiveUids.erase(uid) > 0) {
4787 deleted = true;
4788 }
4789 }
4790 if (deleted) {
4791 sp<CameraService> service = mService.promote();
4792 if (service != nullptr) {
4793 service->blockClientsForUid(uid);
4794 }
4795 }
4796}
4797
Emilian Peev53722fa2019-02-22 17:47:20 -08004798void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004799 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004800 bool procStateChange = false;
4801 {
4802 Mutex::Autolock _l(mUidLock);
4803 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4804 mMonitoredUids[uid].procState != procState) {
4805 mMonitoredUids[uid].procState = procState;
4806 procStateChange = true;
4807 }
4808 }
4809
4810 if (procStateChange) {
4811 sp<CameraService> service = mService.promote();
4812 if (service != nullptr) {
4813 service->notifyMonitoredUids();
4814 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004815 }
4816}
4817
Austin Borgerdddb7552023-03-30 17:53:01 -07004818/**
4819 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4820 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4821 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4822 * monitoredUids. If it is revised above some other monitoredUid, signal
4823 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4824 * foreground apps in split screen - state changes will capture all other cases.
4825 */
4826void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4827 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004828 {
4829 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004830 auto it = mMonitoredUids.find(uid);
4831
4832 if (it != mMonitoredUids.end()) {
4833 if (it->second.hasCamera) {
4834 for (auto &monitoredUid : mMonitoredUids) {
4835 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004836 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004837 notifyUidSet.emplace(monitoredUid.first);
4838 }
4839 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004840 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004841 notifyUidSet.emplace(uid);
4842 } else {
4843 for (auto &monitoredUid : mMonitoredUids) {
4844 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004845 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004846 notifyUidSet.emplace(uid);
4847 }
4848 }
4849 }
4850 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004851 }
4852 }
4853
Austin Borgerdddb7552023-03-30 17:53:01 -07004854 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004855 sp<CameraService> service = mService.promote();
4856 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004857 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004858 }
4859 }
4860}
4861
Austin Borgerdddb7552023-03-30 17:53:01 -07004862/**
4863 * Register a uid for monitoring, and note whether it owns a camera.
4864 */
4865void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004866 Mutex::Autolock _l(mUidLock);
4867 auto it = mMonitoredUids.find(uid);
4868 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004869 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004870 } else {
Austin Borger65577682022-02-17 00:25:43 +00004871 MonitoredUid monitoredUid;
4872 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004873 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004874 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004875 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004876 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004877 if (res != OK) {
4878 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4879 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004880 }
4881
4882 if (openCamera) {
4883 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004884 }
4885}
4886
Austin Borgerdddb7552023-03-30 17:53:01 -07004887/**
4888 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4889 */
4890void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004891 Mutex::Autolock _l(mUidLock);
4892 auto it = mMonitoredUids.find(uid);
4893 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004894 it->second.refCount--;
4895 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004896 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004897 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004898 if (res != OK) {
4899 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4900 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004901 } else if (closeCamera) {
4902 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004903 }
4904 } else {
4905 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4906 }
4907}
4908
Austin Borgered99f642023-06-01 16:51:35 -07004909bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004910 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004911 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004912}
4913
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004914static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4915static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004916
Austin Borgered99f642023-06-01 16:51:35 -07004917bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004918 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004919 // If activity manager is unreachable, assume everything is active
4920 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004921 return true;
4922 }
4923 auto it = mOverrideUids.find(uid);
4924 if (it != mOverrideUids.end()) {
4925 return it->second;
4926 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004927 bool active = mActiveUids.find(uid) != mActiveUids.end();
4928 if (!active) {
4929 // We want active UIDs to always access camera with their first attempt since
4930 // there is no guarantee the app is robustly written and would retry getting
4931 // the camera on failure. The inverse case is not a problem as we would take
4932 // camera away soon once we get the callback that the uid is no longer active.
4933 ActivityManager am;
4934 // Okay to access with a lock held as UID changes are dispatched without
4935 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004936 int64_t startTimeMillis = 0;
4937 do {
4938 // TODO: Fix this b/109950150!
4939 // Okay this is a hack. There is a race between the UID turning active and
4940 // activity being resumed. The proper fix is very risky, so we temporary add
4941 // some polling which should happen pretty rarely anyway as the race is hard
4942 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004943 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004944 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004945 if (active) {
4946 break;
4947 }
4948 if (startTimeMillis <= 0) {
4949 startTimeMillis = uptimeMillis();
4950 }
4951 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004952 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004953 if (remainingTimeMillis <= 0) {
4954 break;
4955 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004956 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4957
4958 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004959 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004960 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004961 } while (true);
4962
Svet Ganov7b4ab782018-03-25 12:48:10 -07004963 if (active) {
4964 // Now that we found out the UID is actually active, cache that
4965 mActiveUids.insert(uid);
4966 }
4967 }
4968 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004969}
4970
Varun Shahb42f1eb2019-04-16 14:45:13 -07004971int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4972 Mutex::Autolock _l(mUidLock);
4973 return getProcStateLocked(uid);
4974}
4975
4976int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4977 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4978 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004979 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004980 }
4981 return procState;
4982}
4983
Austin Borgered99f642023-06-01 16:51:35 -07004984void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4985 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004986 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004987}
4988
Austin Borgered99f642023-06-01 16:51:35 -07004989void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004990 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004991}
4992
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004993void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4994 Mutex::Autolock _l(mUidLock);
4995 ALOGV("UidPolicy: ActivityManager has died");
4996 mRegistered = false;
4997 mActiveUids.clear();
4998}
4999
Austin Borgered99f642023-06-01 16:51:35 -07005000void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07005001 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005002 bool wasActive = false;
5003 bool isActive = false;
5004 {
5005 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07005006 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08005007 mOverrideUids.erase(uid);
5008 if (insert) {
5009 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
5010 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07005011 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08005012 }
5013 if (wasActive != isActive && !isActive) {
5014 sp<CameraService> service = mService.promote();
5015 if (service != nullptr) {
5016 service->blockClientsForUid(uid);
5017 }
5018 }
5019}
5020
5021// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08005022// SensorPrivacyPolicy
5023// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005024
5025void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
5026{
Michael Grooverd1d435a2018-12-18 17:39:42 -08005027 Mutex::Autolock _l(mSensorPrivacyLock);
5028 if (mRegistered) {
5029 return;
5030 }
Evan Severson09ab4002021-02-10 14:15:19 -08005031 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08005032 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00005033 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005034 mSpm.addToggleSensorPrivacyListener(this);
5035 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005036 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005037 if (flags::camera_privacy_allowlist()) {
5038 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
5039 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
5040 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5041 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005042 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005043 if (res == OK) {
5044 mRegistered = true;
5045 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
5046 }
5047}
5048
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005049void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
5050 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07005051 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005052 return;
5053 }
5054
5055 registerWithSensorPrivacyManager();
5056}
5057
5058void CameraService::SensorPrivacyPolicy::registerSelf() {
5059 // Use checkservice to see if the sensor_privacy service is available
5060 // If service is not available then register for notification
5061 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07005062 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005063 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07005064 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005065 } else {
5066 registerWithSensorPrivacyManager();
5067 }
5068}
5069
Michael Grooverd1d435a2018-12-18 17:39:42 -08005070void CameraService::SensorPrivacyPolicy::unregisterSelf() {
5071 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08005072 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00005073 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005074 mSpm.removeToggleSensorPrivacyListener(this);
5075 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005076 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005077 mRegistered = false;
5078 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
5079}
5080
5081bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005082 if (!mRegistered) {
5083 registerWithSensorPrivacyManager();
5084 }
5085
Michael Grooverd1d435a2018-12-18 17:39:42 -08005086 Mutex::Autolock _l(mSensorPrivacyLock);
5087 return mSensorPrivacyEnabled;
5088}
5089
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005090int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
5091 if (!mRegistered) {
5092 registerWithSensorPrivacyManager();
5093 }
5094
5095 Mutex::Autolock _l(mSensorPrivacyLock);
5096 return mCameraPrivacyState;
5097}
5098
Evan Seversond0b69922022-01-27 10:47:34 -08005099bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08005100 if (!hasCameraPrivacyFeature()) {
5101 return false;
5102 }
Evan Seversond0b69922022-01-27 10:47:34 -08005103 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08005104}
5105
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005106bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
5107 if (!hasCameraPrivacyFeature()) {
5108 return SensorPrivacyManager::DISABLED;
5109 }
5110 return mSpm.isCameraPrivacyEnabled(packageName);
5111}
5112
Evan Seversond0b69922022-01-27 10:47:34 -08005113binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005114 int toggleType, int sensor, bool enabled) {
5115 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
5116 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
5117 {
5118 Mutex::Autolock _l(mSensorPrivacyLock);
5119 mSensorPrivacyEnabled = enabled;
5120 }
5121 // if sensor privacy is enabled then block all clients from accessing the camera
5122 if (enabled) {
5123 sp<CameraService> service = mService.promote();
5124 if (service != nullptr) {
5125 service->blockAllClients();
5126 }
5127 }
5128 }
5129 return binder::Status::ok();
5130}
5131
5132binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
5133 int, int sensor, int state) {
5134 if (!flags::camera_privacy_allowlist()
5135 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
5136 return binder::Status::ok();
5137 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08005138 {
5139 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005140 mCameraPrivacyState = state;
5141 }
5142 sp<CameraService> service = mService.promote();
5143 if (!service) {
5144 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005145 }
5146 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005147 if (state == SensorPrivacyManager::ENABLED) {
5148 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08005149 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005150 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005151 }
5152 return binder::Status::ok();
5153}
5154
5155void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
5156 Mutex::Autolock _l(mSensorPrivacyLock);
5157 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
5158 mRegistered = false;
5159}
5160
Evan Severson09ab4002021-02-10 14:15:19 -08005161bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08005162 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
5163 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5164 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
5165 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5166 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08005167}
5168
Michael Grooverd1d435a2018-12-18 17:39:42 -08005169// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005170// CameraState
5171// ----------------------------------------------------------------------------
5172
Austin Borgered99f642023-06-01 16:51:35 -07005173CameraService::CameraState::CameraState(const std::string& id, int cost,
5174 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005175 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005176 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005177 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005178
5179CameraService::CameraState::~CameraState() {}
5180
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005181CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005182 Mutex::Autolock lock(mStatusLock);
5183 return mStatus;
5184}
5185
Austin Borgered99f642023-06-01 16:51:35 -07005186std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005187 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005188 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005189 return res;
5190}
5191
Ruben Brunkcc776712015-02-17 20:18:47 -08005192CameraParameters CameraService::CameraState::getShimParams() const {
5193 return mShimParams;
5194}
5195
5196void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5197 mShimParams = params;
5198}
5199
5200int CameraService::CameraState::getCost() const {
5201 return mCost;
5202}
5203
Austin Borgered99f642023-06-01 16:51:35 -07005204std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005205 return mConflicting;
5206}
5207
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005208SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5209 return mSystemCameraKind;
5210}
5211
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005212bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5213 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5214 != mPhysicalCameras.end();
5215}
5216
Austin Borgered99f642023-06-01 16:51:35 -07005217bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005218 Mutex::Autolock lock(mStatusLock);
5219 auto result = mUnavailablePhysicalIds.insert(physicalId);
5220 return result.second;
5221}
5222
Austin Borgered99f642023-06-01 16:51:35 -07005223bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005224 Mutex::Autolock lock(mStatusLock);
5225 auto count = mUnavailablePhysicalIds.erase(physicalId);
5226 return count > 0;
5227}
5228
Austin Borgered99f642023-06-01 16:51:35 -07005229void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005230 Mutex::Autolock lock(mStatusLock);
5231 mClientPackage = clientPackage;
5232}
5233
Austin Borgered99f642023-06-01 16:51:35 -07005234std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005235 Mutex::Autolock lock(mStatusLock);
5236 return mClientPackage;
5237}
5238
Ruben Brunkcc776712015-02-17 20:18:47 -08005239// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005240// ClientEventListener
5241// ----------------------------------------------------------------------------
5242
5243void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005244 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005245 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005246 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005247 if (basicClient.get() != nullptr) {
5248 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005249 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005250 static_cast<int>(basicClient->getClientUid()));
5251 }
5252}
5253
5254void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005255 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005256 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005257 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005258 if (basicClient.get() != nullptr) {
5259 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005260 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005261 static_cast<int>(basicClient->getClientUid()));
5262 }
5263}
5264
Ruben Brunk99e69712015-05-26 17:25:07 -07005265// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005266// CameraClientManager
5267// ----------------------------------------------------------------------------
5268
Ruben Brunk99e69712015-05-26 17:25:07 -07005269CameraService::CameraClientManager::CameraClientManager() {
5270 setListener(std::make_shared<ClientEventListener>());
5271}
5272
Ruben Brunkcc776712015-02-17 20:18:47 -08005273CameraService::CameraClientManager::~CameraClientManager() {}
5274
5275sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005276 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005277 auto descriptor = get(id);
5278 if (descriptor == nullptr) {
5279 return sp<BasicClient>{nullptr};
5280 }
5281 return descriptor->getValue();
5282}
5283
Austin Borgered99f642023-06-01 16:51:35 -07005284std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005285 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005286 std::ostringstream ret;
5287 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005288 bool hasAny = false;
5289 for (auto& i : all) {
5290 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005291 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005292 int32_t cost = i->getCost();
5293 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005294 int32_t score = i->getPriority().getScore();
5295 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005296 auto conflicting = i->getConflicting();
5297 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005298 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005299 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005300 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005301 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005302 uid_t clientUid = clientSp->getClientUid();
5303 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005304 }
Austin Borgered99f642023-06-01 16:51:35 -07005305 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5306 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005307
Ruben Brunk6267b532015-04-30 17:44:07 -07005308 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005309 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005310 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005311 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005312 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005313 }
5314
Austin Borgered99f642023-06-01 16:51:35 -07005315 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005316 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005317 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005318 }
Austin Borgered99f642023-06-01 16:51:35 -07005319 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005320 }
Austin Borgered99f642023-06-01 16:51:35 -07005321 if (hasAny) ret << "\n";
5322 ret << "]\n";
5323 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005324}
5325
5326CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005327 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5328 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005329 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005330
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005331 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005332 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005333
Austin Borgered99f642023-06-01 16:51:35 -07005334 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005335 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5336 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005337}
5338
5339CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005340 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005341 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005342 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005343 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005344 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5345 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005346}
5347
5348// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005349// InjectionStatusListener
5350// ----------------------------------------------------------------------------
5351
5352void CameraService::InjectionStatusListener::addListener(
5353 const sp<ICameraInjectionCallback>& callback) {
5354 Mutex::Autolock lock(mListenerLock);
5355 if (mCameraInjectionCallback) return;
5356 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5357 if (res == OK) {
5358 mCameraInjectionCallback = callback;
5359 }
5360}
5361
5362void CameraService::InjectionStatusListener::removeListener() {
5363 Mutex::Autolock lock(mListenerLock);
5364 if (mCameraInjectionCallback == nullptr) {
5365 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5366 return;
5367 }
5368 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5369 mCameraInjectionCallback = nullptr;
5370}
5371
5372void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005373 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005374 if (mCameraInjectionCallback == nullptr) {
5375 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5376 return;
5377 }
Cliff Wud3a05312021-04-26 23:07:31 +08005378
5379 switch (err) {
5380 case -ENODEV:
5381 mCameraInjectionCallback->onInjectionError(
5382 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5383 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005384 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005385 break;
5386 case -EBUSY:
5387 mCameraInjectionCallback->onInjectionError(
5388 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5389 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005390 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005391 break;
5392 case DEAD_OBJECT:
5393 mCameraInjectionCallback->onInjectionError(
5394 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5395 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005396 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005397 break;
5398 case INVALID_OPERATION:
5399 mCameraInjectionCallback->onInjectionError(
5400 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5401 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005402 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005403 break;
5404 case UNKNOWN_TRANSACTION:
5405 mCameraInjectionCallback->onInjectionError(
5406 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5407 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005408 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005409 break;
5410 default:
5411 mCameraInjectionCallback->onInjectionError(
5412 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5413 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005414 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005415 }
Cliff Wud8cae102021-03-11 01:37:42 +08005416}
5417
5418void CameraService::InjectionStatusListener::binderDied(
5419 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005420 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5421 auto parent = mParent.promote();
5422 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005423 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5424 if (clientDescriptor != nullptr) {
5425 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5426 baseClientPtr->stopInjection();
5427 }
Cliff Wu3b268182021-07-06 15:44:43 +08005428 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005429 }
5430}
5431
5432// ----------------------------------------------------------------------------
5433// CameraInjectionSession
5434// ----------------------------------------------------------------------------
5435
5436binder::Status CameraService::CameraInjectionSession::stopInjection() {
5437 Mutex::Autolock lock(mInjectionSessionLock);
5438 auto parent = mParent.promote();
5439 if (parent == nullptr) {
5440 ALOGE("CameraInjectionSession: Parent is gone");
5441 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5442 "Camera service encountered error");
5443 }
Cliff Wud3a05312021-04-26 23:07:31 +08005444
5445 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005446 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5447 if (clientDescriptor != nullptr) {
5448 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5449 res = baseClientPtr->stopInjection();
5450 if (res != OK) {
5451 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5452 " ret != NO_ERROR: %d", res);
5453 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5454 "Camera session encountered error");
5455 }
5456 }
Cliff Wu3b268182021-07-06 15:44:43 +08005457 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005458 return binder::Status::ok();
5459}
5460
5461// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005462
5463static const int kDumpLockRetries = 50;
5464static const int kDumpLockSleep = 60000;
5465
5466static bool tryLock(Mutex& mutex)
5467{
5468 bool locked = false;
5469 for (int i = 0; i < kDumpLockRetries; ++i) {
5470 if (mutex.tryLock() == NO_ERROR) {
5471 locked = true;
5472 break;
5473 }
5474 usleep(kDumpLockSleep);
5475 }
5476 return locked;
5477}
5478
Rucha Katakwardf223072021-06-15 10:21:00 -07005479void CameraService::cacheDump() {
5480 if (mMemFd != -1) {
5481 const Vector<String16> args;
5482 ATRACE_CALL();
5483 // Acquiring service lock here will avoid the deadlock since
5484 // cacheDump will not be called during the second disconnect.
5485 Mutex::Autolock lock(mServiceLock);
5486
5487 Mutex::Autolock l(mCameraStatesLock);
5488 // Start collecting the info for open sessions and store it in temp file.
5489 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005490 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005491 auto clientDescriptor = mActiveClientManager.get(cameraId);
5492 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005493 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005494 // Log the current open session info before device is disconnected.
5495 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5496 }
5497 }
5498 }
5499}
5500
Mathias Agopian65ab4712010-07-14 17:59:35 -07005501status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005502 ATRACE_CALL();
5503
Austin Borgered99f642023-06-01 16:51:35 -07005504 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005505 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005506 getCallingPid(),
5507 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005508 return NO_ERROR;
5509 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005510 bool locked = tryLock(mServiceLock);
5511 // failed to lock - CameraService is probably deadlocked
5512 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005513 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005514 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005515
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005516 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005517 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005518
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005519 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005520 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005521
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005522 if (locked) mServiceLock.unlock();
5523 return NO_ERROR;
5524 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005525 dprintf(fd, "\n== Service global info: ==\n\n");
5526 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005527 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005528 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5529 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005530 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5531 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5532 }
Austin Borgered99f642023-06-01 16:51:35 -07005533 std::string activeClientString = mActiveClientManager.toString();
5534 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5535 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005536 if (mStreamUseCaseOverrides.size() > 0) {
5537 dprintf(fd, "Active stream use case overrides:");
5538 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5539 dprintf(fd, " %" PRId64, useCaseOverride);
5540 }
5541 dprintf(fd, "\n");
5542 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005543
5544 dumpEventLog(fd);
5545
5546 bool stateLocked = tryLock(mCameraStatesLock);
5547 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005548 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005549 }
5550
Emilian Peevbd8c5032018-02-14 23:05:40 +00005551 int argSize = args.size();
5552 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005553 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005554 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005555 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005556 }
5557 break;
5558 }
5559 }
5560
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005561 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005562 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005563
Austin Borgered99f642023-06-01 16:51:35 -07005564 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005565
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005566 CameraParameters p = state.second->getShimParams();
5567 if (!p.isEmpty()) {
5568 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5569 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005570 }
5571
5572 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005573 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005574 // log the current open session info
5575 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005576 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005577 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005578 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005579
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005580 }
5581
5582 if (stateLocked) mCameraStatesLock.unlock();
5583
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005584 if (locked) mServiceLock.unlock();
5585
Emilian Peevf53f66e2017-04-11 14:29:43 +01005586 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005587
5588 dprintf(fd, "\n== Vendor tags: ==\n\n");
5589
5590 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5591 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005592 sp<VendorTagDescriptorCache> cache =
5593 VendorTagDescriptorCache::getGlobalVendorTagCache();
5594 if (cache == NULL) {
5595 dprintf(fd, "No vendor tags.\n");
5596 } else {
5597 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5598 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005599 } else {
5600 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5601 }
5602
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005603 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005604 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005605 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005606
5607 // Process dump arguments, if any
5608 int n = args.size();
5609 String16 verboseOption("-v");
5610 String16 unreachableOption("--unreachable");
5611 for (int i = 0; i < n; i++) {
5612 if (args[i] == verboseOption) {
5613 // change logging level
5614 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005615 std::string levelStr = toStdString(args[i+1]);
5616 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005617 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005618 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005619 } else if (args[i] == unreachableOption) {
5620 // Dump memory analysis
5621 // TODO - should limit be an argument parameter?
5622 UnreachableMemoryInfo info;
5623 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5624 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005625 dprintf(fd, "\n== Unable to dump unreachable memory. "
5626 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005627 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005628 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005629 std::string s = info.ToString(/*log_contents*/ true);
5630 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005631 }
5632 }
5633 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005634
5635 bool serviceLocked = tryLock(mServiceLock);
5636
5637 // Dump info from previous open sessions.
5638 // Reposition the offset to beginning of the file before reading
5639
5640 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5641 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5642 ssize_t size_read;
5643 char buf[4096];
5644 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5645 // Read data from file to a small buffer and write it to fd.
5646 write(fd, buf, size_read);
5647 if (size_read == -1) {
5648 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5649 break;
5650 }
5651 }
5652 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5653 } else {
5654 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5655 }
5656
5657 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005658 return NO_ERROR;
5659}
5660
Rucha Katakwardf223072021-06-15 10:21:00 -07005661void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005662 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005663 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005664 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005665 getFormattedCurrentTime().c_str(),
5666 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005667 dprintf(fd, " Client priority score: %d state: %d\n",
5668 clientDescriptor->getPriority().getScore(),
5669 clientDescriptor->getPriority().getState());
5670 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5671
5672 auto client = clientDescriptor->getValue();
5673 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005674 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005675
5676 client->dumpClient(fd, args);
5677}
5678
Austin Borgered99f642023-06-01 16:51:35 -07005679void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005680 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005681 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005682}
5683
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005684void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005685 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005686
5687 Mutex::Autolock l(mLogLock);
5688 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005689 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005690 }
5691
5692 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005693 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005694 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005695 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005696 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005697 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005698}
5699
Austin Borgered99f642023-06-01 16:51:35 -07005700void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005701 Mutex::Autolock lock(mLogLock);
5702 if (!isClientWatchedLocked(client)) { return; }
5703
5704 std::vector<std::string> dumpVector;
5705 client->dumpWatchedEventsToVector(dumpVector);
5706
5707 if (dumpVector.empty()) { return; }
5708
Austin Borgered99f642023-06-01 16:51:35 -07005709 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005710
Austin Borgered99f642023-06-01 16:51:35 -07005711 std::string currentTime = getFormattedCurrentTime();
5712 dumpString << "Cached @ ";
5713 dumpString << currentTime;
5714 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005715
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005716 size_t i = dumpVector.size();
5717
5718 // Store the string in reverse order (latest last)
5719 while (i > 0) {
5720 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005721 dumpString << cameraId;
5722 dumpString << ":";
5723 dumpString << client->getPackageName();
5724 dumpString << " ";
5725 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005726 }
5727
Austin Borgered99f642023-06-01 16:51:35 -07005728 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005729}
5730
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005731void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005732 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005733 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5734 if (mTorchClientMap[i] == who) {
5735 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005736 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005737 status_t res = mFlashlight->setTorchMode(cameraId, false);
5738 if (res) {
5739 ALOGE("%s: torch client died but couldn't turn off torch: "
5740 "%s (%d)", __FUNCTION__, strerror(-res), res);
5741 return;
5742 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005743 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005744 break;
5745 }
5746 }
5747}
5748
Ruben Brunkcc776712015-02-17 20:18:47 -08005749/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005750
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005751 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005752 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5753 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005754 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005755 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005756 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005757
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005758 // check torch client
5759 handleTorchClientBinderDied(who);
5760
5761 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005762 if(!evictClientIdByRemote(who)) {
5763 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005764 return;
5765 }
5766
Ruben Brunkcc776712015-02-17 20:18:47 -08005767 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5768 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005769}
5770
Austin Borgered99f642023-06-01 16:51:35 -07005771void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005772 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005773}
5774
Austin Borgered99f642023-06-01 16:51:35 -07005775void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005776 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005777 // Do not lock mServiceLock here or can get into a deadlock from
5778 // connect() -> disconnect -> updateStatus
5779
5780 auto state = getCameraState(cameraId);
5781
5782 if (state == nullptr) {
5783 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005784 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005785 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005786 }
5787
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005788 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5789 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5790 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005791 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005792 return;
5793 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005794
Biswarup Pal37a75182024-01-16 15:53:35 +00005795 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5796 CameraMetadata cameraInfo;
5797 status_t res = mCameraProviderManager->getCameraCharacteristics(
5798 cameraId, false, &cameraInfo, false);
5799 if (res != OK) {
5800 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5801 __FUNCTION__, cameraId.c_str());
5802 } else {
5803 int32_t deviceId = getDeviceId(cameraInfo);
5804 if (deviceId != kDefaultDeviceId) {
5805 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5806 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5807 static_cast<camera_metadata_enum_android_lens_facing_t>(
5808 lensFacingEntry.data.u8[0]);
5809 std::string mappedCameraId;
5810 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5811 mappedCameraId = kVirtualDeviceBackCameraId;
5812 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5813 mappedCameraId = kVirtualDeviceFrontCameraId;
5814 } else {
5815 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5816 __func__);
5817 }
5818 if (!mappedCameraId.empty()) {
5819 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5820 }
5821 }
5822 }
5823 }
5824
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005825 // Collect the logical cameras without holding mStatusLock in updateStatus
5826 // as that can lead to a deadlock(b/162192331).
5827 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005828 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005829 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005830 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005831 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005832 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005833 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5834 auto [deviceId, mappedCameraId] =
5835 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005836
Biswarup Pal37a75182024-01-16 15:53:35 +00005837 if (status != StatusInternal::ENUMERATING) {
5838 // Update torch status if it has a flash unit.
5839 Mutex::Autolock al(mTorchStatusMutex);
5840 TorchModeStatus torchStatus;
5841 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5842 NAME_NOT_FOUND) {
5843 TorchModeStatus newTorchStatus =
5844 status == StatusInternal::PRESENT ?
5845 TorchModeStatus::AVAILABLE_OFF :
5846 TorchModeStatus::NOT_AVAILABLE;
5847 if (torchStatus != newTorchStatus) {
5848 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5849 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005850 }
5851 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005852
Biswarup Pal37a75182024-01-16 15:53:35 +00005853 Mutex::Autolock lock(mStatusListenerLock);
5854 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5855 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005856
Biswarup Pal37a75182024-01-16 15:53:35 +00005857 for (auto& listener : mListenerList) {
5858 bool isVendorListener = listener->isVendorListener();
5859 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5860 listener->getListenerPid(), listener->getListenerUid())) {
5861 ALOGV("Skipping discovery callback for system-only camera device %s",
5862 cameraId.c_str());
5863 continue;
5864 }
5865
5866 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5867 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005868 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005869 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005870 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5871 ret.exceptionCode());
Biswarup Pal37a75182024-01-16 15:53:35 +00005872
5873 // Only cameras of the default device can be remapped to a different camera
5874 // (using remapCameraIds method), so do the following only if the camera is
5875 // associated with the default device.
5876 if (deviceId == kDefaultDeviceId) {
5877 // For the default device, also trigger the callbacks for cameras that were
5878 // remapped to the current cameraId for the specific package that this
5879 // listener belongs to.
5880 std::vector<std::string> remappedCameraIds =
5881 findOriginalIdsForRemappedCameraId(cameraId,
5882 listener->getListenerUid());
5883 for (auto &remappedCameraId: remappedCameraIds) {
5884 ret = listener->getListener()->onStatusChanged(
5885 mapToInterface(status), remappedCameraId, kDefaultDeviceId);
5886 listener->handleBinderStatus(ret,
5887 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
5888 __FUNCTION__, listener->getListenerUid(),
5889 listener->getListenerPid(), ret.exceptionCode());
5890 }
5891 }
malikakash82ed4352023-07-21 22:44:34 +00005892 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005893 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005894}
5895
Austin Borgered99f642023-06-01 16:51:35 -07005896void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5897 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005898 auto state = getCameraState(cameraId);
5899 if (state == nullptr) {
5900 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005901 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005902 return;
5903 }
5904 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005905 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005906 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005907 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005908 }
5909
Biswarup Pal37a75182024-01-16 15:53:35 +00005910 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5911 auto [deviceId, mappedCameraId] =
5912 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5913
Shuzhen Wang695044d2020-03-06 09:02:23 -08005914 Mutex::Autolock lock(mStatusListenerLock);
5915
5916 for (const auto& it : mListenerList) {
5917 if (!it->isOpenCloseCallbackAllowed()) {
5918 continue;
5919 }
5920
5921 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005922 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005923 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5924 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005925 } else {
Biswarup Pal37a75182024-01-16 15:53:35 +00005926 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005927 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005928
5929 it->handleBinderStatus(ret,
5930 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5931 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005932 }
5933}
5934
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005935template<class Func>
5936void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005937 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005938 std::initializer_list<StatusInternal> rejectSourceStates,
5939 Func onStatusUpdatedLocked) {
5940 Mutex::Autolock lock(mStatusLock);
5941 StatusInternal oldStatus = mStatus;
5942 mStatus = status;
5943
5944 if (oldStatus == status) {
5945 return;
5946 }
5947
5948 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005949 cameraId.c_str(), oldStatus, status);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005950
5951 if (oldStatus == StatusInternal::NOT_PRESENT &&
5952 (status != StatusInternal::PRESENT &&
5953 status != StatusInternal::ENUMERATING)) {
5954
5955 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5956 __FUNCTION__);
5957 mStatus = oldStatus;
5958 return;
5959 }
5960
5961 /**
5962 * Sometimes we want to conditionally do a transition.
5963 * For example if a client disconnects, we want to go to PRESENT
5964 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5965 */
5966 for (auto& rejectStatus : rejectSourceStates) {
5967 if (oldStatus == rejectStatus) {
5968 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005969 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005970 mStatus = oldStatus;
5971 return;
5972 }
5973 }
5974
5975 onStatusUpdatedLocked(cameraId, status);
5976}
5977
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005978status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005979 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005980 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005981 if (!status) {
5982 return BAD_VALUE;
5983 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005984 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5985 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005986 // invalid camera ID or the camera doesn't have a flash unit
5987 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005988 }
5989
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005990 *status = mTorchStatusMap.valueAt(index);
5991 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005992}
5993
Austin Borgered99f642023-06-01 16:51:35 -07005994status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005995 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005996 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5997 if (index == NAME_NOT_FOUND) {
5998 return BAD_VALUE;
5999 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006000 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006001
6002 return OK;
6003}
6004
Austin Borgered99f642023-06-01 16:51:35 -07006005std::list<std::string> CameraService::getLogicalCameras(
6006 const std::string& physicalCameraId) {
6007 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08006008 Mutex::Autolock lock(mCameraStatesLock);
6009 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07006010 if (state.second->containsPhysicalCamera(physicalCameraId)) {
6011 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08006012 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006013 }
6014 return retList;
6015}
6016
6017void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07006018 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00006019 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006020 // mStatusListenerLock is expected to be locked
6021 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08006022 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006023 // Note: we check only the deviceKind of the physical camera id
6024 // since, logical camera ids and their physical camera ids are
6025 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07006026 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
6027 listener->getListenerPid(), listener->getListenerUid())) {
6028 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07006029 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07006030 continue;
6031 }
Austin Borgere8e2c422022-05-12 13:45:24 -07006032 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00006033 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07006034 listener->handleBinderStatus(ret,
6035 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
6036 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
6037 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08006038 }
6039 }
6040}
6041
Svet Ganova453d0d2018-01-11 15:37:58 -08006042void CameraService::blockClientsForUid(uid_t uid) {
6043 const auto clients = mActiveClientManager.getAll();
6044 for (auto& current : clients) {
6045 if (current != nullptr) {
6046 const auto basicClient = current->getValue();
6047 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
6048 basicClient->block();
6049 }
6050 }
6051 }
6052}
6053
Michael Grooverd1d435a2018-12-18 17:39:42 -08006054void CameraService::blockAllClients() {
6055 const auto clients = mActiveClientManager.getAll();
6056 for (auto& current : clients) {
6057 if (current != nullptr) {
6058 const auto basicClient = current->getValue();
6059 if (basicClient.get() != nullptr) {
6060 basicClient->block();
6061 }
6062 }
6063 }
6064}
6065
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00006066void CameraService::blockPrivacyEnabledClients() {
6067 const auto clients = mActiveClientManager.getAll();
6068 for (auto& current : clients) {
6069 if (current != nullptr) {
6070 const auto basicClient = current->getValue();
6071 if (basicClient.get() != nullptr) {
6072 std::string pkgName = basicClient->getPackageName();
6073 bool cameraPrivacyEnabled =
6074 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
6075 if (cameraPrivacyEnabled) {
6076 basicClient->block();
6077 }
6078 }
6079 }
6080 }
6081}
6082
Svet Ganova453d0d2018-01-11 15:37:58 -08006083// NOTE: This is a remote API - make sure all args are validated
6084status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006085 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006086 return PERMISSION_DENIED;
6087 }
6088 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
6089 return BAD_VALUE;
6090 }
Austin Borgered99f642023-06-01 16:51:35 -07006091 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006092 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006093 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006094 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006095 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006096 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07006097 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006098 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07006099 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006100 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07006101 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006102 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07006103 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006104 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07006105 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006106 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07006107 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006108 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07006109 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006110 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07006111 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006112 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07006113 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006114 handleClearStreamUseCaseOverrides();
6115 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07006116 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006117 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07006118 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006119 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07006120 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00006121 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07006122 } else if (args.size() >= 4 && args[0] == toString16("remap-camera-id")) {
malikakash82ed4352023-07-21 22:44:34 +00006123 return handleCameraIdRemapping(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006124 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006125 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006126 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08006127 }
6128 printHelp(err);
6129 return BAD_VALUE;
6130}
6131
malikakash82ed4352023-07-21 22:44:34 +00006132status_t CameraService::handleCameraIdRemapping(const Vector<String16>& args, int err) {
6133 uid_t uid = IPCThreadState::self()->getCallingUid();
6134 if (uid != AID_ROOT) {
6135 dprintf(err, "Must be adb root\n");
6136 return PERMISSION_DENIED;
6137 }
6138 if (args.size() != 4) {
6139 dprintf(err, "Expected format: remap-camera-id <PACKAGE> <Id0> <Id1>\n");
6140 return BAD_VALUE;
6141 }
Austin Borgered99f642023-06-01 16:51:35 -07006142 std::string packageName = toStdString(args[1]);
6143 std::string cameraIdToReplace = toStdString(args[2]);
6144 std::string cameraIdNew = toStdString(args[3]);
malikakash82ed4352023-07-21 22:44:34 +00006145 remapCameraIds({{packageName, {{cameraIdToReplace, cameraIdNew}}}});
6146 return OK;
6147}
6148
Svet Ganova453d0d2018-01-11 15:37:58 -08006149status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006150 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006151
Svet Ganova453d0d2018-01-11 15:37:58 -08006152 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07006153 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006154 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07006155 } else if ((args[2] != toString16("idle"))) {
6156 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08006157 return BAD_VALUE;
6158 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006159
6160 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006161 if (args.size() >= 5 && args[3] == toString16("--user")) {
6162 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006163 }
6164
6165 uid_t uid;
6166 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
6167 return BAD_VALUE;
6168 }
6169
6170 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08006171 return NO_ERROR;
6172}
6173
6174status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006175 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006176
6177 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006178 if (args.size() >= 4 && args[2] == toString16("--user")) {
6179 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006180 }
6181
6182 uid_t uid;
6183 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006184 return BAD_VALUE;
6185 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006186
6187 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08006188 return NO_ERROR;
6189}
6190
6191status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006192 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006193
6194 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006195 if (args.size() >= 4 && args[2] == toString16("--user")) {
6196 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006197 }
6198
6199 uid_t uid;
6200 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006201 return BAD_VALUE;
6202 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006203
6204 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006205 return dprintf(out, "active\n");
6206 } else {
6207 return dprintf(out, "idle\n");
6208 }
6209}
6210
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006211status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006212 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006213 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
6214 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
6215 Mutex::Autolock lock(mServiceLock);
6216
6217 mOverrideRotateAndCropMode = rotateValue;
6218
6219 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6220
6221 const auto clients = mActiveClientManager.getAll();
6222 for (auto& current : clients) {
6223 if (current != nullptr) {
6224 const auto basicClient = current->getValue();
6225 if (basicClient.get() != nullptr) {
6226 basicClient->setRotateAndCropOverride(rotateValue);
6227 }
6228 }
6229 }
6230
6231 return OK;
6232}
6233
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006234status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6235 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006236 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006237 if ((*end != '\0') ||
6238 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6239 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6240 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6241 return BAD_VALUE;
6242 }
6243
6244 Mutex::Autolock lock(mServiceLock);
6245 mOverrideAutoframingMode = autoframingValue;
6246
6247 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6248
6249 const auto clients = mActiveClientManager.getAll();
6250 for (auto& current : clients) {
6251 if (current != nullptr) {
6252 const auto basicClient = current->getValue();
6253 if (basicClient.get() != nullptr) {
6254 basicClient->setAutoframingOverride(autoframingValue);
6255 }
6256 }
6257 }
6258
6259 return OK;
6260}
6261
Ravneetaeb20dc2022-03-30 05:33:03 +00006262status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006263 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006264
6265 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6266
6267 Mutex::Autolock lock(mServiceLock);
6268
6269 mCameraServiceWatchdogEnabled = enableWatchdog;
6270
6271 const auto clients = mActiveClientManager.getAll();
6272 for (auto& current : clients) {
6273 if (current != nullptr) {
6274 const auto basicClient = current->getValue();
6275 if (basicClient.get() != nullptr) {
6276 basicClient->setCameraServiceWatchdog(enableWatchdog);
6277 }
6278 }
6279 }
6280
6281 return OK;
6282}
6283
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006284status_t CameraService::handleGetRotateAndCrop(int out) {
6285 Mutex::Autolock lock(mServiceLock);
6286
6287 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6288}
6289
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006290status_t CameraService::handleGetAutoframing(int out) {
6291 Mutex::Autolock lock(mServiceLock);
6292
6293 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6294}
6295
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006296status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6297 char *endPtr;
6298 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006299 std::string maskString = toStdString(args[1]);
6300 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006301
6302 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006303 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006304 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6305
6306 Mutex::Autolock lock(mServiceLock);
6307
6308 mImageDumpMask = maskValue;
6309
6310 return OK;
6311}
6312
6313status_t CameraService::handleGetImageDumpMask(int out) {
6314 Mutex::Autolock lock(mServiceLock);
6315
6316 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6317}
6318
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006319status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006320 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006321 if (errno != 0) return BAD_VALUE;
6322
6323 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6324 Mutex::Autolock lock(mServiceLock);
6325
6326 mOverrideCameraMuteMode = (muteValue == 1);
6327
6328 const auto clients = mActiveClientManager.getAll();
6329 for (auto& current : clients) {
6330 if (current != nullptr) {
6331 const auto basicClient = current->getValue();
6332 if (basicClient.get() != nullptr) {
6333 if (basicClient->supportsCameraMute()) {
6334 basicClient->setCameraMute(mOverrideCameraMuteMode);
6335 }
6336 }
6337 }
6338 }
6339
6340 return OK;
6341}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006342
Shuzhen Wang16610a62022-12-15 22:38:07 -08006343status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6344 std::vector<int64_t> useCasesOverride;
6345 for (size_t i = 1; i < args.size(); i++) {
6346 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006347 std::string arg = toStdString(args[i]);
6348 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006349 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006350 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006351 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006352 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006353 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006354 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006355 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006356 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006357 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006358 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006359 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006360 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006361 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6362 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006363 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006364 return BAD_VALUE;
6365 }
6366 useCasesOverride.push_back(useCase);
6367 }
6368
6369 Mutex::Autolock lock(mServiceLock);
6370 mStreamUseCaseOverrides = std::move(useCasesOverride);
6371
6372 return OK;
6373}
6374
6375void CameraService::handleClearStreamUseCaseOverrides() {
6376 Mutex::Autolock lock(mServiceLock);
6377 mStreamUseCaseOverrides.clear();
6378}
6379
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006380status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6381 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006382 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006383 if ((*end != '\0') ||
6384 (zoomOverrideValue != -1 &&
6385 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6386 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6387 return BAD_VALUE;
6388 }
6389
6390 Mutex::Autolock lock(mServiceLock);
6391 mZoomOverrideValue = zoomOverrideValue;
6392
6393 const auto clients = mActiveClientManager.getAll();
6394 for (auto& current : clients) {
6395 if (current != nullptr) {
6396 const auto basicClient = current->getValue();
6397 if (basicClient.get() != nullptr) {
6398 if (basicClient->supportsZoomOverride()) {
6399 basicClient->setZoomOverride(mZoomOverrideValue);
6400 }
6401 }
6402 }
6403 }
6404
6405 return OK;
6406}
6407
Avichal Rakesh84147132021-11-11 17:47:11 -08006408status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006409 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006410 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006411 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006412 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006413 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006414 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006415 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006416 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006417 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006418 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006419 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006420 dprintf(outFd, "Camera service watch commands:\n"
6421 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6422 " starts watching the provided tags for clients with provided package\n"
6423 " recognizes tag shorthands like '3a'\n"
6424 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006425 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006426 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006427 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006428 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006429 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006430 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006431 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006432}
6433
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006434status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6435 Mutex::Autolock lock(mLogLock);
6436 size_t tagsIdx; // index of '-m'
6437 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006438 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006439 if (tagsIdx < args.size() - 1) {
6440 tags = args[tagsIdx + 1];
6441 } else {
6442 dprintf(outFd, "No tags provided.\n");
6443 return BAD_VALUE;
6444 }
6445
6446 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006447 // watch all clients if no clients are provided
6448 String16 clients = toString16(kWatchAllClientsFlag);
6449 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006450 clientsIdx++);
6451 if (clientsIdx < args.size() - 1) {
6452 clients = args[clientsIdx + 1];
6453 }
Austin Borgered99f642023-06-01 16:51:35 -07006454 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006455
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006456 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006457 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006458
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006459 bool serviceLock = tryLock(mServiceLock);
6460 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006461 auto cameraClients = mActiveClientManager.getAll();
6462 for (const auto &clientDescriptor: cameraClients) {
6463 if (clientDescriptor == nullptr) { continue; }
6464 sp<BasicClient> client = clientDescriptor->getValue();
6465 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006466
6467 if (isClientWatchedLocked(client.get())) {
6468 client->startWatchingTags(mMonitorTags, outFd);
6469 numWatchedClients++;
6470 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006471 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006472 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6473
6474 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006475 return OK;
6476}
6477
6478status_t CameraService::stopWatchingTags(int outFd) {
6479 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006480 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006481 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006482
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006483 mWatchedClientPackages.clear();
6484 mWatchedClientsDumpCache.clear();
6485
6486 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006487 auto cameraClients = mActiveClientManager.getAll();
6488 for (const auto &clientDescriptor : cameraClients) {
6489 if (clientDescriptor == nullptr) { continue; }
6490 sp<BasicClient> client = clientDescriptor->getValue();
6491 if (client.get() == nullptr) { continue; }
6492 client->stopWatchingTags(outFd);
6493 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006494 dprintf(outFd, "Stopped watching all clients.\n");
6495 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006496 return OK;
6497}
6498
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006499status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6500 Mutex::Autolock lock(mLogLock);
6501 size_t clearedSize = mWatchedClientsDumpCache.size();
6502 mWatchedClientsDumpCache.clear();
6503 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6504 return OK;
6505}
6506
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006507status_t CameraService::printWatchedTags(int outFd) {
6508 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006509 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006510
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006511 bool printedSomething = false; // tracks if any monitoring information was printed
6512 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006513
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006514 bool serviceLock = tryLock(mServiceLock);
6515 // get all watched clients that are currently connected
6516 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6517 if (clientDescriptor == nullptr) { continue; }
6518
6519 sp<BasicClient> client = clientDescriptor->getValue();
6520 if (client.get() == nullptr) { continue; }
6521 if (!isClientWatchedLocked(client.get())) { continue; }
6522
6523 std::vector<std::string> dumpVector;
6524 client->dumpWatchedEventsToVector(dumpVector);
6525
6526 size_t printIdx = dumpVector.size();
6527 if (printIdx == 0) {
6528 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006529 }
6530
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006531 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006532 const std::string &cameraId = clientDescriptor->getKey();
6533 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006534 while(printIdx > 0) {
6535 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006536 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006537 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006538 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006539 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006540 printedSomething = true;
6541
6542 connectedMonitoredClients.emplace(client->getPackageName());
6543 }
6544 if (serviceLock) { mServiceLock.unlock(); }
6545
6546 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6547 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006548 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006549 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6550 continue;
6551 }
6552
Austin Borgered99f642023-06-01 16:51:35 -07006553 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006554 dprintf(outFd, "%s\n", kv.second.c_str());
6555 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006556 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006557
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006558 if (!printedSomething) {
6559 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006560 }
6561
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006562 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006563}
6564
Avichal Rakesh84147132021-11-11 17:47:11 -08006565// Print all events in vector `events' that came after lastPrintedEvent
6566void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006567 const std::string &cameraId,
6568 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006569 const std::vector<std::string> &events,
6570 const std::string &lastPrintedEvent) {
6571 if (events.empty()) { return; }
6572
6573 // index of lastPrintedEvent in events.
6574 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6575 size_t lastPrintedIdx;
6576 for (lastPrintedIdx = 0;
6577 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6578 lastPrintedIdx++);
6579
6580 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6581
Avichal Rakesh84147132021-11-11 17:47:11 -08006582 // print events in chronological order (latest event last)
6583 size_t idxToPrint = lastPrintedIdx;
6584 do {
6585 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006586 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6587 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006588 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006589}
6590
6591// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6592// command should be interrupted if the user presses the return key, or if user loses any way to
6593// signal interrupt.
6594// If timeoutMs == 0, this function will always return false
6595bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6596 struct timeval startTime;
6597 int startTimeError = gettimeofday(&startTime, nullptr);
6598 if (startTimeError) {
6599 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6600 return true;
6601 }
6602
6603 const nfds_t numFds = 1;
6604 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6605
6606 struct timeval currTime;
6607 char buffer[2];
6608 while(true) {
6609 int currTimeError = gettimeofday(&currTime, nullptr);
6610 if (currTimeError) {
6611 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6612 return true;
6613 }
6614
6615 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6616 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6617 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6618
6619 if (remainingTimeMs <= 0) {
6620 // No user interrupt within timeoutMs, don't interrupt watch command
6621 return false;
6622 }
6623
6624 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6625 if (numFdsUpdated < 0) {
6626 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6627 return true;
6628 }
6629
6630 if (numFdsUpdated == 0) {
6631 // No user input within timeoutMs, don't interrupt watch command
6632 return false;
6633 }
6634
6635 if (!(pollFd.revents & POLLIN)) {
6636 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6637 return true;
6638 }
6639
6640 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6641 if (sizeRead < 0) {
6642 dprintf(outFd, "Error reading user input. Exiting.\n");
6643 return true;
6644 }
6645
6646 if (sizeRead == 0) {
6647 // Reached end of input fd (can happen if input is piped)
6648 // User has no way to signal an interrupt, so interrupt here
6649 return true;
6650 }
6651
6652 if (buffer[0] == '\n') {
6653 // User pressed return, interrupt watch command.
6654 return true;
6655 }
6656 }
6657}
6658
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006659status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6660 int inFd, int outFd) {
6661 // Figure out refresh interval, if present in args
6662 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006663 if (args.size() > 2) {
6664 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006665 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006666 intervalIdx++);
6667
6668 size_t intervalValIdx = intervalIdx + 1;
6669 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006670 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006671 if (errno) { return BAD_VALUE; }
6672 }
6673 }
6674
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006675 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6676 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006677
Avichal Rakesh84147132021-11-11 17:47:11 -08006678 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006679 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006680
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006681 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006682 bool serviceLock = tryLock(mServiceLock);
6683 auto cameraClients = mActiveClientManager.getAll();
6684 if (serviceLock) { mServiceLock.unlock(); }
6685
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006686 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006687 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006688 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006689
6690 sp<BasicClient> client = clientDescriptor->getValue();
6691 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006692 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006693
Austin Borgered99f642023-06-01 16:51:35 -07006694 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006695 // This also initializes the map entries with an empty string
6696 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6697
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006698 std::vector<std::string> latestEvents;
6699 client->dumpWatchedEventsToVector(latestEvents);
6700
6701 if (!latestEvents.empty()) {
6702 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006703 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006704 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006705 latestEvents,
6706 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006707 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006708 }
6709 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006710 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006711 break;
6712 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006713 }
6714 return OK;
6715}
6716
Austin Borgered99f642023-06-01 16:51:35 -07006717void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006718 mWatchedClientPackages.clear();
6719
Austin Borgered99f642023-06-01 16:51:35 -07006720 std::istringstream iss(clients);
6721 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006722
Austin Borgered99f642023-06-01 16:51:35 -07006723 while (std::getline(iss, nextClient, ',')) {
6724 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006725 // Don't need to track any other package if 'all' is present
6726 mWatchedClientPackages.clear();
6727 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6728 break;
6729 }
6730
6731 // track package names
6732 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006733 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006734}
6735
Svet Ganova453d0d2018-01-11 15:37:58 -08006736status_t CameraService::printHelp(int out) {
6737 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006738 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6739 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6740 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006741 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6742 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6743 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006744 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6745 " Valid values 0=false, 1=true, 2=auto\n"
6746 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006747 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6748 " Valid values 0=OFF, 1=ON for JPEG\n"
6749 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006750 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006751 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6752 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6753 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6754 " on. In case the number of usecases is smaller than the number of streams, the\n"
6755 " last use case is assigned to all the remaining streams. In case of multiple\n"
6756 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6757 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6758 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6759 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006760 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6761 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006762 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6763 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006764 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
malikakash73125c62023-07-21 22:44:34 +00006765 " remap-camera-id <PACKAGE> <Id0> <Id1> remaps camera ids. Must use adb root\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006766 " help print this message\n");
6767}
6768
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006769bool CameraService::isClientWatched(const BasicClient *client) {
6770 Mutex::Autolock lock(mLogLock);
6771 return isClientWatchedLocked(client);
6772}
6773
6774bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6775 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6776 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6777}
6778
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006779int32_t CameraService::updateAudioRestriction() {
6780 Mutex::Autolock lock(mServiceLock);
6781 return updateAudioRestrictionLocked();
6782}
6783
6784int32_t CameraService::updateAudioRestrictionLocked() {
6785 int32_t mode = 0;
6786 // iterate through all active client
6787 for (const auto& i : mActiveClientManager.getAll()) {
6788 const auto clientSp = i->getValue();
6789 mode |= clientSp->getAudioRestriction();
6790 }
6791
6792 bool modeChanged = (mAudioRestriction != mode);
6793 mAudioRestriction = mode;
6794 if (modeChanged) {
6795 mAppOps.setCameraAudioRestriction(mode);
6796 }
6797 return mode;
6798}
6799
Austin Borgered99f642023-06-01 16:51:35 -07006800status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006801 sp<BasicClient> clientSp) {
6802 std::unique_ptr<AutoConditionLock> lock =
6803 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6804 status_t res = NO_ERROR;
6805 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006806 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006807 mInjectionStatusListener->notifyInjectionError(
6808 externalCamId, UNKNOWN_TRANSACTION);
6809 clientSp->notifyError(
6810 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6811 CaptureResultExtras());
6812
6813 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6814 // other clients from connecting in mServiceLockWrapper if held
6815 mServiceLock.unlock();
6816
6817 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006818 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006819 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006820 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006821
6822 // Reacquire mServiceLock
6823 mServiceLock.lock();
6824 }
6825
6826 return res;
6827}
6828
Cliff Wud3a05312021-04-26 23:07:31 +08006829void CameraService::clearInjectionParameters() {
6830 {
6831 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006832 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006833 mInjectionInternalCamId = "";
6834 }
6835 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006836 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006837}
6838
Biswarup Pal37a75182024-01-16 15:53:35 +00006839} // namespace android