blob: 04840b15b1c0880fc074de221d054ea97803bde0 [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;
Biswarup Pale506e732024-03-27 13:46:20 +00001135 // Get the device id that owns this camera.
1136 auto [cameraOwnerDeviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1137 cameraId);
1138 bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid,
1139 cameraOwnerDeviceId);
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001140 if (hasCameraPermission) {
1141 // Caller has camera permission; no need to remove keys
1142 return Status::ok();
1143 }
1144
1145 status_t ret = metadata->removePermissionEntries(
1146 mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1147 if (ret != OK) {
1148 metadata->clear();
1149 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1150 "Failed to remove camera characteristics needing camera permission "
1151 "for device %s:%s (%d)",
1152 cameraId.c_str(), strerror(-ret), ret);
1153 }
1154
1155 if (!tagsRemoved.empty()) {
1156 ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1157 tagsRemoved.data(), tagsRemoved.size());
1158 if (ret != OK) {
1159 metadata->clear();
1160 return STATUS_ERROR_FMT(
1161 ERROR_INVALID_OPERATION,
1162 "Failed to insert camera keys needing permission for device %s: %s (%d)",
1163 cameraId.c_str(), strerror(-ret), ret);
1164 }
1165 }
1166 return Status::ok();
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001167}
1168
malikakash82ed4352023-07-21 22:44:34 +00001169Status CameraService::parseCameraIdRemapping(
1170 const hardware::CameraIdRemapping& cameraIdRemapping,
malikakash214f6e62023-08-10 23:50:56 +00001171 /* out */ TCameraIdRemapping* cameraIdRemappingMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001172 std::string packageName;
1173 std::string cameraIdToReplace, updatedCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001174 for (const auto& packageIdRemapping: cameraIdRemapping.packageIdRemappings) {
malikakash82ed4352023-07-21 22:44:34 +00001175 packageName = packageIdRemapping.packageName;
malikakash0894f5b2023-08-10 22:46:47 +00001176 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001177 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1178 "CameraIdRemapping: Package name cannot be empty");
1179 }
malikakash214f6e62023-08-10 23:50:56 +00001180 if (packageIdRemapping.cameraIdsToReplace.size()
1181 != packageIdRemapping.updatedCameraIds.size()) {
malikakash82ed4352023-07-21 22:44:34 +00001182 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1183 "CameraIdRemapping: Mismatch in CameraId Remapping lists sizes for package %s",
malikakash73125c62023-07-21 22:44:34 +00001184 packageName.c_str());
malikakash82ed4352023-07-21 22:44:34 +00001185 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001186 for (size_t i = 0; i < packageIdRemapping.cameraIdsToReplace.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -07001187 cameraIdToReplace = packageIdRemapping.cameraIdsToReplace[i];
1188 updatedCameraId = packageIdRemapping.updatedCameraIds[i];
malikakash0894f5b2023-08-10 22:46:47 +00001189 if (cameraIdToReplace.empty() || updatedCameraId.empty()) {
malikakash214f6e62023-08-10 23:50:56 +00001190 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1191 "CameraIdRemapping: Camera Id cannot be empty for package %s",
Austin Borgered99f642023-06-01 16:51:35 -07001192 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001193 }
1194 if (cameraIdToReplace == updatedCameraId) {
1195 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1196 "CameraIdRemapping: CameraIdToReplace cannot be the same"
1197 " as updatedCameraId for %s",
Austin Borgered99f642023-06-01 16:51:35 -07001198 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001199 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001200
1201 // Do not allow any camera remapping that involves a virtual camera.
1202 auto [deviceIdForCameraToReplace, _] =
1203 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1204 cameraIdToReplace);
1205 if (deviceIdForCameraToReplace != kDefaultDeviceId) {
1206 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1207 "CameraIdRemapping: CameraIdToReplace cannot be a virtual camera");
1208 }
1209 [[maybe_unused]] auto [deviceIdForUpdatedCamera, unusedMappedCameraId] =
1210 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(updatedCameraId);
1211 if (deviceIdForUpdatedCamera != kDefaultDeviceId) {
1212 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1213 "CameraIdRemapping: UpdatedCameraId cannot be a virtual camera");
1214 }
1215
malikakash214f6e62023-08-10 23:50:56 +00001216 (*cameraIdRemappingMap)[packageName][cameraIdToReplace] = updatedCameraId;
malikakash82ed4352023-07-21 22:44:34 +00001217 }
1218 }
1219 return Status::ok();
1220}
1221
1222void CameraService::remapCameraIds(const TCameraIdRemapping& cameraIdRemapping) {
1223 // Acquire mServiceLock and prevent other clients from connecting
1224 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1225 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1226
malikakashedb38962023-09-06 00:03:35 +00001227 // Collect all existing clients for camera Ids that are being
1228 // remapped in the new cameraIdRemapping, but only if they were being used by a
1229 // targeted packageName.
malikakash82ed4352023-07-21 22:44:34 +00001230 std::vector<sp<BasicClient>> clientsToDisconnect;
Austin Borgered99f642023-06-01 16:51:35 -07001231 std::vector<std::string> cameraIdsToUpdate;
malikakash82ed4352023-07-21 22:44:34 +00001232 for (const auto& [packageName, injectionMap] : cameraIdRemapping) {
1233 for (auto& [id0, id1] : injectionMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001234 ALOGI("%s: UPDATE:= %s: %s: %s", __FUNCTION__, packageName.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001235 id0.c_str(), id1.c_str());
1236 auto clientDescriptor = mActiveClientManager.get(id0);
1237 if (clientDescriptor != nullptr) {
1238 sp<BasicClient> clientSp = clientDescriptor->getValue();
1239 if (clientSp->getPackageName() == packageName) {
malikakashedb38962023-09-06 00:03:35 +00001240 // This camera is being used by a targeted packageName and
1241 // being remapped to a new camera Id. We should disconnect it.
malikakash82ed4352023-07-21 22:44:34 +00001242 clientsToDisconnect.push_back(clientSp);
1243 cameraIdsToUpdate.push_back(id0);
1244 }
1245 }
1246 }
1247 }
1248
malikakashedb38962023-09-06 00:03:35 +00001249 for (auto& clientSp : clientsToDisconnect) {
malikakashf4c80f22023-09-25 21:50:28 +00001250 // Notify the clients about the disconnection.
1251 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
malikakashedb38962023-09-06 00:03:35 +00001252 CaptureResultExtras{});
1253 }
malikakash82ed4352023-07-21 22:44:34 +00001254
1255 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1256 // blocking other clients from connecting in mServiceLockWrapper if held.
1257 mServiceLock.unlock();
1258
malikakashedb38962023-09-06 00:03:35 +00001259 // Clear calling identity for disconnect() PID checks.
Austin Borger22c5c852024-03-08 13:31:36 -08001260 int64_t token = clearCallingIdentity();
malikakashedb38962023-09-06 00:03:35 +00001261
malikakash82ed4352023-07-21 22:44:34 +00001262 // Disconnect clients.
1263 for (auto& clientSp : clientsToDisconnect) {
malikakashedb38962023-09-06 00:03:35 +00001264 // This also triggers a call to updateStatus() which also reads mCameraIdRemapping
1265 // and requires mCameraIdRemappingLock.
malikakash82ed4352023-07-21 22:44:34 +00001266 clientSp->disconnect();
1267 }
1268
malikakashedb38962023-09-06 00:03:35 +00001269 // Invoke destructors (which call disconnect()) now while we don't hold the mServiceLock.
1270 clientsToDisconnect.clear();
1271
Austin Borger22c5c852024-03-08 13:31:36 -08001272 restoreCallingIdentity(token);
malikakash82ed4352023-07-21 22:44:34 +00001273 mServiceLock.lock();
malikakashedb38962023-09-06 00:03:35 +00001274
1275 {
1276 Mutex::Autolock lock(mCameraIdRemappingLock);
1277 // Update mCameraIdRemapping.
1278 mCameraIdRemapping.clear();
1279 mCameraIdRemapping.insert(cameraIdRemapping.begin(), cameraIdRemapping.end());
1280 }
malikakash82ed4352023-07-21 22:44:34 +00001281}
1282
malikakash22af94c2023-12-04 18:13:14 +00001283Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001284 const std::string& cameraId,
1285 const CameraMetadata& sessionParams) {
1286 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001287 const int pid = getCallingPid();
1288 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001289 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1290 __FUNCTION__, pid, uid);
1291 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1292 "Permission Denial: no permission to inject session params");
1293 }
1294
Biswarup Pal37a75182024-01-16 15:53:35 +00001295 // Do not allow session params injection for a virtual camera.
1296 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1297 if (deviceId != kDefaultDeviceId) {
1298 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1299 "Cannot inject session params for a virtual camera");
1300 }
1301
malikakash22af94c2023-12-04 18:13:14 +00001302 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1303 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1304
1305 auto clientDescriptor = mActiveClientManager.get(cameraId);
1306 if (clientDescriptor == nullptr) {
1307 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1308 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1309 "No active client for camera id %s", cameraId.c_str());
1310 }
1311
1312 sp<BasicClient> clientSp = clientDescriptor->getValue();
1313 status_t res = clientSp->injectSessionParams(sessionParams);
1314
1315 if (res != OK) {
1316 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1317 "Error injecting session params into camera \"%s\": %s (%d)",
1318 cameraId.c_str(), strerror(-res), res);
1319 }
1320 return Status::ok();
1321}
1322
Austin Borgered99f642023-06-01 16:51:35 -07001323std::vector<std::string> CameraService::findOriginalIdsForRemappedCameraId(
1324 const std::string& inputCameraId, int clientUid) {
1325 std::string packageName = getPackageNameFromUid(clientUid);
1326 std::vector<std::string> cameraIds;
malikakash82ed4352023-07-21 22:44:34 +00001327 Mutex::Autolock lock(mCameraIdRemappingLock);
1328 if (auto packageMapIter = mCameraIdRemapping.find(packageName);
1329 packageMapIter != mCameraIdRemapping.end()) {
1330 for (auto& [id0, id1]: packageMapIter->second) {
1331 if (id1 == inputCameraId) {
1332 cameraIds.push_back(id0);
1333 }
1334 }
1335 }
1336 return cameraIds;
1337}
1338
Austin Borgered99f642023-06-01 16:51:35 -07001339std::string CameraService::resolveCameraId(
1340 const std::string& inputCameraId,
malikakashedb38962023-09-06 00:03:35 +00001341 int clientUid,
Austin Borgered99f642023-06-01 16:51:35 -07001342 const std::string& packageName) {
1343 std::string packageNameVal = packageName;
malikakashedb38962023-09-06 00:03:35 +00001344 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001345 packageNameVal = getPackageNameFromUid(clientUid);
1346 }
malikakash65d20692023-09-07 01:06:33 +00001347 if (clientUid < AID_APP_START || packageNameVal.empty()) {
malikakashedb38962023-09-06 00:03:35 +00001348 // We shouldn't remap cameras for processes with system/vendor UIDs.
1349 return inputCameraId;
1350 }
malikakash82ed4352023-07-21 22:44:34 +00001351 Mutex::Autolock lock(mCameraIdRemappingLock);
1352 if (auto packageMapIter = mCameraIdRemapping.find(packageNameVal);
1353 packageMapIter != mCameraIdRemapping.end()) {
malikakash82ed4352023-07-21 22:44:34 +00001354 auto packageMap = packageMapIter->second;
1355 if (auto replacementIdIter = packageMap.find(inputCameraId);
1356 replacementIdIter != packageMap.end()) {
malikakashedb38962023-09-06 00:03:35 +00001357 ALOGI("%s: resolveCameraId: remapping cameraId %s for %s to %s",
malikakash82ed4352023-07-21 22:44:34 +00001358 __FUNCTION__, inputCameraId.c_str(),
malikakashedb38962023-09-06 00:03:35 +00001359 packageNameVal.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001360 replacementIdIter->second.c_str());
1361 return replacementIdIter->second;
1362 }
1363 }
1364 return inputCameraId;
1365}
1366
Biswarup Pal37a75182024-01-16 15:53:35 +00001367std::optional<std::string> CameraService::resolveCameraId(
1368 const std::string& inputCameraId,
1369 int32_t deviceId,
1370 int32_t devicePolicy,
1371 int clientUid,
1372 const std::string& packageName) {
1373 if ((deviceId == kDefaultDeviceId)
1374 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1375 auto [storedDeviceId, _] =
1376 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1377 if (storedDeviceId != kDefaultDeviceId) {
1378 // Trying to access a virtual camera from default-policy device context, we should fail.
1379 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1380 inputCameraId.c_str(), deviceId);
1381 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1382 return std::nullopt;
1383 }
1384 return resolveCameraId(inputCameraId, clientUid, packageName);
1385 }
1386
1387 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1388}
1389
1390Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait, int32_t deviceId,
1391 int32_t devicePolicy, CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001392 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001393 Mutex::Autolock l(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001394 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId, deviceId, devicePolicy);
1395 if (cameraIdStr.empty()) {
1396 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
1397 cameraId, deviceId);
1398 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1399 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1400 }
malikakashedb38962023-09-06 00:03:35 +00001401
Austin Borgered99f642023-06-01 16:51:35 -07001402 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001403 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1404 "characteristics for system only device %s: ", cameraIdStr.c_str());
1405 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001406
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001407 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001408 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001409 return STATUS_ERROR(ERROR_DISCONNECTED,
1410 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001411 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001412 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001413 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001414 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1415 if (hasSystemCameraPermissions) {
1416 cameraIdBound = mNumberOfCameras;
1417 }
1418 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001419 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1420 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001421 }
1422
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001423 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001424 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001425 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borgered99f642023-06-01 16:51:35 -07001426 cameraIdStr, overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001427 if (err != OK) {
1428 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1429 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1430 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001431 logServiceError(std::string("Error retrieving camera info from device ")
1432 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001433 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001434
Ruben Brunkcc776712015-02-17 20:18:47 -08001435 return ret;
1436}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001437
Biswarup Pal37a75182024-01-16 15:53:35 +00001438std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1439 int32_t deviceId, int32_t devicePolicy) {
1440 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1441 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1442 std::optional<std::string> cameraIdOptional =
1443 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1444 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1445 }
1446
1447 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001448 auto callingPid = getCallingPid();
1449 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001450 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1451 callingPid, callingUid, /* checkCameraPermissions= */ false);
1452 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001453 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001454 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001455 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1456 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1457 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001458 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001459 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001460
Biswarup Pal37a75182024-01-16 15:53:35 +00001461 std::string unresolvedCameraId = (*cameraIds)[cameraIdInt];
1462 return resolveCameraId(unresolvedCameraId, getCallingUid());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001463}
1464
Biswarup Pal37a75182024-01-16 15:53:35 +00001465std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1466 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001467 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001468 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001469}
1470
Austin Borgered99f642023-06-01 16:51:35 -07001471Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +00001472 int targetSdkVersion, bool overrideToPortrait, int32_t deviceId, int32_t devicePolicy,
1473 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001474 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001475
Zhijun He2b59be82013-09-25 10:14:30 -07001476 if (!cameraInfo) {
1477 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001478 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001479 }
1480
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001481 if (!mInitialized) {
1482 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001483 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001484 return STATUS_ERROR(ERROR_DISCONNECTED,
1485 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001486 }
1487
Biswarup Pal37a75182024-01-16 15:53:35 +00001488 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
1489 devicePolicy, getCallingUid());
1490 if (!cameraIdOptional.has_value()) {
1491 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1492 unresolvedCameraId.c_str(), deviceId);
1493 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1494 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1495 }
1496 std::string cameraId = cameraIdOptional.value();
1497
Austin Borgered99f642023-06-01 16:51:35 -07001498 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001499 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001500 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001501 }
1502
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001503 bool overrideForPerfClass =
1504 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001505 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001506 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borgered99f642023-06-01 16:51:35 -07001507 cameraId, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001508 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001509 if (res == NAME_NOT_FOUND) {
1510 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001511 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001512 strerror(-res), res);
1513 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001514 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1515 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001516 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001517 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001518 strerror(-res), res);
1519 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001520 }
Emilian Peeve20c6372018-08-14 18:45:53 +01001521
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001522 return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -07001523}
1524
Biswarup Pal37a75182024-01-16 15:53:35 +00001525Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId, int32_t deviceId,
1526 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001527 ATRACE_CALL();
1528 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001529
Biswarup Pal37a75182024-01-16 15:53:35 +00001530 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
1531 devicePolicy, getCallingUid());
1532 if (!cameraIdOptional.has_value()) {
1533 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1534 unresolvedCameraId.c_str(), deviceId);
1535 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1536 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1537 }
1538 std::string cameraId = cameraIdOptional.value();
1539
Rucha Katakwar38284522021-11-10 11:25:21 -08001540 if (!mInitialized) {
1541 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1542 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1543 }
1544
Biswarup Pal37a75182024-01-16 15:53:35 +00001545 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001546 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1547 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1548 }
1549
Austin Borgered99f642023-06-01 16:51:35 -07001550 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001551 if (res != OK) {
1552 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001553 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001554 strerror(-res), res);
1555 }
1556 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1557 return Status::ok();
1558}
1559
Austin Borgered99f642023-06-01 16:51:35 -07001560std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001561 time_t now = time(nullptr);
1562 char formattedTime[64];
1563 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001564 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001565}
1566
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001567Status CameraService::getCameraVendorTagDescriptor(
1568 /*out*/
1569 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001570 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001571 if (!mInitialized) {
1572 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001573 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001574 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001575 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1576 if (globalDescriptor != nullptr) {
1577 *desc = *(globalDescriptor.get());
1578 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001579 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001580}
1581
Emilian Peev71c73a22017-03-21 16:35:51 +00001582Status CameraService::getCameraVendorTagCache(
1583 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1584 ATRACE_CALL();
1585 if (!mInitialized) {
1586 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1587 return STATUS_ERROR(ERROR_DISCONNECTED,
1588 "Camera subsystem not available");
1589 }
1590 sp<VendorTagDescriptorCache> globalCache =
1591 VendorTagDescriptorCache::getGlobalVendorTagCache();
1592 if (globalCache != nullptr) {
1593 *cache = *(globalCache.get());
1594 }
1595 return Status::ok();
1596}
1597
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001598void CameraService::clearCachedVariables() {
1599 BasicClient::BasicClient::sCameraService = nullptr;
1600}
1601
Austin Borgered99f642023-06-01 16:51:35 -07001602std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001603 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001604 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001605
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001606 int deviceVersion = 0;
1607
Emilian Peevf53f66e2017-04-11 14:29:43 +01001608 status_t res;
1609 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001610 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001611 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001612 if (res != OK || transport == IPCTransport::INVALID) {
1613 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001614 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001615 return std::make_pair(-1, IPCTransport::INVALID) ;
1616 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001617 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001618
Emilian Peevf53f66e2017-04-11 14:29:43 +01001619 hardware::CameraInfo info;
1620 if (facing) {
Austin Borgered99f642023-06-01 16:51:35 -07001621 res = mCameraProviderManager->getCameraInfo(cameraId, overrideToPortrait,
Austin Borger18b30a72022-10-27 12:20:29 -07001622 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001623 if (res != OK) {
1624 return std::make_pair(-1, IPCTransport::INVALID);
1625 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001626 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001627 if (orientation) {
1628 *orientation = info.orientation;
1629 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001630 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001631
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001632 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001633}
1634
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001635Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001636 switch(err) {
1637 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001638 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001639 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001640 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1641 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001642 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001643 return STATUS_ERROR(ERROR_DISCONNECTED,
1644 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001645 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001646 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1647 "Camera HAL encountered error %d: %s",
1648 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001649 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001650}
1651
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001652Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001653 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1654 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001655 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001656 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001657 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
malikakash73125c62023-07-21 22:44:34 +00001658 bool forceSlowJpegMode, const std::string& originalCameraId,
1659 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001660 // For HIDL devices
1661 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1662 // Create CameraClient based on device version reported by the HAL.
1663 int deviceVersion = deviceVersionAndTransport.first;
1664 switch(deviceVersion) {
1665 case CAMERA_DEVICE_API_VERSION_1_0:
1666 ALOGE("Camera using old HAL version: %d", deviceVersion);
1667 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1668 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001669 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001670 break;
1671 case CAMERA_DEVICE_API_VERSION_3_0:
1672 case CAMERA_DEVICE_API_VERSION_3_1:
1673 case CAMERA_DEVICE_API_VERSION_3_2:
1674 case CAMERA_DEVICE_API_VERSION_3_3:
1675 case CAMERA_DEVICE_API_VERSION_3_4:
1676 case CAMERA_DEVICE_API_VERSION_3_5:
1677 case CAMERA_DEVICE_API_VERSION_3_6:
1678 case CAMERA_DEVICE_API_VERSION_3_7:
1679 break;
1680 default:
1681 // Should not be reachable
1682 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1683 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1684 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001685 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001686 }
1687 }
1688 if (effectiveApiLevel == API_1) { // Camera1 API route
1689 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001690 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001691 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001692 api1CameraId, facing, sensorOrientation,
Chengfei Taobe683db2023-01-31 18:52:49 +00001693 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait,
1694 forceSlowJpegMode);
1695 ALOGI("%s: Camera1 API (legacy), override to portrait %d, forceSlowJpegMode %d",
1696 __FUNCTION__, overrideToPortrait, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001697 } else { // Camera2 API route
1698 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1699 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001700 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001701 cameraService->mCameraServiceProxyWrapper,
1702 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001703 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
malikakash82ed4352023-07-21 22:44:34 +00001704 overrideForPerfClass, overrideToPortrait, originalCameraId);
Austin Borger18b30a72022-10-27 12:20:29 -07001705 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001706 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001707 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001708}
1709
Austin Borgered99f642023-06-01 16:51:35 -07001710std::string CameraService::toString(std::set<userid_t> intSet) {
1711 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001712 bool first = true;
1713 for (userid_t i : intSet) {
1714 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001715 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001716 first = false;
1717 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001718 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001719 }
1720 }
Austin Borgered99f642023-06-01 16:51:35 -07001721 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001722}
1723
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001724int32_t CameraService::mapToInterface(TorchModeStatus status) {
1725 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1726 switch (status) {
1727 case TorchModeStatus::NOT_AVAILABLE:
1728 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1729 break;
1730 case TorchModeStatus::AVAILABLE_OFF:
1731 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1732 break;
1733 case TorchModeStatus::AVAILABLE_ON:
1734 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1735 break;
1736 default:
1737 ALOGW("Unknown new flash status: %d", status);
1738 }
1739 return serviceStatus;
1740}
1741
1742CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1743 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1744 switch (status) {
1745 case CameraDeviceStatus::NOT_PRESENT:
1746 serviceStatus = StatusInternal::NOT_PRESENT;
1747 break;
1748 case CameraDeviceStatus::PRESENT:
1749 serviceStatus = StatusInternal::PRESENT;
1750 break;
1751 case CameraDeviceStatus::ENUMERATING:
1752 serviceStatus = StatusInternal::ENUMERATING;
1753 break;
1754 default:
1755 ALOGW("Unknown new HAL device status: %d", status);
1756 }
1757 return serviceStatus;
1758}
1759
1760int32_t CameraService::mapToInterface(StatusInternal status) {
1761 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1762 switch (status) {
1763 case StatusInternal::NOT_PRESENT:
1764 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1765 break;
1766 case StatusInternal::PRESENT:
1767 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1768 break;
1769 case StatusInternal::ENUMERATING:
1770 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1771 break;
1772 case StatusInternal::NOT_AVAILABLE:
1773 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1774 break;
1775 case StatusInternal::UNKNOWN:
1776 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1777 break;
1778 default:
1779 ALOGW("Unknown new internal device status: %d", status);
1780 }
1781 return serviceStatus;
1782}
1783
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001784Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001785 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001786
Austin Borgered99f642023-06-01 16:51:35 -07001787 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001788 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001789 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001790 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001791 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1792 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001793 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Chengfei Taobe683db2023-01-31 18:52:49 +00001794 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true,
Austin Borgered99f642023-06-01 16:51:35 -07001795 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001796 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001797 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001798 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001799 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001800}
1801
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001802Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001803 /*out*/
1804 CameraParameters* parameters) {
1805
1806 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1807
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001808 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001809
1810 if (parameters == NULL) {
1811 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001812 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001813 }
1814
malikakashedb38962023-09-06 00:03:35 +00001815 std::string unresolvedCameraId = std::to_string(cameraId);
1816 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08001817 getCallingUid());
Ruben Brunkcc776712015-02-17 20:18:47 -08001818
1819 // Check if we already have parameters
1820 {
1821 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001822 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001823 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001824 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001825 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001826 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001827 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001828 }
1829 CameraParameters p = cameraState->getShimParams();
1830 if (!p.isEmpty()) {
1831 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001832 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001833 }
1834 }
1835
Austin Borger22c5c852024-03-08 13:31:36 -08001836 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001837 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001838 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001839 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001840 // Error already logged by callee
1841 return ret;
1842 }
1843
1844 // Check for parameters again
1845 {
1846 // Scope for service lock
1847 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001848 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001849 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001850 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001851 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001852 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001853 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001854 CameraParameters p = cameraState->getShimParams();
1855 if (!p.isEmpty()) {
1856 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001857 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001858 }
1859 }
1860
Ruben Brunkcc776712015-02-17 20:18:47 -08001861 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1862 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001863 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001864}
1865
Austin Borgered99f642023-06-01 16:51:35 -07001866Status CameraService::validateConnectLocked(const std::string& cameraId,
1867 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001868 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001869
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001870#ifdef __BRILLO__
1871 UNUSED(clientName8);
1872 UNUSED(clientUid);
1873 UNUSED(clientPid);
1874 UNUSED(originalClientPid);
1875#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001876 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1877 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001878 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001879 return allowed;
1880 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001881#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001882
Austin Borger22c5c852024-03-08 13:31:36 -08001883 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001884
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001885 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001886 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1887 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001888 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001889 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001890 }
1891
Ruben Brunkcc776712015-02-17 20:18:47 -08001892 if (getCameraState(cameraId) == nullptr) {
1893 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001894 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001895 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001896 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001897 }
1898
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001899 status_t err = checkIfDeviceIsUsable(cameraId);
1900 if (err != NO_ERROR) {
1901 switch(err) {
1902 case -ENODEV:
1903 case -EBUSY:
1904 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001905 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001906 default:
1907 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001908 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001909 }
1910 }
1911 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001912}
1913
Austin Borgered99f642023-06-01 16:51:35 -07001914Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1915 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001916 /*out*/int& originalClientPid) const {
Austin Borger22c5c852024-03-08 13:31:36 -08001917 int callingPid = getCallingPid();
1918 int callingUid = getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001919
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001920 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001921 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001922 clientUid = callingUid;
1923 } else if (!isTrustedCallingUid(callingUid)) {
1924 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1925 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001926 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1927 "Untrusted caller (calling PID %d, UID %d) trying to "
1928 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001929 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001930 clientName.c_str(), clientPid, clientUid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001931 }
1932
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001933 // Check if we can trust clientPid
1934 if (clientPid == USE_CALLING_PID) {
1935 clientPid = callingPid;
1936 } else if (!isTrustedCallingUid(callingUid)) {
1937 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1938 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001939 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1940 "Untrusted caller (calling PID %d, UID %d) trying to "
1941 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001942 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001943 clientName.c_str(), clientPid, clientUid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001944 }
1945
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001946 if (shouldRejectSystemCameraConnection(cameraId)) {
1947 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1948 cameraId.c_str());
1949 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001950 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001951 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001952 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1953 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001954 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001955 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001956 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001957 }
1958
Biswarup Pale506e732024-03-27 13:46:20 +00001959 // Get the device id that owns this camera.
1960 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1961
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001962 // If it's not calling from cameraserver, check the permission if the
1963 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1964 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001965 bool checkPermissionForCamera =
Biswarup Pale506e732024-03-27 13:46:20 +00001966 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName, deviceId);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001967 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001968 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001969 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001970 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1971 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001972 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001973 }
1974
Svet Ganova453d0d2018-01-11 15:37:58 -08001975 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001976 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001977 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001978 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1979 clientPid, clientUid);
1980 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001981 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1982 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001983 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001984 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001985 }
1986
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001987 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1988 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1989 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1990 if ((!isAutomotivePrivilegedClient(callingUid) ||
1991 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1992 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001993 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1994 return STATUS_ERROR_FMT(ERROR_DISABLED,
1995 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001996 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001997 }
1998
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001999 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
2000 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07002001 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07002002 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002003
Ruben Brunk6267b532015-04-30 17:44:07 -07002004 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08002005
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002006 // For non-system clients : Only allow clients who are being used by the current foreground
2007 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08002008 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08002009 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002010 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
2011 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07002012 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002013 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2014 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002015 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07002016 }
2017
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07002018 if (flags::camera_hsum_permission()) {
2019 // If the System User tries to access the camera when the device is running in
2020 // headless system user mode, ensure that client has the required permission
2021 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07002022 if (isHeadlessSystemUserMode()
2023 && (clientUserId == USER_SYSTEM)
2024 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07002025 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
2026 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2027 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
2028 User without camera headless system user permission",
Austin Borger249e6592024-03-10 22:28:11 -07002029 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07002030 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07002031 }
2032
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002033 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002034}
2035
Austin Borgered99f642023-06-01 16:51:35 -07002036status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08002037 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08002038 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08002039 if (cameraState == nullptr) {
2040 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07002041 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002042 return -ENODEV;
2043 }
2044
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002045 StatusInternal currentStatus = cameraState->getStatus();
2046 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002047 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07002048 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002049 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002050 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002051 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07002052 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002053 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07002054 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002055
Ruben Brunkcc776712015-02-17 20:18:47 -08002056 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08002057}
2058
Ruben Brunkcc776712015-02-17 20:18:47 -08002059void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002060 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08002061
Ruben Brunkcc776712015-02-17 20:18:47 -08002062 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002063 auto clientDescriptor =
2064 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002065 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08002066 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
2067
2068 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002069 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08002070
2071 if (evicted.size() > 0) {
2072 // This should never happen - clients should already have been removed in disconnect
2073 for (auto& i : evicted) {
2074 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07002075 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002076 }
2077
2078 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
2079 __FUNCTION__);
2080 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002081
2082 // And register a death notification for the client callback. Do
2083 // this last to avoid Binder policy where a nested Binder
2084 // transaction might be pre-empted to service the client death
2085 // notification if the client process dies before linkToDeath is
2086 // invoked.
2087 sp<IBinder> remoteCallback = client->getRemote();
2088 if (remoteCallback != nullptr) {
2089 remoteCallback->linkToDeath(this);
2090 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002091}
2092
Austin Borgered99f642023-06-01 16:51:35 -07002093status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
2094 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
2095 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08002096 /*out*/
2097 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07002098 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002099 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08002100 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002101 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08002102 DescriptorPtr clientDescriptor;
2103 {
2104 if (effectiveApiLevel == API_1) {
2105 // If we are using API1, any existing client for this camera ID with the same remote
2106 // should be returned rather than evicted to allow MediaRecorder to work properly.
2107
2108 auto current = mActiveClientManager.get(cameraId);
2109 if (current != nullptr) {
2110 auto clientSp = current->getValue();
2111 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002112 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07002113 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002114 " API level, evicting prior client...");
2115 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002116 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002117 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002118 *client = clientSp;
2119 return NO_ERROR;
2120 }
2121 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002122 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002123 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08002124
Ruben Brunkcc776712015-02-17 20:18:47 -08002125 // Get state for the given cameraId
2126 auto state = getCameraState(cameraId);
2127 if (state == nullptr) {
2128 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07002129 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002130 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07002131 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002132 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002133
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002134 sp<IServiceManager> sm = defaultServiceManager();
2135 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08002136 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002137 // If processinfo service is not available and the client is automotive privileged
2138 // client used for safety critical uses cases such as rear-view and surround-view which
2139 // needs to be available before android boot completes, then use the hardcoded values
2140 // for the process state and priority score. As this scenario is before android system
2141 // services are up and client is native client, hence using NATIVE_ADJ as the priority
2142 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
2143 // visible on the top.
2144 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2145 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2146 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
2147 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
2148 } else {
2149 // Get current active client PIDs
2150 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
2151 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002152
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002153 std::vector<int> priorityScores(ownerPids.size());
2154 std::vector<int> states(ownerPids.size());
2155
2156 // Get priority scores of all active PIDs
2157 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
2158 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
2159 if (err != OK) {
2160 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
2161 return err;
2162 }
2163
2164 // Update all active clients' priorities
2165 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
2166 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
2167 pidToPriorityMap.emplace(ownerPids[i],
2168 resource_policy::ClientPriority(priorityScores[i], states[i],
2169 /* isVendorClient won't get copied over*/ false,
2170 /* oomScoreOffset won't get copied over*/ 0));
2171 }
2172 mActiveClientManager.updatePriorities(pidToPriorityMap);
2173
2174 int32_t actualScore = priorityScores[priorityScores.size() - 1];
2175 int32_t actualState = states[states.size() - 1];
2176
2177 // Make descriptor for incoming client. We store the oomScoreOffset
2178 // since we might need it later on new handleEvictionsLocked and
2179 // ProcessInfoService would not take that into account.
2180 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2181 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2182 state->getConflicting(), actualScore, clientPid, actualState,
2183 oomScoreOffset, systemNativeClient);
2184 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002185
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002186 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
2187
Ruben Brunkcc776712015-02-17 20:18:47 -08002188 // Find clients that would be evicted
2189 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
2190
2191 // If the incoming client was 'evicted,' higher priority clients have the camera in the
2192 // background, so we cannot do evictions
2193 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2194 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2195 " priority).", clientPid);
2196
2197 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002198 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002199 auto incompatibleClients =
2200 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2201
Austin Borgered99f642023-06-01 16:51:35 -07002202 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2203 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2204 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002205 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002206
2207 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002208 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002209 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002210 i->getKey().c_str(),
2211 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002212 i->getOwnerId(), i->getPriority().getScore(),
2213 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002214 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002215 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2216 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002217 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002218 }
2219
2220 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002221 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002222 mEventLog.add(msg);
2223
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002224 auto current = mActiveClientManager.get(cameraId);
2225 if (current != nullptr) {
2226 return -EBUSY; // CAMERA_IN_USE
2227 } else {
2228 return -EUSERS; // MAX_CAMERAS_IN_USE
2229 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002230 }
2231
2232 for (auto& i : evicted) {
2233 sp<BasicClient> clientSp = i->getValue();
2234 if (clientSp.get() == nullptr) {
2235 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2236
2237 // TODO: Remove this
2238 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2239 __FUNCTION__);
2240 mActiveClientManager.remove(i);
2241 continue;
2242 }
2243
2244 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002245 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002246 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002247
Ruben Brunkcc776712015-02-17 20:18:47 -08002248 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002249 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002250 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2251 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002252 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002253 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002254 i->getPriority().getState(), cameraId.c_str(),
2255 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002256 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002257
2258 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002259 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002260 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002261 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002262 }
2263
Ruben Brunkcc776712015-02-17 20:18:47 -08002264 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2265 // other clients from connecting in mServiceLockWrapper if held
2266 mServiceLock.unlock();
2267
2268 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002269 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002270
2271 // Destroy evicted clients
2272 for (auto& i : evictedClients) {
2273 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002274 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002275 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002276
Austin Borger22c5c852024-03-08 13:31:36 -08002277 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002278
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002279 for (const auto& i : evictedClients) {
2280 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002281 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002282 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2283 if (ret == TIMED_OUT) {
2284 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002285 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2286 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002287 return -EBUSY;
2288 }
2289 if (ret != NO_ERROR) {
2290 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002291 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2292 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002293 return ret;
2294 }
2295 }
2296
2297 evictedClients.clear();
2298
Ruben Brunkcc776712015-02-17 20:18:47 -08002299 // Once clients have been disconnected, relock
2300 mServiceLock.lock();
2301
2302 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2303 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2304 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002305 }
2306
Ruben Brunkcc776712015-02-17 20:18:47 -08002307 *partial = clientDescriptor;
2308 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002309}
2310
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002311Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002312 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002313 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07002314 const std::string& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002315 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08002316 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002317 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07002318 bool overrideToPortrait,
Chengfei Taobe683db2023-01-31 18:52:49 +00002319 bool forceSlowJpegMode,
Biswarup Pal37a75182024-01-16 15:53:35 +00002320 int32_t deviceId,
2321 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002322 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002323 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002324 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002325 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002326
Biswarup Pal37a75182024-01-16 15:53:35 +00002327 std::string cameraIdStr = cameraIdIntToStr(api1CameraId, deviceId, devicePolicy);
2328 if (cameraIdStr.empty()) {
2329 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
2330 api1CameraId, deviceId);
2331 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2332 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2333 }
malikakashedb38962023-09-06 00:03:35 +00002334
Ruben Brunkcc776712015-02-17 20:18:47 -08002335 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002336 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
2337 clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002338 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002339 overrideToPortrait, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002340
Biswarup Pal37a75182024-01-16 15:53:35 +00002341 if (!ret.isOk()) {
2342 logRejected(cameraIdStr, getCallingPid(), clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002343 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002344 }
2345
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002346 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002347
2348 const sp<IServiceManager> sm(defaultServiceManager());
2349 const auto& mActivityManager = getActivityManager();
2350 if (mActivityManager) {
2351 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002352 getCallingUid(),
2353 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002354 }
2355
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002356 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002357}
2358
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002359bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2360 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002361 // If the client is not a vendor client, don't add listener if
2362 // a) the camera is a publicly hidden secure camera OR
2363 // b) the camera is a system only camera and the client doesn't
2364 // have android.permission.SYSTEM_CAMERA permissions.
2365 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2366 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002367 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002368 return true;
2369 }
2370 return false;
2371}
2372
Austin Borgered99f642023-06-01 16:51:35 -07002373bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002374 // Rules for rejection:
2375 // 1) If cameraserver tries to access this camera device, accept the
2376 // connection.
2377 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002378 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002379 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2380 // and the serving thread is a non hwbinder thread, the client must have
2381 // android.permission.SYSTEM_CAMERA permissions to connect.
2382
Austin Borger22c5c852024-03-08 13:31:36 -08002383 int cPid = getCallingPid();
2384 int cUid = getCallingUid();
2385 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002386 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2387 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002388 // This isn't a known camera ID, so it's not a system camera
2389 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2390 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002391 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002392
2393 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002394 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002395 return false;
2396 }
2397 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002398 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002399 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2400 return true;
2401 }
2402 // (3) Here we only check for permissions if it is a system only camera device. This is since
2403 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2404 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2405 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002406 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002407 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002408 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2409 cameraId.c_str());
2410 return true;
2411 }
2412
2413 return false;
2414}
2415
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002416Status CameraService::connectDevice(
2417 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002418 const std::string& unresolvedCameraId,
2419 const std::string& clientPackageName,
2420 const std::optional<std::string>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002421 int clientUid, int oomScoreOffset, int targetSdkVersion,
Biswarup Pal37a75182024-01-16 15:53:35 +00002422 bool overrideToPortrait, int32_t deviceId, int32_t devicePolicy,
Ruben Brunkcc776712015-02-17 20:18:47 -08002423 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002424 sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002425 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002426 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002427 sp<CameraDeviceClient> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002428 std::string clientPackageNameAdj = clientPackageName;
Austin Borger22c5c852024-03-08 13:31:36 -08002429 int callingPid = getCallingPid();
2430 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002431 bool systemNativeClient = false;
Austin Borger22c5c852024-03-08 13:31:36 -08002432 if (callerHasSystemUid() && (clientPackageNameAdj.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002433 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borgered99f642023-06-01 16:51:35 -07002434 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002435 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002436 }
Austin Borger249e6592024-03-10 22:28:11 -07002437
Biswarup Pal37a75182024-01-16 15:53:35 +00002438 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
2439 devicePolicy, callingUid, clientPackageNameAdj);
2440 if (!cameraIdOptional.has_value()) {
2441 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
2442 unresolvedCameraId.c_str(), deviceId);
2443 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2444 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2445 }
2446 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002447
2448 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002449 std::string msg =
2450 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
2451 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
2452 cameraId.c_str());
2453 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2454 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002455 }
2456
Austin Borger9bfa0a72022-08-03 17:50:40 -07002457 userid_t clientUserId = multiuser_get_user_id(clientUid);
Austin Borger9bfa0a72022-08-03 17:50:40 -07002458 if (clientUid == USE_CALLING_UID) {
2459 clientUserId = multiuser_get_user_id(callingUid);
2460 }
2461
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002462 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2463 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002464 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2465 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002466 std::string msg = "Camera disabled by device policy";
2467 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2468 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002469 }
2470
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002471 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002472 if (oomScoreOffset > 0
2473 && !hasPermissionsForSystemCamera(cameraId, callingPid,
Austin Borger249e6592024-03-10 22:28:11 -07002474 callingUid)
2475 && !isTrustedCallingUid(callingUid)) {
Austin Borgered99f642023-06-01 16:51:35 -07002476 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002477 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07002478 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2479 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2480 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002481 }
2482
Austin Borgered99f642023-06-01 16:51:35 -07002483 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
2484 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002485 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
malikakash73125c62023-07-21 22:44:34 +00002486 targetSdkVersion, overrideToPortrait, /*forceSlowJpegMode*/false, unresolvedCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002487 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002488
Biswarup Pal37a75182024-01-16 15:53:35 +00002489 if (!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002490 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002491 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002492 }
2493
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002494 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002495 Mutex::Autolock lock(mServiceLock);
2496
2497 // Clear the previous cached logs and reposition the
2498 // file offset to beginning of the file to log new data.
2499 // If either truncate or lseek fails, close the previous file and create a new one.
2500 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2501 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2502 // Close the previous memfd.
2503 close(mMemFd);
2504 // If failure to wipe the data, then create a new file and
2505 // assign the new value to mMemFd.
2506 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2507 if (mMemFd == -1) {
2508 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2509 }
2510 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002511 const sp<IServiceManager> sm(defaultServiceManager());
2512 const auto& mActivityManager = getActivityManager();
2513 if (mActivityManager) {
2514 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002515 callingUid,
2516 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002517 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002518 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002519}
2520
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002521bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2522 int callingPid, int callingUid) {
2523 if (!isAutomotiveDevice()) {
2524 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2525 }
2526
2527 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2528 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2529 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2530 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2531 "using camera %s", callingUid, cam_id.c_str());
2532 return false;
2533 }
2534
2535 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2536 return true;
2537 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2538 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002539 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2540 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002541 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2542 return false;
2543 } else {
2544 return true;
2545 }
2546 }
2547 return false;
2548}
2549
Austin Borgered99f642023-06-01 16:51:35 -07002550std::string CameraService::getPackageNameFromUid(int clientUid) {
2551 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002552
Avichal Rakesh5788fec2024-03-15 14:39:20 -07002553 sp<IPermissionController> permCtrl;
2554 if (flags::cache_permission_services()) {
2555 permCtrl = getPermissionController();
2556 } else {
2557 sp<IServiceManager> sm = defaultServiceManager();
2558#pragma clang diagnostic push
2559#pragma clang diagnostic ignored "-Wdeprecated-declarations"
2560 // Using deprecated function to preserve functionality until the
2561 // cache_permission_services flag is removed.
2562 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
2563#pragma clang diagnostic pop
2564 if (binder == 0) {
2565 ALOGE("Cannot get permission service");
2566 permCtrl = nullptr;
2567 } else {
2568 permCtrl = interface_cast<IPermissionController>(binder);
2569 }
2570 }
2571
2572 if (permCtrl == nullptr) {
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002573 // Return empty package name and the further interaction
2574 // with camera will likely fail
2575 return packageName;
2576 }
2577
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002578 Vector<String16> packages;
2579
2580 permCtrl->getPackagesForUid(clientUid, packages);
2581
2582 if (packages.isEmpty()) {
2583 ALOGE("No packages for calling UID %d", clientUid);
2584 // Return empty package name and the further interaction
2585 // with camera will likely fail
2586 return packageName;
2587 }
2588
2589 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002590 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002591
2592 return packageName;
2593}
2594
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002595template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002596Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2597 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2598 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002599 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002600 bool overrideToPortrait, bool forceSlowJpegMode, const std::string& originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002601 /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002602 binder::Status ret = binder::Status::ok();
2603
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002604 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002605 std::string clientPackageName;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002606 int packageUid = (clientUid == USE_CALLING_UID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002607 getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002608 if (clientPackageNameMaybe.size() <= 0) {
2609 // NDK calls don't come with package names, but we need one for various cases.
2610 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2611 // do exist. For all authentication cases, all packages under the same UID get the
2612 // same permissions, so picking any associated package name is sufficient. For some
2613 // other cases, this may give inaccurate names for clients in logs.
2614 isNonSystemNdk = true;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002615 clientPackageName = getPackageNameFromUid(packageUid);
2616 } else {
2617 clientPackageName = clientPackageNameMaybe;
2618 }
2619
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002620 int originalClientPid = 0;
2621
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002622 int packagePid = (clientPid == USE_CALLING_PID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002623 getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002624 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002625 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002626 static_cast<int>(effectiveApiLevel));
2627
Shuzhen Wang316781a2020-08-18 18:11:01 -07002628 nsecs_t openTimeNs = systemTime();
2629
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002630 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002631 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002632 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002633
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002634 {
2635 // Acquire mServiceLock and prevent other clients from connecting
2636 std::unique_ptr<AutoConditionLock> lock =
2637 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2638
2639 if (lock == nullptr) {
2640 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2641 , clientPid);
2642 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2643 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002644 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002645 }
2646
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002647 // Enforce client permissions and do basic validity checks
Biswarup Pal37a75182024-01-16 15:53:35 +00002648 if (!(ret = validateConnectLocked(cameraId, clientPackageName,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002649 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2650 return ret;
2651 }
2652
2653 // Check the shim parameters after acquiring lock, if they have already been updated and
2654 // we were doing a shim update, return immediately
2655 if (shimUpdateOnly) {
2656 auto cameraState = getCameraState(cameraId);
2657 if (cameraState != nullptr) {
2658 if (!cameraState->getShimParams().isEmpty()) return ret;
2659 }
2660 }
2661
2662 status_t err;
2663
2664 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002665 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002666 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002667 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2668 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002669 switch (err) {
2670 case -ENODEV:
2671 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2672 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002673 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002674 case -EBUSY:
2675 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2676 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002677 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002678 case -EUSERS:
2679 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2680 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002681 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002682 default:
2683 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2684 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002685 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002686 }
2687 }
2688
2689 if (clientTmp.get() != nullptr) {
2690 // Handle special case for API1 MediaRecorder where the existing client is returned
2691 device = static_cast<CLIENT*>(clientTmp.get());
2692 return ret;
2693 }
2694
2695 // give flashlight a chance to close devices if necessary.
2696 mFlashlight->prepareDeviceOpen(cameraId);
2697
Austin Borger18b30a72022-10-27 12:20:29 -07002698 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002699 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07002700 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
2701 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002702 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002703 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002704 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002705 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002706 }
2707
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002708 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002709 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002710 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002711 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002712 clientFeatureId, cameraId, api1CameraId, facing,
2713 orientation, clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002714 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
malikakash82ed4352023-07-21 22:44:34 +00002715 overrideToPortrait, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002716 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002717 return ret;
2718 }
2719 client = static_cast<CLIENT*>(tmp.get());
2720
2721 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2722 __FUNCTION__);
2723
Austin Borgered99f642023-06-01 16:51:35 -07002724 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002725 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002726 if (err != OK) {
2727 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002728 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002729 mServiceLock.unlock();
2730 client->disconnect();
2731 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002732 switch(err) {
2733 case BAD_VALUE:
2734 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002735 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002736 case -EBUSY:
2737 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002738 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002739 case -EUSERS:
2740 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2741 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002742 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002743 case PERMISSION_DENIED:
2744 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002745 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002746 case -EACCES:
2747 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002748 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002749 case -ENODEV:
2750 default:
2751 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002752 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002753 strerror(-err), err);
2754 }
2755 }
2756
2757 // Update shim paremeters for legacy clients
2758 if (effectiveApiLevel == API_1) {
2759 // Assume we have always received a Client subclass for API1
2760 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2761 String8 rawParams = shimClient->getParameters();
2762 CameraParameters params(rawParams);
2763
2764 auto cameraState = getCameraState(cameraId);
2765 if (cameraState != nullptr) {
2766 cameraState->setShimParams(params);
2767 } else {
2768 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002769 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002770 }
2771 }
2772
Ravneetaeb20dc2022-03-30 05:33:03 +00002773 // Enable/disable camera service watchdog
2774 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2775
Emilian Peev6d45db82024-01-18 20:11:54 +00002776 CameraMetadata chars;
2777 bool rotateAndCropSupported = true;
2778 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
2779 &chars, overrideToPortrait);
2780 if (err == OK) {
2781 auto availableRotateCropEntry = chars.find(
2782 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2783 if (availableRotateCropEntry.count <= 1) {
2784 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002785 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002786 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002787 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2788 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002789 }
2790
Emilian Peev6d45db82024-01-18 20:11:54 +00002791 if (rotateAndCropSupported) {
2792 // Set rotate-and-crop override behavior
2793 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2794 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
2795 } else if (overrideToPortrait && portraitRotation != 0) {
2796 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2797 switch (portraitRotation) {
2798 case 90:
2799 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2800 break;
2801 case 180:
2802 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2803 break;
2804 case 270:
2805 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2806 break;
2807 default:
2808 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2809 break;
2810 }
2811 client->setRotateAndCropOverride(rotateAndCropMode);
2812 } else {
2813 client->setRotateAndCropOverride(
2814 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2815 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2816 }
2817 }
2818
2819 bool autoframingSupported = true;
2820 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2821 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2822 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2823 autoframingSupported = false;
2824 }
2825
2826 if (autoframingSupported) {
2827 // Set autoframing override behaviour
2828 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2829 client->setAutoframingOverride(mOverrideAutoframingMode);
2830 } else {
2831 client->setAutoframingOverride(
2832 mCameraServiceProxyWrapper->getAutoframingOverride(
2833 clientPackageName));
2834 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002835 }
2836
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002837 bool isCameraPrivacyEnabled;
2838 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002839 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002840 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2841 toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2842 } else {
2843 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002844 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002845 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002846
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002847 if (client->supportsCameraMute()) {
2848 client->setCameraMute(
2849 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2850 } else if (isCameraPrivacyEnabled) {
2851 // no camera mute supported, but privacy is on! => disconnect
2852 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2853 client->getPackageName().c_str(), cameraId.c_str());
2854 // Do not hold mServiceLock while disconnecting clients, but
2855 // retain the condition blocking other clients from connecting
2856 // in mServiceLockWrapper if held.
2857 mServiceLock.unlock();
2858 // Clear caller identity temporarily so client disconnect PID
2859 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002860 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002861 // Note AppOp to trigger the "Unblock" dialog
2862 client->noteAppOp();
2863 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002864 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002865 // Reacquire mServiceLock
2866 mServiceLock.lock();
2867
2868 return STATUS_ERROR_FMT(ERROR_DISABLED,
2869 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002870 }
2871
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002872 if (shimUpdateOnly) {
2873 // If only updating legacy shim parameters, immediately disconnect client
2874 mServiceLock.unlock();
2875 client->disconnect();
2876 mServiceLock.lock();
2877 } else {
2878 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002879 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002880 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002881
2882 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002883 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002884 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002885 } // lock is destroyed, allow further connect calls
2886
2887 // Important: release the mutex here so the client can call back into the service from its
2888 // destructor (can be at the end of the call)
2889 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002890
2891 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002892 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002893 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002894
Cliff Wud3a05312021-04-26 23:07:31 +08002895 {
2896 Mutex::Autolock lock(mInjectionParametersLock);
2897 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2898 mInjectionInitPending = false;
2899 status_t res = NO_ERROR;
2900 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2901 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002902 sp<BasicClient> clientSp = clientDescriptor->getValue();
2903 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2904 if(res != OK) {
2905 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2906 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002907 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002908 }
2909 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002910 if (res != OK) {
2911 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2912 }
2913 } else {
2914 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002915 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002916 res = NO_INIT;
2917 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2918 }
2919 }
2920 }
2921
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002922 return ret;
2923}
2924
Austin Borgered99f642023-06-01 16:51:35 -07002925status_t CameraService::addOfflineClient(const std::string &cameraId,
2926 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002927 if (offlineClient.get() == nullptr) {
2928 return BAD_VALUE;
2929 }
2930
2931 {
2932 // Acquire mServiceLock and prevent other clients from connecting
2933 std::unique_ptr<AutoConditionLock> lock =
2934 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2935
2936 if (lock == nullptr) {
2937 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2938 , __FUNCTION__, offlineClient->getClientPid());
2939 return TIMED_OUT;
2940 }
2941
2942 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2943 if (onlineClientDesc.get() == nullptr) {
2944 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2945 cameraId.c_str());
2946 return BAD_VALUE;
2947 }
2948
2949 // Offline clients do not evict or conflict with other online devices. Resource sharing
2950 // conflicts are handled by the camera provider which will either succeed or fail before
2951 // reaching this method.
2952 const auto& onlinePriority = onlineClientDesc->getPriority();
2953 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2954 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002955 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002956 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002957 // native clients don't have offline processing support.
2958 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002959 if (offlineClientDesc == nullptr) {
2960 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2961 return BAD_VALUE;
2962 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002963
2964 // Allow only one offline device per camera
2965 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2966 if (!incompatibleClients.empty()) {
2967 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2968 return BAD_VALUE;
2969 }
2970
Austin Borgered99f642023-06-01 16:51:35 -07002971 std::string monitorTags = isClientWatched(offlineClient.get())
2972 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002973 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002974 if (err != OK) {
2975 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2976 return err;
2977 }
2978
2979 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2980 if (evicted.size() > 0) {
2981 for (auto& i : evicted) {
2982 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002983 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002984 }
2985
2986 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2987 "properly", __FUNCTION__);
2988
2989 return BAD_VALUE;
2990 }
2991
2992 logConnectedOffline(offlineClientDesc->getKey(),
2993 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002994 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002995
2996 sp<IBinder> remoteCallback = offlineClient->getRemote();
2997 if (remoteCallback != nullptr) {
2998 remoteCallback->linkToDeath(this);
2999 }
3000 } // lock is destroyed, allow further connect calls
3001
3002 return OK;
3003}
3004
Austin Borgered99f642023-06-01 16:51:35 -07003005Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +00003006 int32_t torchStrength, const sp<IBinder>& clientBinder, int32_t deviceId,
3007 int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08003008 Mutex::Autolock lock(mServiceLock);
3009
3010 ATRACE_CALL();
3011 if (clientBinder == nullptr) {
3012 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
3013 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
3014 "Torch client binder in null.");
3015 }
3016
Austin Borger22c5c852024-03-08 13:31:36 -08003017 int uid = getCallingUid();
Biswarup Pal37a75182024-01-16 15:53:35 +00003018 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
3019 devicePolicy, uid);
3020 if (!cameraIdOptional.has_value()) {
3021 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
3022 unresolvedCameraId.c_str(), deviceId);
3023 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3024 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3025 }
3026 std::string cameraId = cameraIdOptional.value();
3027
Austin Borgered99f642023-06-01 16:51:35 -07003028 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08003029 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07003030 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003031 }
3032
3033 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07003034 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08003035 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07003036 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003037 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003038 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003039 }
3040
3041 StatusInternal cameraStatus = state->getStatus();
3042 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
3043 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07003044 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08003045 (int)cameraStatus);
3046 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003047 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003048 }
3049
3050 {
3051 Mutex::Autolock al(mTorchStatusMutex);
3052 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003053 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08003054 if (err != OK) {
3055 if (err == NAME_NOT_FOUND) {
3056 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003057 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003058 }
3059 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003060 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003061 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
3062 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003063 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08003064 }
3065
3066 if (status == TorchModeStatus::NOT_AVAILABLE) {
3067 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
3068 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003069 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003070 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3071 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003072 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003073 } else {
3074 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003075 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003076 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3077 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003078 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003079 }
3080 }
3081 }
3082
3083 {
3084 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003085 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08003086 }
3087 // Check if the current torch strength level is same as the new one.
3088 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07003089 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003090
Austin Borgered99f642023-06-01 16:51:35 -07003091 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003092
3093 if (err != OK) {
3094 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003095 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08003096 switch (err) {
3097 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003098 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
3099 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003100 errorCode = ERROR_ILLEGAL_ARGUMENT;
3101 break;
3102 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003103 msg = fmt::sprintf("Camera \"%s\" is in use",
3104 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003105 errorCode = ERROR_CAMERA_IN_USE;
3106 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08003107 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07003108 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08003109 "valid range.", torchStrength);
3110 errorCode = ERROR_ILLEGAL_ARGUMENT;
3111 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08003112 default:
Austin Borgered99f642023-06-01 16:51:35 -07003113 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08003114 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08003115 }
Austin Borgered99f642023-06-01 16:51:35 -07003116 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3117 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003118 }
3119
3120 {
3121 // update the link to client's death
3122 // Store the last client that turns on each camera's torch mode.
3123 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003124 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08003125 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003126 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08003127 } else {
3128 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
3129 mTorchClientMap.replaceValueAt(index, clientBinder);
3130 }
3131 clientBinder->linkToDeath(this);
3132 }
3133
Austin Borger22c5c852024-03-08 13:31:36 -08003134 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08003135 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07003136 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08003137 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07003138 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003139 }
3140 return Status::ok();
3141}
3142
malikakash73125c62023-07-21 22:44:34 +00003143Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Biswarup Pal37a75182024-01-16 15:53:35 +00003144 const sp<IBinder>& clientBinder, int32_t deviceId, int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003145 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003146
3147 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07003148 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003149 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003150 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
3151 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003152 }
3153
Austin Borger22c5c852024-03-08 13:31:36 -08003154 int uid = getCallingUid();
Biswarup Pal37a75182024-01-16 15:53:35 +00003155 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
3156 devicePolicy, uid);
3157 if (!cameraIdOptional.has_value()) {
3158 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
3159 unresolvedCameraId.c_str(), deviceId);
3160 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3161 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3162 }
3163 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003164
Austin Borgered99f642023-06-01 16:51:35 -07003165 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003166 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07003167 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003168 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003169 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07003170 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003171 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07003172 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003173 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003174 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003175 }
3176
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003177 StatusInternal cameraStatus = state->getStatus();
3178 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003179 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07003180 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
3181 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003182 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003183 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003184 }
3185
3186 {
3187 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003188 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003189 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003190 if (err != OK) {
3191 if (err == NAME_NOT_FOUND) {
3192 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003193 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003194 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003195 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003196 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003197 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07003198 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003199 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003200 }
3201
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003202 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003203 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003204 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003205 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003206 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3207 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003208 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003209 } else {
3210 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003211 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003212 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3213 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003214 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003215 }
3216 }
3217 }
3218
Ruben Brunk99e69712015-05-26 17:25:07 -07003219 {
3220 // Update UID map - this is used in the torch status changed callbacks, so must be done
3221 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003222 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003223 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003224 }
3225
Austin Borgered99f642023-06-01 16:51:35 -07003226 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003227
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003228 if (err != OK) {
3229 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003230 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003231 switch (err) {
3232 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003233 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3234 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003235 errorCode = ERROR_ILLEGAL_ARGUMENT;
3236 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003237 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003238 msg = fmt::sprintf("Camera \"%s\" is in use",
3239 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003240 errorCode = ERROR_CAMERA_IN_USE;
3241 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003242 default:
Austin Borgered99f642023-06-01 16:51:35 -07003243 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003244 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003245 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003246 errorCode = ERROR_INVALID_OPERATION;
3247 }
Austin Borgered99f642023-06-01 16:51:35 -07003248 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3249 logServiceError(msg, errorCode);
3250 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003251 }
3252
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003253 {
3254 // update the link to client's death
3255 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003256 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003257 if (enabled) {
3258 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003259 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003260 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003261 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003262 mTorchClientMap.replaceValueAt(index, clientBinder);
3263 }
3264 clientBinder->linkToDeath(this);
3265 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003266 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003267 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003268 }
3269
Austin Borger22c5c852024-03-08 13:31:36 -08003270 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003271 std::string torchState = enabled ? "on" : "off";
3272 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3273 torchState.c_str(), clientPid);
3274 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003275 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003276}
3277
Austin Borgered99f642023-06-01 16:51:35 -07003278void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3279 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3280 mTorchUidMap[cameraId].first = uid;
3281 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003282 } else {
3283 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003284 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003285 }
3286}
3287
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003288Status CameraService::notifySystemEvent(int32_t eventId,
3289 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003290 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003291 const int selfPid = getpid();
3292
3293 // Permission checks
3294 if (pid != selfPid) {
3295 // Ensure we're being called by system_server, or similar process with
3296 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003297 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003298 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003299 ALOGE("Permission Denial: cannot send updates to camera service about system"
3300 " events from pid=%d, uid=%d", pid, uid);
3301 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003302 "No permission to send updates to camera service about system events"
3303 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003304 }
3305 }
3306
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003307 ATRACE_CALL();
3308
Ruben Brunk36597b22015-03-20 22:15:57 -07003309 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003310 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003311 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003312 // from a system server crash
3313 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003314 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003315 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003316 break;
3317 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003318 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3319 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003320 if (args.size() != 1) {
3321 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3322 "USB Device Event requires 1 argument");
3323 }
3324
Valentin Iftime29e2e152021-08-13 15:17:33 +02003325 // Notify CameraProviderManager for lazy HALs
3326 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3327 std::to_string(args[0]));
3328 break;
3329 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003330 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003331 default: {
3332 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3333 eventId);
3334 break;
3335 }
3336 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003337 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003338}
3339
Emilian Peev53722fa2019-02-22 17:47:20 -08003340void CameraService::notifyMonitoredUids() {
3341 Mutex::Autolock lock(mStatusListenerLock);
3342
3343 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003344 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003345 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3346 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003347 }
3348}
3349
Austin Borgerdddb7552023-03-30 17:53:01 -07003350void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3351 Mutex::Autolock lock(mStatusListenerLock);
3352
3353 for (const auto& it : mListenerList) {
3354 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3355 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3356 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3357 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3358 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3359 }
3360 }
3361}
3362
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003363Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003364 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003365 const int selfPid = getpid();
3366
3367 // Permission checks
3368 if (pid != selfPid) {
3369 // Ensure we're being called by system_server, or similar process with
3370 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003371 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003372 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003373 ALOGE("Permission Denial: cannot send updates to camera service about device"
3374 " state changes from pid=%d, uid=%d", pid, uid);
3375 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3376 "No permission to send updates to camera service about device state"
3377 " changes from pid=%d, uid=%d", pid, uid);
3378 }
3379 }
3380
3381 ATRACE_CALL();
3382
Austin Borger18b30a72022-10-27 12:20:29 -07003383 {
3384 Mutex::Autolock lock(mServiceLock);
3385 mDeviceState = newState;
3386 }
3387
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003388 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003389
3390 return Status::ok();
3391}
3392
Emilian Peev8b64f282021-03-25 16:49:57 -07003393Status CameraService::notifyDisplayConfigurationChange() {
3394 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003395 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003396 const int selfPid = getpid();
3397
3398 // Permission checks
3399 if (callingPid != selfPid) {
3400 // Ensure we're being called by system_server, or similar process with
3401 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003402 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003403 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003404 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3405 " changes from pid=%d, uid=%d", callingPid, uid);
3406 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3407 "No permission to send updates to camera service about orientation"
3408 " changes from pid=%d, uid=%d", callingPid, uid);
3409 }
3410 }
3411
3412 Mutex::Autolock lock(mServiceLock);
3413
3414 // Don't do anything if rotate-and-crop override via cmd is active
3415 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3416
3417 const auto clients = mActiveClientManager.getAll();
3418 for (auto& current : clients) {
3419 if (current != nullptr) {
3420 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003421 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3422 basicClient->setRotateAndCropOverride(
3423 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3424 basicClient->getPackageName(),
3425 basicClient->getCameraFacing(),
3426 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003427 }
3428 }
3429 }
3430
3431 return Status::ok();
3432}
3433
Biswarup Pal37a75182024-01-16 15:53:35 +00003434// TODO(b/291736219): This to be made device-aware.
Emilian Peev8b64f282021-03-25 16:49:57 -07003435Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003436 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3437 ATRACE_CALL();
3438 if (!concurrentCameraIds) {
3439 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3440 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3441 }
3442
3443 if (!mInitialized) {
3444 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003445 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003446 return STATUS_ERROR(ERROR_DISCONNECTED,
3447 "Camera subsystem is not available");
3448 }
3449 // First call into the provider and get the set of concurrent camera
3450 // combinations
3451 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003452 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003453 for (auto &combination : concurrentCameraCombinations) {
3454 std::vector<std::string> validCombination;
3455 for (auto &cameraId : combination) {
3456 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003457 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003458 if (state == nullptr) {
3459 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3460 continue;
3461 }
3462 StatusInternal status = state->getStatus();
3463 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3464 continue;
3465 }
Austin Borgered99f642023-06-01 16:51:35 -07003466 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003467 continue;
3468 }
3469 validCombination.push_back(cameraId);
3470 }
3471 if (validCombination.size() != 0) {
3472 concurrentCameraIds->push_back(std::move(validCombination));
3473 }
3474 }
3475 return Status::ok();
3476}
3477
3478Status CameraService::isConcurrentSessionConfigurationSupported(
3479 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003480 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003481 if (!isSupported) {
3482 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3483 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3484 }
3485
3486 if (!mInitialized) {
3487 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3488 return STATUS_ERROR(ERROR_DISCONNECTED,
3489 "Camera subsystem is not available");
3490 }
3491
3492 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003493 int callingPid = getCallingPid();
3494 int callingUid = getCallingUid();
Biswarup Pale506e732024-03-27 13:46:20 +00003495 // TODO(b/291736219): Pass deviceId owning the camera if we make this method device-aware.
Austin Borger249e6592024-03-10 22:28:11 -07003496 bool hasCameraPermission = ((callingPid == getpid()) ||
Biswarup Pale506e732024-03-27 13:46:20 +00003497 hasPermissionsForCamera(callingPid, callingUid, kDefaultDeviceId));
Austin Borger249e6592024-03-10 22:28:11 -07003498 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003499 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3500 "android.permission.CAMERA needed to call"
3501 "isConcurrentSessionConfigurationSupported");
3502 }
3503
3504 status_t res =
3505 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003506 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3507 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003508 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003509 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003510 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003511 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3512 "support %s (%d)", strerror(-res), res);
3513 }
3514 return Status::ok();
3515}
3516
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003517Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3518 /*out*/
3519 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003520 return addListenerHelper(listener, cameraStatuses);
3521}
3522
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003523binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3524 std::vector<hardware::CameraStatus>* cameraStatuses) {
3525 return addListenerHelper(listener, cameraStatuses, false, true);
3526}
3527
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003528Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3529 /*out*/
3530 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003531 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003532 ATRACE_CALL();
3533
Igor Murashkinbfc99152013-02-27 12:55:20 -08003534 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003535
Ruben Brunk3450ba72015-06-16 11:00:37 -07003536 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003537 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003538 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003539 }
3540
Austin Borger22c5c852024-03-08 13:31:36 -08003541 auto clientPid = getCallingPid();
3542 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003543 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003544
Igor Murashkinbfc99152013-02-27 12:55:20 -08003545 Mutex::Autolock lock(mServiceLock);
3546
Ruben Brunkcc776712015-02-17 20:18:47 -08003547 {
3548 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003549 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003550 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003551 ALOGW("%s: Tried to add listener %p which was already subscribed",
3552 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003553 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003554 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003555 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003556
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003557 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003558 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3559 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003560 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003561 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003562 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003563 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003564 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3565 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3566 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003567 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003568 // The listener still needs to be added to the list of listeners, regardless of what
3569 // permissions the listener process has / whether it is a vendor listener. Since it might be
3570 // eligible to listen to other camera ids.
3571 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003572 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003573 }
3574
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003575 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003576 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003577 Mutex::Autolock lock(mCameraStatesLock);
3578 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003579 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3580 auto [deviceId, mappedCameraId] =
3581 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3582
3583 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003584 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003585 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3586 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003587 }
3588 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003589 // Remove the camera statuses that should be hidden from the client, we do
3590 // this after collecting the states in order to avoid holding
3591 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3592 // the same time.
3593 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3594 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003595 std::string cameraId = s.cameraId;
3596 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
3597 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM,
3598 clientUid);
3599 if (!cameraIdOptional.has_value()) {
3600 std::string msg =
3601 fmt::sprintf(
3602 "Camera %s: Invalid camera id for device id %d",
3603 s.cameraId.c_str(), s.deviceId);
3604 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3605 return true;
3606 }
3607 cameraId = cameraIdOptional.value();
3608 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3609 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3610 ALOGE("%s: Invalid camera id %s, skipping status update",
3611 __FUNCTION__, s.cameraId.c_str());
3612 return true;
3613 }
3614 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3615 clientUid);
3616 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003617
Biswarup Pal37a75182024-01-16 15:53:35 +00003618 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003619 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003620 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003621 // Add only default device cameras here, as virtual cameras currently don't support torch
3622 // anyway. Note that this is a simplification of the implementation here, and we should
3623 // change this when virtual cameras support torch.
3624 if (s.deviceId == kDefaultDeviceId) {
3625 idsChosenForCallback.insert(s.cameraId);
3626 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003627 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003628
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003629 /*
3630 * Immediately signal current torch status to this listener only
3631 * This may be a subset of all the devices, so don't include it in the response directly
3632 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003633 {
3634 Mutex::Autolock al(mTorchStatusMutex);
3635 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003636 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003637 // The camera id is visible to the client. Fine to send torch
3638 // callback.
3639 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003640 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3641 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003642 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003643 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003644 }
3645
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003646 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003647}
Ruben Brunkcc776712015-02-17 20:18:47 -08003648
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003649Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003650 ATRACE_CALL();
3651
Igor Murashkinbfc99152013-02-27 12:55:20 -08003652 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3653
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003654 if (listener == 0) {
3655 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003656 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003657 }
3658
Igor Murashkinbfc99152013-02-27 12:55:20 -08003659 Mutex::Autolock lock(mServiceLock);
3660
Ruben Brunkcc776712015-02-17 20:18:47 -08003661 {
3662 Mutex::Autolock lock(mStatusListenerLock);
3663 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003664 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003665 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003666 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003667 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003668 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003669 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003670 }
3671 }
3672
3673 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3674 __FUNCTION__, listener.get());
3675
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003676 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003677}
3678
Austin Borgered99f642023-06-01 16:51:35 -07003679Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003680
3681 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003682 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3683
3684 if (parameters == NULL) {
3685 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003686 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003687 }
3688
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003689 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003690
3691 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003692 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003693 // Error logged by caller
3694 return ret;
3695 }
3696
3697 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003698
Austin Borgered99f642023-06-01 16:51:35 -07003699 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003700
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003701 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003702}
3703
Austin Borgered99f642023-06-01 16:51:35 -07003704Status CameraService::supportsCameraApi(const std::string& unresolvedCameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003705 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003706 ATRACE_CALL();
3707
malikakashedb38962023-09-06 00:03:35 +00003708 const std::string cameraId = resolveCameraId(
Austin Borger22c5c852024-03-08 13:31:36 -08003709 unresolvedCameraId, getCallingUid());
malikakash82ed4352023-07-21 22:44:34 +00003710
Austin Borgered99f642023-06-01 16:51:35 -07003711 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003712
3713 switch (apiVersion) {
3714 case API_VERSION_1:
3715 case API_VERSION_2:
3716 break;
3717 default:
Austin Borgered99f642023-06-01 16:51:35 -07003718 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3719 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3720 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003721 }
3722
Austin Borger18b30a72022-10-27 12:20:29 -07003723 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -07003724 auto deviceVersionAndTransport = getDeviceVersion(cameraId, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003725 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003726 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3727 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3728 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003729 }
3730 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3731 int deviceVersion = deviceVersionAndTransport.first;
3732 switch (deviceVersion) {
3733 case CAMERA_DEVICE_API_VERSION_1_0:
3734 case CAMERA_DEVICE_API_VERSION_3_0:
3735 case CAMERA_DEVICE_API_VERSION_3_1:
3736 if (apiVersion == API_VERSION_2) {
3737 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003738 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003739 *isSupported = false;
3740 } else { // if (apiVersion == API_VERSION_1) {
3741 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003742 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003743 *isSupported = true;
3744 }
3745 break;
3746 case CAMERA_DEVICE_API_VERSION_3_2:
3747 case CAMERA_DEVICE_API_VERSION_3_3:
3748 case CAMERA_DEVICE_API_VERSION_3_4:
3749 case CAMERA_DEVICE_API_VERSION_3_5:
3750 case CAMERA_DEVICE_API_VERSION_3_6:
3751 case CAMERA_DEVICE_API_VERSION_3_7:
3752 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003753 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003754 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003755 break;
3756 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003757 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3758 deviceVersion, cameraId.c_str());
3759 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3760 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003761 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003762 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003763 } else {
3764 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003765 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003766 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003767}
3768
Austin Borgered99f642023-06-01 16:51:35 -07003769Status CameraService::isHiddenPhysicalCamera(const std::string& unresolvedCameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003770 /*out*/ bool *isSupported) {
3771 ATRACE_CALL();
3772
malikakashedb38962023-09-06 00:03:35 +00003773 const std::string cameraId = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08003774 getCallingUid());
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003775
Austin Borgered99f642023-06-01 16:51:35 -07003776 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3777 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003778
3779 return Status::ok();
3780}
3781
Cliff Wud8cae102021-03-11 01:37:42 +08003782Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003783 const std::string& packageName, const std::string& internalCamId,
3784 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003785 const sp<ICameraInjectionCallback>& callback,
3786 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003787 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003788 ATRACE_CALL();
3789
Austin Borgered99f642023-06-01 16:51:35 -07003790 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003791 const int pid = getCallingPid();
3792 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003793 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3794 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003795 "Permission Denial: no permission to inject camera");
3796 }
3797
3798 // Do not allow any camera injection that injects or replaces a virtual camera.
3799 auto [deviceIdForInternalCamera, _] =
3800 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3801 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3802 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3803 "Cannot replace a virtual camera");
3804 }
3805 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3806 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3807 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3808 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3809 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003810 }
3811
3812 ALOGV(
3813 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3814 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003815 __FUNCTION__, packageName.c_str(),
3816 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003817
Cliff Wud3a05312021-04-26 23:07:31 +08003818 {
3819 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003820 mInjectionInternalCamId = internalCamId;
3821 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003822 mInjectionStatusListener->addListener(callback);
3823 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003824 status_t res = NO_ERROR;
3825 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3826 // If the client already exists, we can directly connect to the camera device through the
3827 // client's injectCamera(), otherwise we need to wait until the client is established
3828 // (execute connectHelper()) before injecting the camera to the camera device.
3829 if (clientDescriptor != nullptr) {
3830 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003831 sp<BasicClient> clientSp = clientDescriptor->getValue();
3832 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3833 if(res != OK) {
3834 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3835 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003836 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003837 }
3838 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003839 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003840 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3841 }
3842 } else {
3843 mInjectionInitPending = true;
3844 }
3845 }
Cliff Wud8cae102021-03-11 01:37:42 +08003846
Cliff Wud3a05312021-04-26 23:07:31 +08003847 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003848}
3849
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003850Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003851 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003852 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3853 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3854 return Status::ok();
3855}
3856
Ruben Brunkcc776712015-02-17 20:18:47 -08003857void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003858 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003859 for (auto& i : mActiveClientManager.getAll()) {
3860 auto clientSp = i->getValue();
3861 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003862 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003863 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003864 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003865 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003866 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003867}
3868
Ruben Brunkcc776712015-02-17 20:18:47 -08003869bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003870 bool ret = false;
3871 {
3872 // Acquire mServiceLock and prevent other clients from connecting
3873 std::unique_ptr<AutoConditionLock> lock =
3874 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003875
Ruben Brunkcc776712015-02-17 20:18:47 -08003876 std::vector<sp<BasicClient>> evicted;
3877 for (auto& i : mActiveClientManager.getAll()) {
3878 auto clientSp = i->getValue();
3879 if (clientSp.get() == nullptr) {
3880 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3881 mActiveClientManager.remove(i);
3882 continue;
3883 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003884 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003885 mActiveClientManager.remove(i);
3886 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003887
Ruben Brunkcc776712015-02-17 20:18:47 -08003888 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003889 clientSp->notifyError(
3890 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003891 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003892 }
3893 }
3894
Ruben Brunkcc776712015-02-17 20:18:47 -08003895 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3896 // other clients from connecting in mServiceLockWrapper if held
3897 mServiceLock.unlock();
3898
Ruben Brunk36597b22015-03-20 22:15:57 -07003899 // Do not clear caller identity, remote caller should be client proccess
3900
Ruben Brunkcc776712015-02-17 20:18:47 -08003901 for (auto& i : evicted) {
3902 if (i.get() != nullptr) {
3903 i->disconnect();
3904 ret = true;
3905 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003906 }
3907
Ruben Brunkcc776712015-02-17 20:18:47 -08003908 // Reacquire mServiceLock
3909 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003910
Ruben Brunkcc776712015-02-17 20:18:47 -08003911 } // lock is destroyed, allow further connect calls
3912
3913 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003914}
3915
Ruben Brunkcc776712015-02-17 20:18:47 -08003916std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003917 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003918 std::shared_ptr<CameraState> state;
3919 {
3920 Mutex::Autolock lock(mCameraStatesLock);
3921 auto iter = mCameraStates.find(cameraId);
3922 if (iter != mCameraStates.end()) {
3923 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003924 }
3925 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003926 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003927}
3928
Austin Borgered99f642023-06-01 16:51:35 -07003929sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003930 // Remove from active clients list
3931 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3932 if (clientDescriptorPtr == nullptr) {
3933 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003934 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003935 return sp<BasicClient>{nullptr};
3936 }
3937
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003938 sp<BasicClient> client = clientDescriptorPtr->getValue();
3939 if (client.get() != nullptr) {
3940 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3941 }
3942 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003943}
3944
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003945void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003946 // Acquire mServiceLock and prevent other clients from connecting
3947 std::unique_ptr<AutoConditionLock> lock =
3948 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3949
Ruben Brunk6267b532015-04-30 17:44:07 -07003950 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003951 for (size_t i = 0; i < newUserIds.size(); i++) {
3952 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003953 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003954 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003955 return;
3956 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003957 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003958 }
3959
Ruben Brunka8ca9152015-04-07 14:23:40 -07003960
Ruben Brunk6267b532015-04-30 17:44:07 -07003961 if (newAllowedUsers == mAllowedUsers) {
3962 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3963 return;
3964 }
3965
3966 logUserSwitch(mAllowedUsers, newAllowedUsers);
3967
3968 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003969
3970 // Current user has switched, evict all current clients.
3971 std::vector<sp<BasicClient>> evicted;
3972 for (auto& i : mActiveClientManager.getAll()) {
3973 auto clientSp = i->getValue();
3974
3975 if (clientSp.get() == nullptr) {
3976 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3977 continue;
3978 }
3979
Ruben Brunk6267b532015-04-30 17:44:07 -07003980 // Don't evict clients that are still allowed.
3981 uid_t clientUid = clientSp->getClientUid();
3982 userid_t clientUserId = multiuser_get_user_id(clientUid);
3983 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3984 continue;
3985 }
3986
Ruben Brunk36597b22015-03-20 22:15:57 -07003987 evicted.push_back(clientSp);
3988
Ruben Brunk36597b22015-03-20 22:15:57 -07003989 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003990 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003991
Ruben Brunk36597b22015-03-20 22:15:57 -07003992 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003993 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003994 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003995 " to user switch.", i->getKey().c_str(),
3996 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003997 i->getOwnerId(), i->getPriority().getScore(),
3998 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003999
4000 }
4001
4002 // Do not hold mServiceLock while disconnecting clients, but retain the condition
4003 // blocking other clients from connecting in mServiceLockWrapper if held.
4004 mServiceLock.unlock();
4005
4006 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08004007 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07004008
4009 for (auto& i : evicted) {
4010 i->disconnect();
4011 }
4012
Austin Borger22c5c852024-03-08 13:31:36 -08004013 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07004014
4015 // Reacquire mServiceLock
4016 mServiceLock.lock();
4017}
Ruben Brunkcc776712015-02-17 20:18:47 -08004018
Austin Borgered99f642023-06-01 16:51:35 -07004019void CameraService::logEvent(const std::string &event) {
4020 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07004021 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07004022 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07004023 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07004024 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07004025 mEventLog.add(msg);
4026 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
4027 // Error event not added to the dumpsys log before
4028 mEventLog.add(msg);
4029 sServiceErrorEventSet.insert(msg);
4030 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004031}
4032
Austin Borgered99f642023-06-01 16:51:35 -07004033void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
4034 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004035 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004036 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
4037 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004038}
4039
Austin Borgered99f642023-06-01 16:51:35 -07004040void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
4041 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004042 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004043 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
4044 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004045}
4046
Austin Borgered99f642023-06-01 16:51:35 -07004047void CameraService::logConnected(const std::string &cameraId, int clientPid,
4048 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004049 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004050 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
4051 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004052}
4053
Austin Borgered99f642023-06-01 16:51:35 -07004054void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
4055 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004056 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004057 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
4058 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004059}
4060
Austin Borgered99f642023-06-01 16:51:35 -07004061void CameraService::logRejected(const std::string &cameraId, int clientPid,
4062 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004063 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07004064 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
4065 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004066}
4067
Austin Borgered99f642023-06-01 16:51:35 -07004068void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
4069 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07004070 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07004071 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
4072 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07004073}
4074
Ruben Brunk6267b532015-04-30 17:44:07 -07004075void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
4076 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07004077 std::string newUsers = toString(newUserIds);
4078 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004079 if (oldUsers.size() == 0) {
4080 oldUsers = "<None>";
4081 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07004082 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07004083 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
4084 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004085}
4086
Austin Borgered99f642023-06-01 16:51:35 -07004087void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004088 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004089 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004090}
4091
Austin Borgered99f642023-06-01 16:51:35 -07004092void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004093 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004094 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004095}
4096
Austin Borgered99f642023-06-01 16:51:35 -07004097void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004098 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004099 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07004100}
4101
Austin Borgered99f642023-06-01 16:51:35 -07004102void CameraService::logServiceError(const std::string &msg, int errorCode) {
4103 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
4104 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004105}
4106
Ruben Brunk36597b22015-03-20 22:15:57 -07004107status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4108 uint32_t flags) {
4109
Mathias Agopian65ab4712010-07-14 17:59:35 -07004110 // Permission checks
4111 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004112 case SHELL_COMMAND_TRANSACTION: {
4113 int in = data.readFileDescriptor();
4114 int out = data.readFileDescriptor();
4115 int err = data.readFileDescriptor();
4116 int argc = data.readInt32();
4117 Vector<String16> args;
4118 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
4119 args.add(data.readString16());
4120 }
4121 sp<IBinder> unusedCallback;
4122 sp<IResultReceiver> resultReceiver;
4123 status_t status;
4124 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
4125 return status;
4126 }
4127 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
4128 return status;
4129 }
4130 status = shellCommand(in, out, err, args);
4131 if (resultReceiver != nullptr) {
4132 resultReceiver->send(status);
4133 }
4134 return NO_ERROR;
4135 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004136 }
4137
4138 return BnCameraService::onTransact(code, data, reply, flags);
4139}
4140
Mathias Agopian65ab4712010-07-14 17:59:35 -07004141// We share the media players for shutter and recording sound for all clients.
4142// A reference count is kept to determine when we will actually release the
4143// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09004144sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
4145 sp<MediaPlayer> mp = new MediaPlayer();
4146 status_t error;
4147 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08004148 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09004149 error = mp->prepare();
4150 }
4151 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004152 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09004153 mp->disconnect();
4154 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004155 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004156 }
4157 return mp;
4158}
4159
username5755fea2018-12-27 09:48:08 +08004160void CameraService::increaseSoundRef() {
4161 Mutex::Autolock lock(mSoundLock);
4162 mSoundRef++;
4163}
4164
4165void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004166 ATRACE_CALL();
4167
username5755fea2018-12-27 09:48:08 +08004168 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
4169 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
4170 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
4171 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
4172 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4173 }
4174 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
4175 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4176 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4177 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004178 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08004179 }
4180 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4181 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4182 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4183 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4184 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004185 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004186}
4187
username5755fea2018-12-27 09:48:08 +08004188void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004189 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004190 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004191 if (--mSoundRef) return;
4192
4193 for (int i = 0; i < NUM_SOUNDS; i++) {
4194 if (mSoundPlayer[i] != 0) {
4195 mSoundPlayer[i]->disconnect();
4196 mSoundPlayer[i].clear();
4197 }
4198 }
4199}
4200
4201void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004202 ATRACE_CALL();
4203
Mathias Agopian65ab4712010-07-14 17:59:35 -07004204 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004205 if (kind < 0 || kind >= NUM_SOUNDS) {
4206 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4207 return;
4208 }
4209
Mathias Agopian65ab4712010-07-14 17:59:35 -07004210 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004211 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004212 sp<MediaPlayer> player = mSoundPlayer[kind];
4213 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004214 player->seekTo(0);
4215 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004216 }
4217}
4218
4219// ----------------------------------------------------------------------------
4220
4221CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004222 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004223 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004224 const std::string& clientPackageName, bool systemNativeClient,
4225 const std::optional<std::string>& clientFeatureId,
4226 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004227 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004228 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004229 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004230 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004231 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07004232 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004233 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004234 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004235 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004236 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004237 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004238{
Austin Borger22c5c852024-03-08 13:31:36 -08004239 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004240 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004241
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004242 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004243
username5755fea2018-12-27 09:48:08 +08004244 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004245
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004246 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004247}
4248
Mathias Agopian65ab4712010-07-14 17:59:35 -07004249// tear down the client
4250CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004251 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004252 mDestructionStarted = true;
4253
username5755fea2018-12-27 09:48:08 +08004254 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004255 // unconditionally disconnect. function is idempotent
4256 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004257}
4258
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004259sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4260
Igor Murashkin634a5152013-02-20 17:15:11 -08004261CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004262 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004263 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004264 const std::string& clientPackageName, bool nativeClient,
4265 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004266 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004267 int servicePid, bool overrideToPortrait):
Austin Borger249e6592024-03-10 22:28:11 -07004268 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004269 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004270 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004271 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4272 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004273 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004274 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004275 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07004276 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004277 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004278 mRemoteBinder(remoteCallback),
4279 mOpsActive(false),
4280 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004281{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004282 if (sCameraService == nullptr) {
4283 sCameraService = cameraService;
4284 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004285
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004286 // There are 2 scenarios in which a client won't have AppOps operations
4287 // (both scenarios : native clients)
4288 // 1) It's an system native client*, the package name will be empty
4289 // and it will return from this function in the previous if condition
4290 // (This is the same as the previously existing behavior).
4291 // 2) It is a system native client, but its package name has been
4292 // modified for debugging, however it still must not use AppOps since
4293 // the package name is not a real one.
4294 //
4295 // * system native client - native client with UID < AID_APP_START. It
4296 // doesn't exclude clients not on the system partition.
4297 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004298 mAppOpsManager = std::make_unique<AppOpsManager>();
4299 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004300
Charles Chenf075f082024-03-04 23:32:55 +00004301 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004302}
4303
4304CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004305 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004306 mDestructionStarted = true;
4307}
4308
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004309binder::Status CameraService::BasicClient::disconnect() {
4310 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004311 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004312 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004313 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004314 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004315
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004316 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004317 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004318 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004319 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004320
4321 sp<IBinder> remote = getRemote();
4322 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004323 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004324 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004325
4326 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004327 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004328 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004329 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004330 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004331
Igor Murashkincba2c162013-03-20 15:56:31 -07004332 // client shouldn't be able to call into us anymore
4333 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004334
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004335 const auto& mActivityManager = getActivityManager();
4336 if (mActivityManager) {
4337 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004338 getCallingUid(),
4339 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004340 }
4341
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004342 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004343}
4344
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004345status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4346 // No dumping of clients directly over Binder,
4347 // must go through CameraService::dump
4348 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004349 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004350 return OK;
4351}
4352
Austin Borgered99f642023-06-01 16:51:35 -07004353status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004354 // Can't watch tags directly, must go through CameraService::startWatchingTags
4355 return OK;
4356}
4357
4358status_t CameraService::BasicClient::stopWatchingTags(int) {
4359 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4360 return OK;
4361}
4362
4363status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4364 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4365 return OK;
4366}
4367
Austin Borgered99f642023-06-01 16:51:35 -07004368std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004369 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004370}
4371
Emilian Peev8b64f282021-03-25 16:49:57 -07004372int CameraService::BasicClient::getCameraFacing() const {
4373 return mCameraFacing;
4374}
4375
4376int CameraService::BasicClient::getCameraOrientation() const {
4377 return mOrientation;
4378}
Ruben Brunkcc776712015-02-17 20:18:47 -08004379
4380int CameraService::BasicClient::getClientPid() const {
4381 return mClientPid;
4382}
4383
Ruben Brunk6267b532015-04-30 17:44:07 -07004384uid_t CameraService::BasicClient::getClientUid() const {
4385 return mClientUid;
4386}
4387
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004388bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4389 // Defaults to API2.
4390 return level == API_2;
4391}
4392
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004393status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004394 {
4395 Mutex::Autolock l(mAudioRestrictionLock);
4396 mAudioRestriction = mode;
4397 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004398 sCameraService->updateAudioRestriction();
4399 return OK;
4400}
4401
4402int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004403 return sCameraService->updateAudioRestriction();
4404}
4405
4406int32_t CameraService::BasicClient::getAudioRestriction() const {
4407 Mutex::Autolock l(mAudioRestrictionLock);
4408 return mAudioRestriction;
4409}
4410
4411bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4412 switch (mode) {
4413 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4414 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4415 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4416 return true;
4417 default:
4418 return false;
4419 }
4420}
4421
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004422status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4423 if (mode == AppOpsManager::MODE_ERRORED) {
4424 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004425 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004426 return PERMISSION_DENIED;
4427 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4428 // If the calling Uid is trusted (a native service), the AppOpsManager could
4429 // return MODE_IGNORED. Do not treat such case as error.
4430 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4431 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004432
4433 bool isCameraPrivacyEnabled;
4434 if (flags::camera_privacy_allowlist()) {
4435 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4436 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4437 } else {
4438 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004439 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004440 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004441 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4442 // We prefer to successfully open the camera and perform camera muting
4443 // or blocking in connectHelper as handleAppOpMode can be called before the
4444 // connection has been fully established and at that time camera muting
4445 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004446 if (!isUidActive || !isCameraPrivacyEnabled) {
Austin Borgerfd05d982024-04-22 15:54:50 -07004447 ALOGI("Camera %s: Access for \"%s\" has been restricted."
4448 "uid active: %s, privacy enabled: %s", mCameraIdStr.c_str(),
4449 mClientPackageName.c_str(), isUidActive ? "true" : "false",
4450 isCameraPrivacyEnabled ? "true" : "false");
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004451 // Return the same error as for device policy manager rejection
4452 return -EACCES;
4453 }
4454 }
4455 return OK;
4456}
4457
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004458status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004459 ATRACE_CALL();
4460
Igor Murashkine6800ce2013-03-04 17:25:57 -08004461 {
4462 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004463 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004464 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004465 if (mAppOpsManager != nullptr) {
4466 // Notify app ops that the camera is not available
4467 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004468
4469 if (flags::watch_foreground_changes()) {
4470 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4471 toString16(mClientPackageName),
4472 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4473 } else {
4474 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004475 toString16(mClientPackageName), mOpsCallback);
Austin Borgerca1e0062023-06-28 11:32:55 -07004476 }
Igor Murashkine6800ce2013-03-04 17:25:57 -08004477
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004478 // Just check for camera acccess here on open - delay startOp until
4479 // camera frames start streaming in startCameraStreamingOps
4480 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004481 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004482 status_t res = handleAppOpMode(mode);
4483 if (res != OK) {
4484 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004485 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004486 }
4487
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004488 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004489
4490 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004491 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004492
Austin Borgerdddb7552023-03-30 17:53:01 -07004493 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004494
Shuzhen Wang695044d2020-03-06 09:02:23 -08004495 // Notify listeners of camera open/close status
4496 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4497
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004498 return OK;
4499}
4500
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004501status_t CameraService::BasicClient::startCameraStreamingOps() {
4502 ATRACE_CALL();
4503
4504 if (!mOpsActive) {
4505 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4506 return INVALID_OPERATION;
4507 }
4508 if (mOpsStreaming) {
4509 ALOGV("%s: Streaming already active!", __FUNCTION__);
4510 return OK;
4511 }
4512
4513 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004514 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004515
4516 if (mAppOpsManager != nullptr) {
4517 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004518 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4519 toString16(mClientFeatureId),
4520 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004521 status_t res = handleAppOpMode(mode);
4522 if (res != OK) {
4523 return res;
4524 }
4525 }
4526
4527 mOpsStreaming = true;
4528
4529 return OK;
4530}
4531
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004532status_t CameraService::BasicClient::noteAppOp() {
4533 ATRACE_CALL();
4534
4535 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004536 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004537
4538 // noteAppOp is only used for when camera mute is not supported, in order
4539 // to trigger the sensor privacy "Unblock" dialog
4540 if (mAppOpsManager != nullptr) {
4541 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004542 toString16(mClientPackageName), toString16(mClientFeatureId),
4543 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004544 status_t res = handleAppOpMode(mode);
4545 if (res != OK) {
4546 return res;
4547 }
4548 }
4549
4550 return OK;
4551}
4552
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004553status_t CameraService::BasicClient::finishCameraStreamingOps() {
4554 ATRACE_CALL();
4555
4556 if (!mOpsActive) {
4557 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4558 return INVALID_OPERATION;
4559 }
4560 if (!mOpsStreaming) {
4561 ALOGV("%s: Streaming not active!", __FUNCTION__);
4562 return OK;
4563 }
4564
4565 if (mAppOpsManager != nullptr) {
4566 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004567 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004568 mOpsStreaming = false;
4569 }
4570
4571 return OK;
4572}
4573
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004574status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004575 ATRACE_CALL();
4576
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004577 if (mOpsStreaming) {
4578 // Make sure we've notified everyone about camera stopping
4579 finishCameraStreamingOps();
4580 }
4581
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004582 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004583 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004584 mOpsActive = false;
4585
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004586 // This function is called when a client disconnects. This should
4587 // release the camera, but actually only if it was in a proper
4588 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004589 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004590 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004591
Ruben Brunkcc776712015-02-17 20:18:47 -08004592 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004593 sCameraService->updateStatus(StatusInternal::PRESENT,
4594 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004595 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004596 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004597 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4598 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004599 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004600 mOpsCallback.clear();
4601
Austin Borgerdddb7552023-03-30 17:53:01 -07004602 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004603
Shuzhen Wang695044d2020-03-06 09:02:23 -08004604 // Notify listeners of camera open/close status
4605 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4606
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004607 return OK;
4608}
4609
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004610void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004611 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004612 if (mAppOpsManager == nullptr) {
4613 return;
4614 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004615 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004616 if (op != AppOpsManager::OP_CAMERA) {
4617 ALOGW("Unexpected app ops notification received: %d", op);
4618 return;
4619 }
4620
4621 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004622 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004623 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004624 ALOGV("checkOp returns: %d, %s ", res,
4625 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4626 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4627 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4628 "UNKNOWN");
4629
Shuzhen Wang64900852021-02-05 09:03:29 -08004630 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004631 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4632 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004633 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004634 } else if (res == AppOpsManager::MODE_IGNORED) {
4635 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004636
Austin Borgerca1e0062023-06-28 11:32:55 -07004637 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4638 // If not visible, but still active, then we want to block instead of muting the camera.
4639 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4640 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4641
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004642 bool isCameraPrivacyEnabled;
4643 if (flags::camera_privacy_allowlist()) {
4644 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4645 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4646 } else {
4647 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004648 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004649 }
4650
4651 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004652 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4653 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4654 isCameraPrivacyEnabled);
4655 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4656 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4657 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004658 if (!mUidIsTrusted) {
Austin Borgerca1e0062023-06-28 11:32:55 -07004659 if (flags::watch_foreground_changes()) {
4660 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4661 setCameraMute(true);
4662 } else {
4663 block();
4664 }
4665 } else {
4666 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4667 setCameraMute(true);
4668 } else if (!isUidActive
4669 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4670 block();
4671 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004672 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004673 }
Evan Severson09ab4002021-02-10 14:15:19 -08004674 } else if (res == AppOpsManager::MODE_ALLOWED) {
4675 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004676 }
4677}
4678
Svet Ganova453d0d2018-01-11 15:37:58 -08004679void CameraService::BasicClient::block() {
4680 ATRACE_CALL();
4681
4682 // Reset the client PID to allow server-initiated disconnect,
4683 // and to prevent further calls by client.
Austin Borger22c5c852024-03-08 13:31:36 -08004684 mClientPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004685 CaptureResultExtras resultExtras; // a dummy result (invalid)
4686 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4687 disconnect();
4688}
4689
Mathias Agopian65ab4712010-07-14 17:59:35 -07004690// ----------------------------------------------------------------------------
4691
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004692void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004693 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004694 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004695 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4696 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4697 api1ErrorCode = CAMERA_ERROR_DISABLED;
4698 }
4699 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004700 } else {
4701 ALOGE("mRemoteCallback is NULL!!");
4702 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004703}
4704
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004705// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004706binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004707 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004708 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004709}
4710
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004711bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4712 return level == API_1;
4713}
4714
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004715CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4716 mClient(client) {
4717}
4718
4719void CameraService::Client::OpsCallback::opChanged(int32_t op,
4720 const String16& packageName) {
4721 sp<BasicClient> client = mClient.promote();
4722 if (client != NULL) {
4723 client->opChanged(op, packageName);
4724 }
4725}
4726
Mathias Agopian65ab4712010-07-14 17:59:35 -07004727// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004728// UidPolicy
4729// ----------------------------------------------------------------------------
4730
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004731void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004732 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004733 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004734
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004735 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004736 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004737 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004738 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004739 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4740 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004741 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004742 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004743 if (res == OK) {
4744 mRegistered = true;
4745 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004746 } else {
4747 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004748 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004749}
4750
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004751void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004752 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004753 return;
4754 }
4755
4756 registerWithActivityManager();
4757}
4758
4759void CameraService::UidPolicy::registerSelf() {
4760 // Use check service to see if the activity service is available
4761 // If not available then register for notifications, instead of blocking
4762 // till the service is ready
4763 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004764 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004765 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004766 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004767 } else {
4768 registerWithActivityManager();
4769 }
4770}
4771
Svet Ganova453d0d2018-01-11 15:37:58 -08004772void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004773 Mutex::Autolock _l(mUidLock);
4774
Steven Moreland2f348142019-07-02 15:59:07 -07004775 mAm.unregisterUidObserver(this);
4776 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004777 mRegistered = false;
4778 mActiveUids.clear();
4779 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004780}
4781
4782void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4783 onUidIdle(uid, disabled);
4784}
4785
4786void CameraService::UidPolicy::onUidActive(uid_t uid) {
4787 Mutex::Autolock _l(mUidLock);
4788 mActiveUids.insert(uid);
4789}
4790
4791void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4792 bool deleted = false;
4793 {
4794 Mutex::Autolock _l(mUidLock);
4795 if (mActiveUids.erase(uid) > 0) {
4796 deleted = true;
4797 }
4798 }
4799 if (deleted) {
4800 sp<CameraService> service = mService.promote();
4801 if (service != nullptr) {
4802 service->blockClientsForUid(uid);
4803 }
4804 }
4805}
4806
Emilian Peev53722fa2019-02-22 17:47:20 -08004807void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004808 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004809 bool procStateChange = false;
4810 {
4811 Mutex::Autolock _l(mUidLock);
4812 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4813 mMonitoredUids[uid].procState != procState) {
4814 mMonitoredUids[uid].procState = procState;
4815 procStateChange = true;
4816 }
4817 }
4818
4819 if (procStateChange) {
4820 sp<CameraService> service = mService.promote();
4821 if (service != nullptr) {
4822 service->notifyMonitoredUids();
4823 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004824 }
4825}
4826
Austin Borgerdddb7552023-03-30 17:53:01 -07004827/**
4828 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4829 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4830 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4831 * monitoredUids. If it is revised above some other monitoredUid, signal
4832 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4833 * foreground apps in split screen - state changes will capture all other cases.
4834 */
4835void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4836 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004837 {
4838 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004839 auto it = mMonitoredUids.find(uid);
4840
4841 if (it != mMonitoredUids.end()) {
4842 if (it->second.hasCamera) {
4843 for (auto &monitoredUid : mMonitoredUids) {
4844 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004845 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004846 notifyUidSet.emplace(monitoredUid.first);
4847 }
4848 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004849 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004850 notifyUidSet.emplace(uid);
4851 } else {
4852 for (auto &monitoredUid : mMonitoredUids) {
4853 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004854 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004855 notifyUidSet.emplace(uid);
4856 }
4857 }
4858 }
4859 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004860 }
4861 }
4862
Austin Borgerdddb7552023-03-30 17:53:01 -07004863 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004864 sp<CameraService> service = mService.promote();
4865 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004866 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004867 }
4868 }
4869}
4870
Austin Borgerdddb7552023-03-30 17:53:01 -07004871/**
4872 * Register a uid for monitoring, and note whether it owns a camera.
4873 */
4874void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004875 Mutex::Autolock _l(mUidLock);
4876 auto it = mMonitoredUids.find(uid);
4877 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004878 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004879 } else {
Austin Borger65577682022-02-17 00:25:43 +00004880 MonitoredUid monitoredUid;
4881 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004882 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004883 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004884 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004885 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004886 if (res != OK) {
4887 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4888 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004889 }
4890
4891 if (openCamera) {
4892 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004893 }
4894}
4895
Austin Borgerdddb7552023-03-30 17:53:01 -07004896/**
4897 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4898 */
4899void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004900 Mutex::Autolock _l(mUidLock);
4901 auto it = mMonitoredUids.find(uid);
4902 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004903 it->second.refCount--;
4904 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004905 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004906 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004907 if (res != OK) {
4908 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4909 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004910 } else if (closeCamera) {
4911 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004912 }
4913 } else {
4914 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4915 }
4916}
4917
Austin Borgered99f642023-06-01 16:51:35 -07004918bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004919 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004920 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004921}
4922
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004923static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4924static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004925
Austin Borgered99f642023-06-01 16:51:35 -07004926bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004927 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004928 // If activity manager is unreachable, assume everything is active
4929 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004930 return true;
4931 }
4932 auto it = mOverrideUids.find(uid);
4933 if (it != mOverrideUids.end()) {
4934 return it->second;
4935 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004936 bool active = mActiveUids.find(uid) != mActiveUids.end();
4937 if (!active) {
4938 // We want active UIDs to always access camera with their first attempt since
4939 // there is no guarantee the app is robustly written and would retry getting
4940 // the camera on failure. The inverse case is not a problem as we would take
4941 // camera away soon once we get the callback that the uid is no longer active.
4942 ActivityManager am;
4943 // Okay to access with a lock held as UID changes are dispatched without
4944 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004945 int64_t startTimeMillis = 0;
4946 do {
4947 // TODO: Fix this b/109950150!
4948 // Okay this is a hack. There is a race between the UID turning active and
4949 // activity being resumed. The proper fix is very risky, so we temporary add
4950 // some polling which should happen pretty rarely anyway as the race is hard
4951 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004952 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004953 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004954 if (active) {
4955 break;
4956 }
4957 if (startTimeMillis <= 0) {
4958 startTimeMillis = uptimeMillis();
4959 }
4960 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004961 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004962 if (remainingTimeMillis <= 0) {
4963 break;
4964 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004965 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4966
4967 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004968 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004969 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004970 } while (true);
4971
Svet Ganov7b4ab782018-03-25 12:48:10 -07004972 if (active) {
4973 // Now that we found out the UID is actually active, cache that
4974 mActiveUids.insert(uid);
4975 }
4976 }
4977 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004978}
4979
Varun Shahb42f1eb2019-04-16 14:45:13 -07004980int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4981 Mutex::Autolock _l(mUidLock);
4982 return getProcStateLocked(uid);
4983}
4984
4985int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4986 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4987 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004988 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004989 }
4990 return procState;
4991}
4992
Austin Borgered99f642023-06-01 16:51:35 -07004993void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4994 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004995 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004996}
4997
Austin Borgered99f642023-06-01 16:51:35 -07004998void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004999 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08005000}
5001
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07005002void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
5003 Mutex::Autolock _l(mUidLock);
5004 ALOGV("UidPolicy: ActivityManager has died");
5005 mRegistered = false;
5006 mActiveUids.clear();
5007}
5008
Austin Borgered99f642023-06-01 16:51:35 -07005009void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07005010 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005011 bool wasActive = false;
5012 bool isActive = false;
5013 {
5014 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07005015 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08005016 mOverrideUids.erase(uid);
5017 if (insert) {
5018 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
5019 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07005020 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08005021 }
5022 if (wasActive != isActive && !isActive) {
5023 sp<CameraService> service = mService.promote();
5024 if (service != nullptr) {
5025 service->blockClientsForUid(uid);
5026 }
5027 }
5028}
5029
5030// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08005031// SensorPrivacyPolicy
5032// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005033
5034void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
5035{
Michael Grooverd1d435a2018-12-18 17:39:42 -08005036 Mutex::Autolock _l(mSensorPrivacyLock);
5037 if (mRegistered) {
5038 return;
5039 }
Evan Severson09ab4002021-02-10 14:15:19 -08005040 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08005041 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00005042 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005043 mSpm.addToggleSensorPrivacyListener(this);
5044 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005045 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005046 if (flags::camera_privacy_allowlist()) {
5047 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
5048 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
5049 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5050 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005051 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005052 if (res == OK) {
5053 mRegistered = true;
5054 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
5055 }
5056}
5057
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005058void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
5059 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07005060 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005061 return;
5062 }
5063
5064 registerWithSensorPrivacyManager();
5065}
5066
5067void CameraService::SensorPrivacyPolicy::registerSelf() {
5068 // Use checkservice to see if the sensor_privacy service is available
5069 // If service is not available then register for notification
5070 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07005071 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005072 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07005073 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005074 } else {
5075 registerWithSensorPrivacyManager();
5076 }
5077}
5078
Michael Grooverd1d435a2018-12-18 17:39:42 -08005079void CameraService::SensorPrivacyPolicy::unregisterSelf() {
5080 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08005081 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00005082 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005083 mSpm.removeToggleSensorPrivacyListener(this);
5084 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005085 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005086 mRegistered = false;
5087 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
5088}
5089
5090bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005091 if (!mRegistered) {
5092 registerWithSensorPrivacyManager();
5093 }
5094
Michael Grooverd1d435a2018-12-18 17:39:42 -08005095 Mutex::Autolock _l(mSensorPrivacyLock);
5096 return mSensorPrivacyEnabled;
5097}
5098
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005099int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
5100 if (!mRegistered) {
5101 registerWithSensorPrivacyManager();
5102 }
5103
5104 Mutex::Autolock _l(mSensorPrivacyLock);
5105 return mCameraPrivacyState;
5106}
5107
Evan Seversond0b69922022-01-27 10:47:34 -08005108bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08005109 if (!hasCameraPrivacyFeature()) {
5110 return false;
5111 }
Evan Seversond0b69922022-01-27 10:47:34 -08005112 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08005113}
5114
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005115bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
5116 if (!hasCameraPrivacyFeature()) {
Jyoti Bhayana5882b032024-04-26 11:18:58 -07005117 return false;
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005118 }
5119 return mSpm.isCameraPrivacyEnabled(packageName);
5120}
5121
Evan Seversond0b69922022-01-27 10:47:34 -08005122binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005123 int toggleType, int sensor, bool enabled) {
5124 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
5125 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
5126 {
5127 Mutex::Autolock _l(mSensorPrivacyLock);
5128 mSensorPrivacyEnabled = enabled;
5129 }
5130 // if sensor privacy is enabled then block all clients from accessing the camera
5131 if (enabled) {
5132 sp<CameraService> service = mService.promote();
5133 if (service != nullptr) {
5134 service->blockAllClients();
5135 }
5136 }
5137 }
5138 return binder::Status::ok();
5139}
5140
5141binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
5142 int, int sensor, int state) {
5143 if (!flags::camera_privacy_allowlist()
5144 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
5145 return binder::Status::ok();
5146 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08005147 {
5148 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005149 mCameraPrivacyState = state;
5150 }
5151 sp<CameraService> service = mService.promote();
5152 if (!service) {
5153 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005154 }
5155 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005156 if (state == SensorPrivacyManager::ENABLED) {
5157 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08005158 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005159 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005160 }
5161 return binder::Status::ok();
5162}
5163
5164void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
5165 Mutex::Autolock _l(mSensorPrivacyLock);
5166 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
5167 mRegistered = false;
5168}
5169
Evan Severson09ab4002021-02-10 14:15:19 -08005170bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08005171 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
5172 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5173 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
5174 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5175 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08005176}
5177
Michael Grooverd1d435a2018-12-18 17:39:42 -08005178// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005179// CameraState
5180// ----------------------------------------------------------------------------
5181
Austin Borgered99f642023-06-01 16:51:35 -07005182CameraService::CameraState::CameraState(const std::string& id, int cost,
5183 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005184 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005185 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005186 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005187
5188CameraService::CameraState::~CameraState() {}
5189
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005190CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005191 Mutex::Autolock lock(mStatusLock);
5192 return mStatus;
5193}
5194
Austin Borgered99f642023-06-01 16:51:35 -07005195std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005196 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005197 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005198 return res;
5199}
5200
Ruben Brunkcc776712015-02-17 20:18:47 -08005201CameraParameters CameraService::CameraState::getShimParams() const {
5202 return mShimParams;
5203}
5204
5205void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5206 mShimParams = params;
5207}
5208
5209int CameraService::CameraState::getCost() const {
5210 return mCost;
5211}
5212
Austin Borgered99f642023-06-01 16:51:35 -07005213std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005214 return mConflicting;
5215}
5216
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005217SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5218 return mSystemCameraKind;
5219}
5220
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005221bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5222 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5223 != mPhysicalCameras.end();
5224}
5225
Austin Borgered99f642023-06-01 16:51:35 -07005226bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005227 Mutex::Autolock lock(mStatusLock);
5228 auto result = mUnavailablePhysicalIds.insert(physicalId);
5229 return result.second;
5230}
5231
Austin Borgered99f642023-06-01 16:51:35 -07005232bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005233 Mutex::Autolock lock(mStatusLock);
5234 auto count = mUnavailablePhysicalIds.erase(physicalId);
5235 return count > 0;
5236}
5237
Austin Borgered99f642023-06-01 16:51:35 -07005238void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005239 Mutex::Autolock lock(mStatusLock);
5240 mClientPackage = clientPackage;
5241}
5242
Austin Borgered99f642023-06-01 16:51:35 -07005243std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005244 Mutex::Autolock lock(mStatusLock);
5245 return mClientPackage;
5246}
5247
Ruben Brunkcc776712015-02-17 20:18:47 -08005248// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005249// ClientEventListener
5250// ----------------------------------------------------------------------------
5251
5252void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005253 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005254 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005255 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005256 if (basicClient.get() != nullptr) {
5257 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005258 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005259 static_cast<int>(basicClient->getClientUid()));
5260 }
5261}
5262
5263void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005264 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005265 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005266 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005267 if (basicClient.get() != nullptr) {
5268 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005269 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005270 static_cast<int>(basicClient->getClientUid()));
5271 }
5272}
5273
Ruben Brunk99e69712015-05-26 17:25:07 -07005274// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005275// CameraClientManager
5276// ----------------------------------------------------------------------------
5277
Ruben Brunk99e69712015-05-26 17:25:07 -07005278CameraService::CameraClientManager::CameraClientManager() {
5279 setListener(std::make_shared<ClientEventListener>());
5280}
5281
Ruben Brunkcc776712015-02-17 20:18:47 -08005282CameraService::CameraClientManager::~CameraClientManager() {}
5283
5284sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005285 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005286 auto descriptor = get(id);
5287 if (descriptor == nullptr) {
5288 return sp<BasicClient>{nullptr};
5289 }
5290 return descriptor->getValue();
5291}
5292
Austin Borgered99f642023-06-01 16:51:35 -07005293std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005294 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005295 std::ostringstream ret;
5296 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005297 bool hasAny = false;
5298 for (auto& i : all) {
5299 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005300 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005301 int32_t cost = i->getCost();
5302 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005303 int32_t score = i->getPriority().getScore();
5304 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005305 auto conflicting = i->getConflicting();
5306 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005307 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005308 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005309 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005310 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005311 uid_t clientUid = clientSp->getClientUid();
5312 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005313 }
Austin Borgered99f642023-06-01 16:51:35 -07005314 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5315 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005316
Ruben Brunk6267b532015-04-30 17:44:07 -07005317 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005318 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005319 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005320 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005321 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005322 }
5323
Austin Borgered99f642023-06-01 16:51:35 -07005324 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005325 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005326 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005327 }
Austin Borgered99f642023-06-01 16:51:35 -07005328 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005329 }
Austin Borgered99f642023-06-01 16:51:35 -07005330 if (hasAny) ret << "\n";
5331 ret << "]\n";
5332 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005333}
5334
5335CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005336 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5337 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005338 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005339
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005340 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005341 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005342
Austin Borgered99f642023-06-01 16:51:35 -07005343 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005344 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5345 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005346}
5347
5348CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005349 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005350 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005351 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005352 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005353 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5354 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005355}
5356
5357// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005358// InjectionStatusListener
5359// ----------------------------------------------------------------------------
5360
5361void CameraService::InjectionStatusListener::addListener(
5362 const sp<ICameraInjectionCallback>& callback) {
5363 Mutex::Autolock lock(mListenerLock);
5364 if (mCameraInjectionCallback) return;
5365 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5366 if (res == OK) {
5367 mCameraInjectionCallback = callback;
5368 }
5369}
5370
5371void CameraService::InjectionStatusListener::removeListener() {
5372 Mutex::Autolock lock(mListenerLock);
5373 if (mCameraInjectionCallback == nullptr) {
5374 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5375 return;
5376 }
5377 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5378 mCameraInjectionCallback = nullptr;
5379}
5380
5381void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005382 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005383 if (mCameraInjectionCallback == nullptr) {
5384 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5385 return;
5386 }
Cliff Wud3a05312021-04-26 23:07:31 +08005387
5388 switch (err) {
5389 case -ENODEV:
5390 mCameraInjectionCallback->onInjectionError(
5391 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5392 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005393 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005394 break;
5395 case -EBUSY:
5396 mCameraInjectionCallback->onInjectionError(
5397 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5398 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005399 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005400 break;
5401 case DEAD_OBJECT:
5402 mCameraInjectionCallback->onInjectionError(
5403 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5404 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005405 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005406 break;
5407 case INVALID_OPERATION:
5408 mCameraInjectionCallback->onInjectionError(
5409 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5410 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005411 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005412 break;
5413 case UNKNOWN_TRANSACTION:
5414 mCameraInjectionCallback->onInjectionError(
5415 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5416 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005417 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005418 break;
5419 default:
5420 mCameraInjectionCallback->onInjectionError(
5421 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5422 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005423 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005424 }
Cliff Wud8cae102021-03-11 01:37:42 +08005425}
5426
5427void CameraService::InjectionStatusListener::binderDied(
5428 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005429 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5430 auto parent = mParent.promote();
5431 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005432 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5433 if (clientDescriptor != nullptr) {
5434 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5435 baseClientPtr->stopInjection();
5436 }
Cliff Wu3b268182021-07-06 15:44:43 +08005437 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005438 }
5439}
5440
5441// ----------------------------------------------------------------------------
5442// CameraInjectionSession
5443// ----------------------------------------------------------------------------
5444
5445binder::Status CameraService::CameraInjectionSession::stopInjection() {
5446 Mutex::Autolock lock(mInjectionSessionLock);
5447 auto parent = mParent.promote();
5448 if (parent == nullptr) {
5449 ALOGE("CameraInjectionSession: Parent is gone");
5450 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5451 "Camera service encountered error");
5452 }
Cliff Wud3a05312021-04-26 23:07:31 +08005453
5454 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005455 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5456 if (clientDescriptor != nullptr) {
5457 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5458 res = baseClientPtr->stopInjection();
5459 if (res != OK) {
5460 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5461 " ret != NO_ERROR: %d", res);
5462 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5463 "Camera session encountered error");
5464 }
5465 }
Cliff Wu3b268182021-07-06 15:44:43 +08005466 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005467 return binder::Status::ok();
5468}
5469
5470// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005471
5472static const int kDumpLockRetries = 50;
5473static const int kDumpLockSleep = 60000;
5474
5475static bool tryLock(Mutex& mutex)
5476{
5477 bool locked = false;
5478 for (int i = 0; i < kDumpLockRetries; ++i) {
5479 if (mutex.tryLock() == NO_ERROR) {
5480 locked = true;
5481 break;
5482 }
5483 usleep(kDumpLockSleep);
5484 }
5485 return locked;
5486}
5487
Rucha Katakwardf223072021-06-15 10:21:00 -07005488void CameraService::cacheDump() {
5489 if (mMemFd != -1) {
5490 const Vector<String16> args;
5491 ATRACE_CALL();
5492 // Acquiring service lock here will avoid the deadlock since
5493 // cacheDump will not be called during the second disconnect.
5494 Mutex::Autolock lock(mServiceLock);
5495
5496 Mutex::Autolock l(mCameraStatesLock);
5497 // Start collecting the info for open sessions and store it in temp file.
5498 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005499 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005500 auto clientDescriptor = mActiveClientManager.get(cameraId);
5501 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005502 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005503 // Log the current open session info before device is disconnected.
5504 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5505 }
5506 }
5507 }
5508}
5509
Mathias Agopian65ab4712010-07-14 17:59:35 -07005510status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005511 ATRACE_CALL();
5512
Austin Borgered99f642023-06-01 16:51:35 -07005513 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005514 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005515 getCallingPid(),
5516 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005517 return NO_ERROR;
5518 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005519 bool locked = tryLock(mServiceLock);
5520 // failed to lock - CameraService is probably deadlocked
5521 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005522 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005523 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005524
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005525 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005526 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005527
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005528 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005529 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005530
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005531 if (locked) mServiceLock.unlock();
5532 return NO_ERROR;
5533 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005534 dprintf(fd, "\n== Service global info: ==\n\n");
5535 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005536 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005537 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5538 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005539 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5540 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5541 }
Austin Borgered99f642023-06-01 16:51:35 -07005542 std::string activeClientString = mActiveClientManager.toString();
5543 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5544 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005545 if (mStreamUseCaseOverrides.size() > 0) {
5546 dprintf(fd, "Active stream use case overrides:");
5547 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5548 dprintf(fd, " %" PRId64, useCaseOverride);
5549 }
5550 dprintf(fd, "\n");
5551 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005552
5553 dumpEventLog(fd);
5554
5555 bool stateLocked = tryLock(mCameraStatesLock);
5556 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005557 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005558 }
5559
Emilian Peevbd8c5032018-02-14 23:05:40 +00005560 int argSize = args.size();
5561 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005562 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005563 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005564 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005565 }
5566 break;
5567 }
5568 }
5569
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005570 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005571 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005572
Austin Borgered99f642023-06-01 16:51:35 -07005573 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005574
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005575 CameraParameters p = state.second->getShimParams();
5576 if (!p.isEmpty()) {
5577 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5578 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005579 }
5580
5581 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005582 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005583 // log the current open session info
5584 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005585 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005586 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005587 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005588
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005589 }
5590
5591 if (stateLocked) mCameraStatesLock.unlock();
5592
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005593 if (locked) mServiceLock.unlock();
5594
Emilian Peevf53f66e2017-04-11 14:29:43 +01005595 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005596
5597 dprintf(fd, "\n== Vendor tags: ==\n\n");
5598
5599 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5600 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005601 sp<VendorTagDescriptorCache> cache =
5602 VendorTagDescriptorCache::getGlobalVendorTagCache();
5603 if (cache == NULL) {
5604 dprintf(fd, "No vendor tags.\n");
5605 } else {
5606 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5607 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005608 } else {
5609 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5610 }
5611
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005612 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005613 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005614 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005615
5616 // Process dump arguments, if any
5617 int n = args.size();
5618 String16 verboseOption("-v");
5619 String16 unreachableOption("--unreachable");
5620 for (int i = 0; i < n; i++) {
5621 if (args[i] == verboseOption) {
5622 // change logging level
5623 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005624 std::string levelStr = toStdString(args[i+1]);
5625 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005626 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005627 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005628 } else if (args[i] == unreachableOption) {
5629 // Dump memory analysis
5630 // TODO - should limit be an argument parameter?
5631 UnreachableMemoryInfo info;
5632 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5633 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005634 dprintf(fd, "\n== Unable to dump unreachable memory. "
5635 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005636 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005637 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005638 std::string s = info.ToString(/*log_contents*/ true);
5639 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005640 }
5641 }
5642 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005643
5644 bool serviceLocked = tryLock(mServiceLock);
5645
5646 // Dump info from previous open sessions.
5647 // Reposition the offset to beginning of the file before reading
5648
5649 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5650 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5651 ssize_t size_read;
5652 char buf[4096];
5653 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5654 // Read data from file to a small buffer and write it to fd.
5655 write(fd, buf, size_read);
5656 if (size_read == -1) {
5657 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5658 break;
5659 }
5660 }
5661 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5662 } else {
5663 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5664 }
5665
5666 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005667 return NO_ERROR;
5668}
5669
Rucha Katakwardf223072021-06-15 10:21:00 -07005670void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005671 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005672 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005673 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005674 getFormattedCurrentTime().c_str(),
5675 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005676 dprintf(fd, " Client priority score: %d state: %d\n",
5677 clientDescriptor->getPriority().getScore(),
5678 clientDescriptor->getPriority().getState());
5679 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5680
5681 auto client = clientDescriptor->getValue();
5682 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005683 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005684
5685 client->dumpClient(fd, args);
5686}
5687
Austin Borgered99f642023-06-01 16:51:35 -07005688void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005689 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005690 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005691}
5692
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005693void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005694 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005695
5696 Mutex::Autolock l(mLogLock);
5697 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005698 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005699 }
5700
5701 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005702 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005703 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005704 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005705 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005706 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005707}
5708
Austin Borgered99f642023-06-01 16:51:35 -07005709void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005710 Mutex::Autolock lock(mLogLock);
5711 if (!isClientWatchedLocked(client)) { return; }
5712
5713 std::vector<std::string> dumpVector;
5714 client->dumpWatchedEventsToVector(dumpVector);
5715
5716 if (dumpVector.empty()) { return; }
5717
Austin Borgered99f642023-06-01 16:51:35 -07005718 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005719
Austin Borgered99f642023-06-01 16:51:35 -07005720 std::string currentTime = getFormattedCurrentTime();
5721 dumpString << "Cached @ ";
5722 dumpString << currentTime;
5723 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005724
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005725 size_t i = dumpVector.size();
5726
5727 // Store the string in reverse order (latest last)
5728 while (i > 0) {
5729 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005730 dumpString << cameraId;
5731 dumpString << ":";
5732 dumpString << client->getPackageName();
5733 dumpString << " ";
5734 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005735 }
5736
Austin Borgered99f642023-06-01 16:51:35 -07005737 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005738}
5739
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005740void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005741 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005742 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5743 if (mTorchClientMap[i] == who) {
5744 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005745 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005746 status_t res = mFlashlight->setTorchMode(cameraId, false);
5747 if (res) {
5748 ALOGE("%s: torch client died but couldn't turn off torch: "
5749 "%s (%d)", __FUNCTION__, strerror(-res), res);
5750 return;
5751 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005752 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005753 break;
5754 }
5755 }
5756}
5757
Ruben Brunkcc776712015-02-17 20:18:47 -08005758/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005759
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005760 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005761 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5762 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005763 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005764 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005765 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005766
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005767 // check torch client
5768 handleTorchClientBinderDied(who);
5769
5770 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005771 if(!evictClientIdByRemote(who)) {
5772 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005773 return;
5774 }
5775
Ruben Brunkcc776712015-02-17 20:18:47 -08005776 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5777 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005778}
5779
Austin Borgered99f642023-06-01 16:51:35 -07005780void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005781 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005782}
5783
Austin Borgered99f642023-06-01 16:51:35 -07005784void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005785 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005786 // Do not lock mServiceLock here or can get into a deadlock from
5787 // connect() -> disconnect -> updateStatus
5788
5789 auto state = getCameraState(cameraId);
5790
5791 if (state == nullptr) {
5792 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005793 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005794 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005795 }
5796
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005797 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5798 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5799 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005800 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005801 return;
5802 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005803
Biswarup Pal37a75182024-01-16 15:53:35 +00005804 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5805 CameraMetadata cameraInfo;
5806 status_t res = mCameraProviderManager->getCameraCharacteristics(
5807 cameraId, false, &cameraInfo, false);
5808 if (res != OK) {
5809 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5810 __FUNCTION__, cameraId.c_str());
5811 } else {
5812 int32_t deviceId = getDeviceId(cameraInfo);
5813 if (deviceId != kDefaultDeviceId) {
5814 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5815 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5816 static_cast<camera_metadata_enum_android_lens_facing_t>(
5817 lensFacingEntry.data.u8[0]);
5818 std::string mappedCameraId;
5819 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5820 mappedCameraId = kVirtualDeviceBackCameraId;
5821 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5822 mappedCameraId = kVirtualDeviceFrontCameraId;
5823 } else {
5824 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5825 __func__);
5826 }
5827 if (!mappedCameraId.empty()) {
5828 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5829 }
5830 }
5831 }
5832 }
5833
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005834 // Collect the logical cameras without holding mStatusLock in updateStatus
5835 // as that can lead to a deadlock(b/162192331).
5836 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005837 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005838 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005839 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005840 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005841 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005842 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5843 auto [deviceId, mappedCameraId] =
5844 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005845
Biswarup Pal37a75182024-01-16 15:53:35 +00005846 if (status != StatusInternal::ENUMERATING) {
5847 // Update torch status if it has a flash unit.
5848 Mutex::Autolock al(mTorchStatusMutex);
5849 TorchModeStatus torchStatus;
5850 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5851 NAME_NOT_FOUND) {
5852 TorchModeStatus newTorchStatus =
5853 status == StatusInternal::PRESENT ?
5854 TorchModeStatus::AVAILABLE_OFF :
5855 TorchModeStatus::NOT_AVAILABLE;
5856 if (torchStatus != newTorchStatus) {
5857 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5858 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005859 }
5860 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005861
Biswarup Pal37a75182024-01-16 15:53:35 +00005862 Mutex::Autolock lock(mStatusListenerLock);
5863 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5864 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005865
Biswarup Pal37a75182024-01-16 15:53:35 +00005866 for (auto& listener : mListenerList) {
5867 bool isVendorListener = listener->isVendorListener();
5868 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5869 listener->getListenerPid(), listener->getListenerUid())) {
5870 ALOGV("Skipping discovery callback for system-only camera device %s",
5871 cameraId.c_str());
5872 continue;
5873 }
5874
5875 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5876 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005877 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005878 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005879 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5880 ret.exceptionCode());
Biswarup Pal37a75182024-01-16 15:53:35 +00005881
5882 // Only cameras of the default device can be remapped to a different camera
5883 // (using remapCameraIds method), so do the following only if the camera is
5884 // associated with the default device.
5885 if (deviceId == kDefaultDeviceId) {
5886 // For the default device, also trigger the callbacks for cameras that were
5887 // remapped to the current cameraId for the specific package that this
5888 // listener belongs to.
5889 std::vector<std::string> remappedCameraIds =
5890 findOriginalIdsForRemappedCameraId(cameraId,
5891 listener->getListenerUid());
5892 for (auto &remappedCameraId: remappedCameraIds) {
5893 ret = listener->getListener()->onStatusChanged(
5894 mapToInterface(status), remappedCameraId, kDefaultDeviceId);
5895 listener->handleBinderStatus(ret,
5896 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
5897 __FUNCTION__, listener->getListenerUid(),
5898 listener->getListenerPid(), ret.exceptionCode());
5899 }
5900 }
malikakash82ed4352023-07-21 22:44:34 +00005901 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005902 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005903}
5904
Austin Borgered99f642023-06-01 16:51:35 -07005905void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5906 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005907 auto state = getCameraState(cameraId);
5908 if (state == nullptr) {
5909 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005910 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005911 return;
5912 }
5913 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005914 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005915 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005916 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005917 }
5918
Biswarup Pal37a75182024-01-16 15:53:35 +00005919 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5920 auto [deviceId, mappedCameraId] =
5921 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5922
Shuzhen Wang695044d2020-03-06 09:02:23 -08005923 Mutex::Autolock lock(mStatusListenerLock);
5924
5925 for (const auto& it : mListenerList) {
5926 if (!it->isOpenCloseCallbackAllowed()) {
5927 continue;
5928 }
5929
5930 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005931 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005932 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5933 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005934 } else {
Biswarup Pal37a75182024-01-16 15:53:35 +00005935 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005936 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005937
5938 it->handleBinderStatus(ret,
5939 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5940 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005941 }
5942}
5943
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005944template<class Func>
5945void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005946 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005947 std::initializer_list<StatusInternal> rejectSourceStates,
5948 Func onStatusUpdatedLocked) {
5949 Mutex::Autolock lock(mStatusLock);
5950 StatusInternal oldStatus = mStatus;
5951 mStatus = status;
5952
5953 if (oldStatus == status) {
5954 return;
5955 }
5956
5957 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005958 cameraId.c_str(), oldStatus, status);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005959
5960 if (oldStatus == StatusInternal::NOT_PRESENT &&
5961 (status != StatusInternal::PRESENT &&
5962 status != StatusInternal::ENUMERATING)) {
5963
5964 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5965 __FUNCTION__);
5966 mStatus = oldStatus;
5967 return;
5968 }
5969
5970 /**
5971 * Sometimes we want to conditionally do a transition.
5972 * For example if a client disconnects, we want to go to PRESENT
5973 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5974 */
5975 for (auto& rejectStatus : rejectSourceStates) {
5976 if (oldStatus == rejectStatus) {
5977 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005978 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005979 mStatus = oldStatus;
5980 return;
5981 }
5982 }
5983
5984 onStatusUpdatedLocked(cameraId, status);
5985}
5986
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005987status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005988 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005989 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005990 if (!status) {
5991 return BAD_VALUE;
5992 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005993 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5994 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005995 // invalid camera ID or the camera doesn't have a flash unit
5996 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005997 }
5998
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005999 *status = mTorchStatusMap.valueAt(index);
6000 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006001}
6002
Austin Borgered99f642023-06-01 16:51:35 -07006003status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006004 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006005 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
6006 if (index == NAME_NOT_FOUND) {
6007 return BAD_VALUE;
6008 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006009 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006010
6011 return OK;
6012}
6013
Austin Borgered99f642023-06-01 16:51:35 -07006014std::list<std::string> CameraService::getLogicalCameras(
6015 const std::string& physicalCameraId) {
6016 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08006017 Mutex::Autolock lock(mCameraStatesLock);
6018 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07006019 if (state.second->containsPhysicalCamera(physicalCameraId)) {
6020 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08006021 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006022 }
6023 return retList;
6024}
6025
6026void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07006027 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00006028 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006029 // mStatusListenerLock is expected to be locked
6030 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08006031 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006032 // Note: we check only the deviceKind of the physical camera id
6033 // since, logical camera ids and their physical camera ids are
6034 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07006035 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
6036 listener->getListenerPid(), listener->getListenerUid())) {
6037 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07006038 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07006039 continue;
6040 }
Austin Borgere8e2c422022-05-12 13:45:24 -07006041 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00006042 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07006043 listener->handleBinderStatus(ret,
6044 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
6045 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
6046 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08006047 }
6048 }
6049}
6050
Svet Ganova453d0d2018-01-11 15:37:58 -08006051void CameraService::blockClientsForUid(uid_t uid) {
6052 const auto clients = mActiveClientManager.getAll();
6053 for (auto& current : clients) {
6054 if (current != nullptr) {
6055 const auto basicClient = current->getValue();
6056 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
6057 basicClient->block();
6058 }
6059 }
6060 }
6061}
6062
Michael Grooverd1d435a2018-12-18 17:39:42 -08006063void CameraService::blockAllClients() {
6064 const auto clients = mActiveClientManager.getAll();
6065 for (auto& current : clients) {
6066 if (current != nullptr) {
6067 const auto basicClient = current->getValue();
6068 if (basicClient.get() != nullptr) {
6069 basicClient->block();
6070 }
6071 }
6072 }
6073}
6074
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00006075void CameraService::blockPrivacyEnabledClients() {
6076 const auto clients = mActiveClientManager.getAll();
6077 for (auto& current : clients) {
6078 if (current != nullptr) {
6079 const auto basicClient = current->getValue();
6080 if (basicClient.get() != nullptr) {
6081 std::string pkgName = basicClient->getPackageName();
6082 bool cameraPrivacyEnabled =
6083 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
6084 if (cameraPrivacyEnabled) {
6085 basicClient->block();
6086 }
6087 }
6088 }
6089 }
6090}
6091
Svet Ganova453d0d2018-01-11 15:37:58 -08006092// NOTE: This is a remote API - make sure all args are validated
6093status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006094 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006095 return PERMISSION_DENIED;
6096 }
6097 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
6098 return BAD_VALUE;
6099 }
Austin Borgered99f642023-06-01 16:51:35 -07006100 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006101 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006102 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006103 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006104 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006105 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07006106 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006107 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07006108 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006109 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07006110 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006111 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07006112 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006113 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07006114 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006115 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07006116 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006117 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07006118 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006119 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07006120 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006121 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07006122 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006123 handleClearStreamUseCaseOverrides();
6124 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07006125 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006126 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07006127 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006128 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07006129 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00006130 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07006131 } else if (args.size() >= 4 && args[0] == toString16("remap-camera-id")) {
malikakash82ed4352023-07-21 22:44:34 +00006132 return handleCameraIdRemapping(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006133 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006134 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006135 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08006136 }
6137 printHelp(err);
6138 return BAD_VALUE;
6139}
6140
malikakash82ed4352023-07-21 22:44:34 +00006141status_t CameraService::handleCameraIdRemapping(const Vector<String16>& args, int err) {
6142 uid_t uid = IPCThreadState::self()->getCallingUid();
6143 if (uid != AID_ROOT) {
6144 dprintf(err, "Must be adb root\n");
6145 return PERMISSION_DENIED;
6146 }
6147 if (args.size() != 4) {
6148 dprintf(err, "Expected format: remap-camera-id <PACKAGE> <Id0> <Id1>\n");
6149 return BAD_VALUE;
6150 }
Austin Borgered99f642023-06-01 16:51:35 -07006151 std::string packageName = toStdString(args[1]);
6152 std::string cameraIdToReplace = toStdString(args[2]);
6153 std::string cameraIdNew = toStdString(args[3]);
malikakash82ed4352023-07-21 22:44:34 +00006154 remapCameraIds({{packageName, {{cameraIdToReplace, cameraIdNew}}}});
6155 return OK;
6156}
6157
Svet Ganova453d0d2018-01-11 15:37:58 -08006158status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006159 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006160
Svet Ganova453d0d2018-01-11 15:37:58 -08006161 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07006162 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006163 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07006164 } else if ((args[2] != toString16("idle"))) {
6165 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08006166 return BAD_VALUE;
6167 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006168
6169 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006170 if (args.size() >= 5 && args[3] == toString16("--user")) {
6171 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006172 }
6173
6174 uid_t uid;
6175 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
6176 return BAD_VALUE;
6177 }
6178
6179 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08006180 return NO_ERROR;
6181}
6182
6183status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006184 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006185
6186 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006187 if (args.size() >= 4 && args[2] == toString16("--user")) {
6188 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006189 }
6190
6191 uid_t uid;
6192 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006193 return BAD_VALUE;
6194 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006195
6196 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08006197 return NO_ERROR;
6198}
6199
6200status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006201 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006202
6203 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006204 if (args.size() >= 4 && args[2] == toString16("--user")) {
6205 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006206 }
6207
6208 uid_t uid;
6209 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006210 return BAD_VALUE;
6211 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006212
6213 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006214 return dprintf(out, "active\n");
6215 } else {
6216 return dprintf(out, "idle\n");
6217 }
6218}
6219
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006220status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006221 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006222 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
6223 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
6224 Mutex::Autolock lock(mServiceLock);
6225
6226 mOverrideRotateAndCropMode = rotateValue;
6227
6228 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6229
6230 const auto clients = mActiveClientManager.getAll();
6231 for (auto& current : clients) {
6232 if (current != nullptr) {
6233 const auto basicClient = current->getValue();
6234 if (basicClient.get() != nullptr) {
6235 basicClient->setRotateAndCropOverride(rotateValue);
6236 }
6237 }
6238 }
6239
6240 return OK;
6241}
6242
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006243status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6244 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006245 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006246 if ((*end != '\0') ||
6247 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6248 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6249 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6250 return BAD_VALUE;
6251 }
6252
6253 Mutex::Autolock lock(mServiceLock);
6254 mOverrideAutoframingMode = autoframingValue;
6255
6256 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6257
6258 const auto clients = mActiveClientManager.getAll();
6259 for (auto& current : clients) {
6260 if (current != nullptr) {
6261 const auto basicClient = current->getValue();
6262 if (basicClient.get() != nullptr) {
6263 basicClient->setAutoframingOverride(autoframingValue);
6264 }
6265 }
6266 }
6267
6268 return OK;
6269}
6270
Ravneetaeb20dc2022-03-30 05:33:03 +00006271status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006272 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006273
6274 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6275
6276 Mutex::Autolock lock(mServiceLock);
6277
6278 mCameraServiceWatchdogEnabled = enableWatchdog;
6279
6280 const auto clients = mActiveClientManager.getAll();
6281 for (auto& current : clients) {
6282 if (current != nullptr) {
6283 const auto basicClient = current->getValue();
6284 if (basicClient.get() != nullptr) {
6285 basicClient->setCameraServiceWatchdog(enableWatchdog);
6286 }
6287 }
6288 }
6289
6290 return OK;
6291}
6292
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006293status_t CameraService::handleGetRotateAndCrop(int out) {
6294 Mutex::Autolock lock(mServiceLock);
6295
6296 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6297}
6298
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006299status_t CameraService::handleGetAutoframing(int out) {
6300 Mutex::Autolock lock(mServiceLock);
6301
6302 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6303}
6304
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006305status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6306 char *endPtr;
6307 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006308 std::string maskString = toStdString(args[1]);
6309 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006310
6311 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006312 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006313 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6314
6315 Mutex::Autolock lock(mServiceLock);
6316
6317 mImageDumpMask = maskValue;
6318
6319 return OK;
6320}
6321
6322status_t CameraService::handleGetImageDumpMask(int out) {
6323 Mutex::Autolock lock(mServiceLock);
6324
6325 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6326}
6327
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006328status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006329 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006330 if (errno != 0) return BAD_VALUE;
6331
6332 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6333 Mutex::Autolock lock(mServiceLock);
6334
6335 mOverrideCameraMuteMode = (muteValue == 1);
6336
6337 const auto clients = mActiveClientManager.getAll();
6338 for (auto& current : clients) {
6339 if (current != nullptr) {
6340 const auto basicClient = current->getValue();
6341 if (basicClient.get() != nullptr) {
6342 if (basicClient->supportsCameraMute()) {
6343 basicClient->setCameraMute(mOverrideCameraMuteMode);
6344 }
6345 }
6346 }
6347 }
6348
6349 return OK;
6350}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006351
Shuzhen Wang16610a62022-12-15 22:38:07 -08006352status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6353 std::vector<int64_t> useCasesOverride;
6354 for (size_t i = 1; i < args.size(); i++) {
6355 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006356 std::string arg = toStdString(args[i]);
6357 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006358 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006359 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006360 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006361 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006362 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006363 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006364 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006365 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006366 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006367 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006368 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006369 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006370 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6371 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006372 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006373 return BAD_VALUE;
6374 }
6375 useCasesOverride.push_back(useCase);
6376 }
6377
6378 Mutex::Autolock lock(mServiceLock);
6379 mStreamUseCaseOverrides = std::move(useCasesOverride);
6380
6381 return OK;
6382}
6383
6384void CameraService::handleClearStreamUseCaseOverrides() {
6385 Mutex::Autolock lock(mServiceLock);
6386 mStreamUseCaseOverrides.clear();
6387}
6388
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006389status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6390 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006391 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006392 if ((*end != '\0') ||
6393 (zoomOverrideValue != -1 &&
6394 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6395 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6396 return BAD_VALUE;
6397 }
6398
6399 Mutex::Autolock lock(mServiceLock);
6400 mZoomOverrideValue = zoomOverrideValue;
6401
6402 const auto clients = mActiveClientManager.getAll();
6403 for (auto& current : clients) {
6404 if (current != nullptr) {
6405 const auto basicClient = current->getValue();
6406 if (basicClient.get() != nullptr) {
6407 if (basicClient->supportsZoomOverride()) {
6408 basicClient->setZoomOverride(mZoomOverrideValue);
6409 }
6410 }
6411 }
6412 }
6413
6414 return OK;
6415}
6416
Avichal Rakesh84147132021-11-11 17:47:11 -08006417status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006418 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006419 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006420 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006421 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006422 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006423 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006424 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006425 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006426 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006427 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006428 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006429 dprintf(outFd, "Camera service watch commands:\n"
6430 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6431 " starts watching the provided tags for clients with provided package\n"
6432 " recognizes tag shorthands like '3a'\n"
6433 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006434 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006435 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006436 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006437 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006438 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006439 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006440 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006441}
6442
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006443status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6444 Mutex::Autolock lock(mLogLock);
6445 size_t tagsIdx; // index of '-m'
6446 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006447 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006448 if (tagsIdx < args.size() - 1) {
6449 tags = args[tagsIdx + 1];
6450 } else {
6451 dprintf(outFd, "No tags provided.\n");
6452 return BAD_VALUE;
6453 }
6454
6455 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006456 // watch all clients if no clients are provided
6457 String16 clients = toString16(kWatchAllClientsFlag);
6458 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006459 clientsIdx++);
6460 if (clientsIdx < args.size() - 1) {
6461 clients = args[clientsIdx + 1];
6462 }
Austin Borgered99f642023-06-01 16:51:35 -07006463 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006464
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006465 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006466 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006467
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006468 bool serviceLock = tryLock(mServiceLock);
6469 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006470 auto cameraClients = mActiveClientManager.getAll();
6471 for (const auto &clientDescriptor: cameraClients) {
6472 if (clientDescriptor == nullptr) { continue; }
6473 sp<BasicClient> client = clientDescriptor->getValue();
6474 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006475
6476 if (isClientWatchedLocked(client.get())) {
6477 client->startWatchingTags(mMonitorTags, outFd);
6478 numWatchedClients++;
6479 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006480 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006481 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6482
6483 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006484 return OK;
6485}
6486
6487status_t CameraService::stopWatchingTags(int outFd) {
6488 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006489 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006490 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006491
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006492 mWatchedClientPackages.clear();
6493 mWatchedClientsDumpCache.clear();
6494
6495 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006496 auto cameraClients = mActiveClientManager.getAll();
6497 for (const auto &clientDescriptor : cameraClients) {
6498 if (clientDescriptor == nullptr) { continue; }
6499 sp<BasicClient> client = clientDescriptor->getValue();
6500 if (client.get() == nullptr) { continue; }
6501 client->stopWatchingTags(outFd);
6502 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006503 dprintf(outFd, "Stopped watching all clients.\n");
6504 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006505 return OK;
6506}
6507
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006508status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6509 Mutex::Autolock lock(mLogLock);
6510 size_t clearedSize = mWatchedClientsDumpCache.size();
6511 mWatchedClientsDumpCache.clear();
6512 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6513 return OK;
6514}
6515
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006516status_t CameraService::printWatchedTags(int outFd) {
6517 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006518 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006519
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006520 bool printedSomething = false; // tracks if any monitoring information was printed
6521 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006522
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006523 bool serviceLock = tryLock(mServiceLock);
6524 // get all watched clients that are currently connected
6525 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6526 if (clientDescriptor == nullptr) { continue; }
6527
6528 sp<BasicClient> client = clientDescriptor->getValue();
6529 if (client.get() == nullptr) { continue; }
6530 if (!isClientWatchedLocked(client.get())) { continue; }
6531
6532 std::vector<std::string> dumpVector;
6533 client->dumpWatchedEventsToVector(dumpVector);
6534
6535 size_t printIdx = dumpVector.size();
6536 if (printIdx == 0) {
6537 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006538 }
6539
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006540 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006541 const std::string &cameraId = clientDescriptor->getKey();
6542 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006543 while(printIdx > 0) {
6544 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006545 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006546 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006547 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006548 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006549 printedSomething = true;
6550
6551 connectedMonitoredClients.emplace(client->getPackageName());
6552 }
6553 if (serviceLock) { mServiceLock.unlock(); }
6554
6555 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6556 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006557 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006558 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6559 continue;
6560 }
6561
Austin Borgered99f642023-06-01 16:51:35 -07006562 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006563 dprintf(outFd, "%s\n", kv.second.c_str());
6564 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006565 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006566
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006567 if (!printedSomething) {
6568 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006569 }
6570
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006571 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006572}
6573
Avichal Rakesh84147132021-11-11 17:47:11 -08006574// Print all events in vector `events' that came after lastPrintedEvent
6575void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006576 const std::string &cameraId,
6577 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006578 const std::vector<std::string> &events,
6579 const std::string &lastPrintedEvent) {
6580 if (events.empty()) { return; }
6581
6582 // index of lastPrintedEvent in events.
6583 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6584 size_t lastPrintedIdx;
6585 for (lastPrintedIdx = 0;
6586 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6587 lastPrintedIdx++);
6588
6589 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6590
Avichal Rakesh84147132021-11-11 17:47:11 -08006591 // print events in chronological order (latest event last)
6592 size_t idxToPrint = lastPrintedIdx;
6593 do {
6594 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006595 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6596 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006597 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006598}
6599
6600// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6601// command should be interrupted if the user presses the return key, or if user loses any way to
6602// signal interrupt.
6603// If timeoutMs == 0, this function will always return false
6604bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6605 struct timeval startTime;
6606 int startTimeError = gettimeofday(&startTime, nullptr);
6607 if (startTimeError) {
6608 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6609 return true;
6610 }
6611
6612 const nfds_t numFds = 1;
6613 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6614
6615 struct timeval currTime;
6616 char buffer[2];
6617 while(true) {
6618 int currTimeError = gettimeofday(&currTime, nullptr);
6619 if (currTimeError) {
6620 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6621 return true;
6622 }
6623
6624 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6625 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6626 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6627
6628 if (remainingTimeMs <= 0) {
6629 // No user interrupt within timeoutMs, don't interrupt watch command
6630 return false;
6631 }
6632
6633 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6634 if (numFdsUpdated < 0) {
6635 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6636 return true;
6637 }
6638
6639 if (numFdsUpdated == 0) {
6640 // No user input within timeoutMs, don't interrupt watch command
6641 return false;
6642 }
6643
6644 if (!(pollFd.revents & POLLIN)) {
6645 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6646 return true;
6647 }
6648
6649 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6650 if (sizeRead < 0) {
6651 dprintf(outFd, "Error reading user input. Exiting.\n");
6652 return true;
6653 }
6654
6655 if (sizeRead == 0) {
6656 // Reached end of input fd (can happen if input is piped)
6657 // User has no way to signal an interrupt, so interrupt here
6658 return true;
6659 }
6660
6661 if (buffer[0] == '\n') {
6662 // User pressed return, interrupt watch command.
6663 return true;
6664 }
6665 }
6666}
6667
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006668status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6669 int inFd, int outFd) {
6670 // Figure out refresh interval, if present in args
6671 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006672 if (args.size() > 2) {
6673 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006674 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006675 intervalIdx++);
6676
6677 size_t intervalValIdx = intervalIdx + 1;
6678 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006679 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006680 if (errno) { return BAD_VALUE; }
6681 }
6682 }
6683
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006684 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6685 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006686
Avichal Rakesh84147132021-11-11 17:47:11 -08006687 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006688 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006689
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006690 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006691 bool serviceLock = tryLock(mServiceLock);
6692 auto cameraClients = mActiveClientManager.getAll();
6693 if (serviceLock) { mServiceLock.unlock(); }
6694
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006695 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006696 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006697 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006698
6699 sp<BasicClient> client = clientDescriptor->getValue();
6700 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006701 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006702
Austin Borgered99f642023-06-01 16:51:35 -07006703 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006704 // This also initializes the map entries with an empty string
6705 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6706
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006707 std::vector<std::string> latestEvents;
6708 client->dumpWatchedEventsToVector(latestEvents);
6709
6710 if (!latestEvents.empty()) {
6711 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006712 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006713 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006714 latestEvents,
6715 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006716 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006717 }
6718 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006719 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006720 break;
6721 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006722 }
6723 return OK;
6724}
6725
Austin Borgered99f642023-06-01 16:51:35 -07006726void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006727 mWatchedClientPackages.clear();
6728
Austin Borgered99f642023-06-01 16:51:35 -07006729 std::istringstream iss(clients);
6730 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006731
Austin Borgered99f642023-06-01 16:51:35 -07006732 while (std::getline(iss, nextClient, ',')) {
6733 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006734 // Don't need to track any other package if 'all' is present
6735 mWatchedClientPackages.clear();
6736 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6737 break;
6738 }
6739
6740 // track package names
6741 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006742 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006743}
6744
Svet Ganova453d0d2018-01-11 15:37:58 -08006745status_t CameraService::printHelp(int out) {
6746 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006747 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6748 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6749 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006750 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6751 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6752 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006753 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6754 " Valid values 0=false, 1=true, 2=auto\n"
6755 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006756 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6757 " Valid values 0=OFF, 1=ON for JPEG\n"
6758 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006759 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006760 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6761 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6762 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6763 " on. In case the number of usecases is smaller than the number of streams, the\n"
6764 " last use case is assigned to all the remaining streams. In case of multiple\n"
6765 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6766 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6767 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6768 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006769 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6770 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006771 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6772 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006773 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
malikakash73125c62023-07-21 22:44:34 +00006774 " remap-camera-id <PACKAGE> <Id0> <Id1> remaps camera ids. Must use adb root\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006775 " help print this message\n");
6776}
6777
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006778bool CameraService::isClientWatched(const BasicClient *client) {
6779 Mutex::Autolock lock(mLogLock);
6780 return isClientWatchedLocked(client);
6781}
6782
6783bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6784 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6785 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6786}
6787
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006788int32_t CameraService::updateAudioRestriction() {
6789 Mutex::Autolock lock(mServiceLock);
6790 return updateAudioRestrictionLocked();
6791}
6792
6793int32_t CameraService::updateAudioRestrictionLocked() {
6794 int32_t mode = 0;
6795 // iterate through all active client
6796 for (const auto& i : mActiveClientManager.getAll()) {
6797 const auto clientSp = i->getValue();
6798 mode |= clientSp->getAudioRestriction();
6799 }
6800
6801 bool modeChanged = (mAudioRestriction != mode);
6802 mAudioRestriction = mode;
6803 if (modeChanged) {
6804 mAppOps.setCameraAudioRestriction(mode);
6805 }
6806 return mode;
6807}
6808
Austin Borgered99f642023-06-01 16:51:35 -07006809status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006810 sp<BasicClient> clientSp) {
6811 std::unique_ptr<AutoConditionLock> lock =
6812 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6813 status_t res = NO_ERROR;
6814 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006815 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006816 mInjectionStatusListener->notifyInjectionError(
6817 externalCamId, UNKNOWN_TRANSACTION);
6818 clientSp->notifyError(
6819 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6820 CaptureResultExtras());
6821
6822 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6823 // other clients from connecting in mServiceLockWrapper if held
6824 mServiceLock.unlock();
6825
6826 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006827 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006828 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006829 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006830
6831 // Reacquire mServiceLock
6832 mServiceLock.lock();
6833 }
6834
6835 return res;
6836}
6837
Cliff Wud3a05312021-04-26 23:07:31 +08006838void CameraService::clearInjectionParameters() {
6839 {
6840 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006841 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006842 mInjectionInternalCamId = "";
6843 }
6844 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006845 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006846}
6847
Biswarup Pal37a75182024-01-16 15:53:35 +00006848} // namespace android