blob: 57d2b20669030623d6488d7d119b8cc2f0c9636b [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>
Joanne Chung02c13d02023-01-16 12:58:05 +000041#include <android/permission/PermissionChecker.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080042#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080043#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <binder/MemoryBase.h>
46#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080047#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080048#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080049#include <binderthreadstate/CallerUtils.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070050#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070051#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080052#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080053#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070054#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070055#include "hidl/HidlCameraService.h"
56#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080057#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070058#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070059#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080060#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070062#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000063#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070064#include <utils/Errors.h>
65#include <utils/Log.h>
66#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070067#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080068#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080069#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080070#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080071#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070072#include <system/camera_metadata.h>
Kunal Malhotrabfc96052023-02-28 23:25:34 +000073#include <binder/IServiceManager.h>
74#include <binder/IActivityManager.h>
Austin Borgered99f642023-06-01 16:51:35 -070075#include <camera/StringUtils.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080076
Ruben Brunkb2119af2014-05-09 19:57:56 -070077#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070078
79#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070080#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070081#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070082#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000083#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070084#include "utils/CameraThreadState.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070085#include "utils/CameraServiceProxyWrapper.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070086
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080087namespace {
88 const char* kPermissionServiceName = "permission";
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080089 const char* kActivityServiceName = "activity";
90 const char* kSensorPrivacyServiceName = "sensor_privacy";
91 const char* kAppopsServiceName = "appops";
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080092}; // namespace anonymous
93
Mathias Agopian65ab4712010-07-14 17:59:35 -070094namespace android {
95
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080096using binder::Status;
Austin Borgerea931242021-12-13 23:10:41 +000097using namespace camera3;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070098using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -070099using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800100using hardware::ICamera;
101using hardware::ICameraClient;
102using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800103using hardware::camera2::ICameraInjectionCallback;
104using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800105using hardware::camera2::utils::CameraIdAndSessionConfiguration;
106using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800107
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108// ----------------------------------------------------------------------------
109// Logging support -- this is for debugging only
110// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700111volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700112
Steve Blockb8a80522011-12-20 16:23:08 +0000113#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
114#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700115
116static void setLogLevel(int level) {
117 android_atomic_write(level, &gLogLevel);
118}
119
Henri Chataingbcb99452023-11-01 17:40:30 +0000120int32_t format_as(CameraService::StatusInternal s) {
121 return fmt::underlying(s);
122}
123
Mathias Agopian65ab4712010-07-14 17:59:35 -0700124// ----------------------------------------------------------------------------
125
Austin Borgered99f642023-06-01 16:51:35 -0700126static const std::string sDumpPermission("android.permission.DUMP");
127static const std::string sManageCameraPermission("android.permission.MANAGE_CAMERA");
128static const std::string sCameraPermission("android.permission.CAMERA");
129static const std::string sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
130static const std::string
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700131 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Austin Borgered99f642023-06-01 16:51:35 -0700132static const std::string sCameraOpenCloseListenerPermission(
Shuzhen Wang695044d2020-03-06 09:02:23 -0800133 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Austin Borgered99f642023-06-01 16:51:35 -0700134static const std::string
Cliff Wud8cae102021-03-11 01:37:42 +0800135 sCameraInjectExternalCameraPermission("android.permission.CAMERA_INJECT_EXTERNAL_CAMERA");
Kunal Malhotrabfc96052023-02-28 23:25:34 +0000136// Constant integer for FGS Logging, used to denote the API type for logger
137static const int LOG_FGS_CAMERA_API = 1;
Rucha Katakwardf223072021-06-15 10:21:00 -0700138const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800139static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
140static constexpr int32_t kSystemNativeClientState =
141 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Austin Borgered99f642023-06-01 16:51:35 -0700142static const std::string kServiceName("cameraserver");
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700143
Austin Borgered99f642023-06-01 16:51:35 -0700144const std::string CameraService::kOfflineDevice("offline-");
145const std::string CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700146
Rucha Katakward9ea6452021-05-06 11:57:16 -0700147// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700148static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700149
Austin Borger74fca042022-05-23 12:41:21 -0700150CameraService::CameraService(
151 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper) :
152 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
153 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800154 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800155 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700156 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700157 mSoundRef(0), mInitialized(false),
158 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000159 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800160 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700161 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
162 if (mMemFd == -1) {
163 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
164 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700165}
166
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800167// The word 'System' here does not refer to clients only on the system
168// partition. They just need to have a android system uid.
169static bool doesClientHaveSystemUid() {
170 return (CameraThreadState::getCallingUid() < AID_APP_START);
171}
172
Charles Chena7b613c2023-01-24 21:57:33 +0000173// Enable processes with isolated AID to request the binder
174void CameraService::instantiate() {
175 CameraService::publish(true);
176}
177
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800178void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700179 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800180 return;
181 }
182
183 ALOGV("appops service registered. setting camera audio restriction");
184 mAppOps.setCameraAudioRestriction(mAudioRestriction);
185}
186
Iliyan Malchev8951a972011-04-14 16:55:59 -0700187void CameraService::onFirstRef()
188{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700189
Ruben Brunkcc776712015-02-17 20:18:47 -0800190 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800191
Iliyan Malchev8951a972011-04-14 16:55:59 -0700192 BnCameraService::onFirstRef();
193
Ruben Brunk99e69712015-05-26 17:25:07 -0700194 // Update battery life tracking if service is restarting
195 BatteryNotifier& notifier(BatteryNotifier::getInstance());
196 notifier.noteResetCamera();
197 notifier.noteResetFlashlight();
198
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800199 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800200
Emilian Peevf53f66e2017-04-11 14:29:43 +0100201 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800202 if (res == OK) {
203 mInitialized = true;
204 }
205
Svet Ganova453d0d2018-01-11 15:37:58 -0800206 mUidPolicy = new UidPolicy(this);
207 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800208 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
209 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800210 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800211
212 // appops function setCamerAudioRestriction uses getService which
213 // is blocking till the appops service is ready. To enable early
214 // boot availability for cameraservice, use checkService which is
215 // non blocking and register for notifications
216 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700217 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800218 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700219 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800220 } else {
221 mAppOps.setCameraAudioRestriction(mAudioRestriction);
222 }
223
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700224 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
225 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000226 // Deprecated, so it will fail to register on newer devices
227 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700228 __FUNCTION__);
229 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700230
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700231 if (!AidlCameraService::registerService(this)) {
232 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
233 }
234
Shuzhen Wang24b44152019-09-20 10:38:11 -0700235 // This needs to be last call in this function, so that it's as close to
236 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700237 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700238 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800239}
240
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800241status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800242 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100243
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800244 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000245 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800246 {
247 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800248
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800249 if (nullptr == mCameraProviderManager.get()) {
250 mCameraProviderManager = new CameraProviderManager();
251 res = mCameraProviderManager->initialize(this);
252 if (res != OK) {
253 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
254 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700255 logServiceError("Unable to initialize camera provider manager",
256 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800257 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100258 }
259 }
260
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800261
262 // Setup vendor tags before we call get_camera_info the first time
263 // because HAL might need to setup static vendor keys in get_camera_info
264 // TODO: maybe put this into CameraProviderManager::initialize()?
265 mCameraProviderManager->setUpVendorTags();
266
267 if (nullptr == mFlashlight.get()) {
268 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700269 }
270
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800271 res = mFlashlight->findFlashUnits();
272 if (res != OK) {
273 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
274 }
275
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000276 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800277 }
278
279
280 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700281 if (getCameraState(cameraId) == nullptr) {
282 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800283 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000284 if (unavailPhysicalIds.count(cameraId) > 0) {
285 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700286 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000287 }
288 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800289 }
290
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700291 // Derive primary rear/front cameras, and filter their charactierstics.
292 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700293 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700294 // Assume internal cameras are advertised from the same
295 // provider. If multiple providers are registered at different time,
296 // and each provider contains multiple internal color cameras, the current
297 // logic may filter the characteristics of more than one front/rear color
298 // cameras.
299 Mutex::Autolock l(mServiceLock);
300 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700301 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700302
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800303 return OK;
304}
305
Austin Borgered99f642023-06-01 16:51:35 -0700306void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700307 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800308 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800309 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700310 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
311 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000312 ALOGV("%s: Skipping torch callback for system-only camera device %s",
313 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700314 continue;
315 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700316 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Austin Borgered99f642023-06-01 16:51:35 -0700317 cameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700318 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
319 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
malikakash82ed4352023-07-21 22:44:34 +0000320 // Also trigger the torch callbacks for cameras that were remapped to the current cameraId
321 // for the specific package that this listener belongs to.
Austin Borgered99f642023-06-01 16:51:35 -0700322 std::vector<std::string> remappedCameraIds =
malikakash82ed4352023-07-21 22:44:34 +0000323 findOriginalIdsForRemappedCameraId(cameraId, i->getListenerUid());
324 for (auto& remappedCameraId : remappedCameraIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700325 ret = i->getListener()->onTorchStatusChanged(mapToInterface(status), remappedCameraId);
malikakash82ed4352023-07-21 22:44:34 +0000326 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
327 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
328 }
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800329 }
330}
331
Mathias Agopian65ab4712010-07-14 17:59:35 -0700332CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800333 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800334 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800335 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800336 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700337}
338
Emilian Peevaee727d2017-05-04 16:35:48 +0100339void CameraService::onNewProviderRegistered() {
340 enumerateProviders();
341}
342
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700343void CameraService::filterAPI1SystemCameraLocked(
344 const std::vector<std::string> &normalDeviceIds) {
345 mNormalDeviceIdsWithoutSystemCamera.clear();
346 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700347 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Austin Borgered99f642023-06-01 16:51:35 -0700348 if (getSystemCameraKind(deviceId, &deviceKind) != OK) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700349 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
350 continue;
351 }
352 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700353 // All system camera ids will necessarily come after public camera
354 // device ids as per the HAL interface contract.
355 break;
356 }
357 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
358 }
359 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
360 mNormalDeviceIdsWithoutSystemCamera.size());
361}
362
Austin Borgered99f642023-06-01 16:51:35 -0700363status_t CameraService::getSystemCameraKind(const std::string& cameraId,
364 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700365 auto state = getCameraState(cameraId);
366 if (state != nullptr) {
367 *kind = state->getSystemCameraKind();
368 return OK;
369 }
370 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700371 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700372}
373
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800374void CameraService::updateCameraNumAndIds() {
375 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700376 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
377 // Excludes hidden secure cameras
378 mNumberOfCameras =
379 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
380 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800381 mNormalDeviceIds =
382 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700383 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800384}
385
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700386void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700387 // To claim to be S Performance primary cameras, the cameras must be
388 // backward compatible. So performance class primary camera Ids must be API1
389 // compatible.
390 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
391 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
392 int facing = -1;
393 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800394 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -0700395 getDeviceVersion(cameraId, /*overrideToPortrait*/false, /*out*/&portraitRotation,
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800396 /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700397 if (facing == -1) {
398 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
399 return;
400 }
401
402 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
403 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700404 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
405 if (res == OK) {
406 mPerfClassPrimaryCameraIds.insert(cameraId);
407 } else {
408 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
409 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
410 break;
411 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700412
413 if (facing == hardware::CAMERA_FACING_BACK) {
414 firstRearCameraSeen = true;
415 }
416 if (facing == hardware::CAMERA_FACING_FRONT) {
417 firstFrontCameraSeen = true;
418 }
419 }
420
421 if (firstRearCameraSeen && firstFrontCameraSeen) {
422 break;
423 }
424 }
425}
426
Austin Borgered99f642023-06-01 16:51:35 -0700427void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700428 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100429 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
430 if (res != OK) {
431 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
432 return;
433 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000434 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700435 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
436 if (res != OK) {
437 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
438 return;
439 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000440 std::vector<std::string> physicalCameraIds;
441 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700442 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100443 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700444 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100445 }
446
447 {
448 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700449 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000450 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100451 }
452
Austin Borgered99f642023-06-01 16:51:35 -0700453 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100454 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700455 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800456
Austin Borgered99f642023-06-01 16:51:35 -0700457 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100458 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800459
460 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700461 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100462}
463
Austin Borgered99f642023-06-01 16:51:35 -0700464void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800465 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700466 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100467 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700468 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100469 }
470
471 {
472 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700473 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100474 }
475}
476
Austin Borgered99f642023-06-01 16:51:35 -0700477void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800478 CameraDeviceStatus newHalStatus) {
479 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700480 cameraId.c_str(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700481
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800482 StatusInternal newStatus = mapToInternal(newHalStatus);
483
Austin Borgered99f642023-06-01 16:51:35 -0700484 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800485
486 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700487 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100488 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700489 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100490
491 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700492 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100493
Austin Borgered99f642023-06-01 16:51:35 -0700494 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700495 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700496 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700497 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700498 return;
499 }
500
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800501 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800502
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800503 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800504 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700505 return;
506 }
507
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800508 if (newStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000509 logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
510 oldStatus, newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800511
512 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
513 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700514 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800515
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800516 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700517 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800518 // Don't do this in updateStatus to avoid deadlock over mServiceLock
519 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700520
Ruben Brunkcc776712015-02-17 20:18:47 -0800521 // Remove cached shim parameters
522 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700523
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800524 // Remove online as well as offline client from the list of active clients,
525 // if they are present
Austin Borgered99f642023-06-01 16:51:35 -0700526 clientToDisconnectOnline = removeClientLocked(cameraId);
527 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700528 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800529
Austin Borgered99f642023-06-01 16:51:35 -0700530 disconnectClient(cameraId, clientToDisconnectOnline);
531 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700532
Austin Borgered99f642023-06-01 16:51:35 -0700533 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800534 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800535 if (oldStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000536 logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
537 oldStatus, newStatus));
Ruben Brunka8ca9152015-04-07 14:23:40 -0700538 }
Austin Borgered99f642023-06-01 16:51:35 -0700539 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700540 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800541}
Igor Murashkincba2c162013-03-20 15:56:31 -0700542
Austin Borgered99f642023-06-01 16:51:35 -0700543void CameraService::onDeviceStatusChanged(const std::string& id,
544 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800545 CameraDeviceStatus newHalStatus) {
546 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700547 __FUNCTION__, id.c_str(), physicalId.c_str(), newHalStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800548
549 StatusInternal newStatus = mapToInternal(newHalStatus);
550
551 std::shared_ptr<CameraState> state = getCameraState(id);
552
553 if (state == nullptr) {
554 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700555 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800556 return;
557 }
558
559 StatusInternal logicalCameraStatus = state->getStatus();
560 if (logicalCameraStatus != StatusInternal::PRESENT &&
561 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
562 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Austin Borgered99f642023-06-01 16:51:35 -0700563 __FUNCTION__, physicalId.c_str(), newHalStatus, logicalCameraStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800564 return;
565 }
566
567 bool updated = false;
568 if (newStatus == StatusInternal::PRESENT) {
569 updated = state->removeUnavailablePhysicalId(physicalId);
570 } else {
571 updated = state->addUnavailablePhysicalId(physicalId);
572 }
573
574 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700575 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800576 if (newStatus == StatusInternal::PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000577 logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800578 } else {
Henri Chataingbcb99452023-11-01 17:40:30 +0000579 logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800580 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700581 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
582 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
583 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700584 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700585 return;
586 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800587 Mutex::Autolock lock(mStatusListenerLock);
588 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700589 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
590 listener->getListenerPid(), listener->getListenerUid())) {
591 ALOGV("Skipping discovery callback for system-only camera device %s",
592 id.c_str());
593 continue;
594 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700595 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Austin Borgered99f642023-06-01 16:51:35 -0700596 mapToInterface(newStatus), id, physicalId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700597 listener->handleBinderStatus(ret,
598 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
599 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
600 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800601 }
602 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700603}
604
Austin Borgered99f642023-06-01 16:51:35 -0700605void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800606 if (clientToDisconnect.get() != nullptr) {
607 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700608 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800609 // Notify the client of disconnection
610 clientToDisconnect->notifyError(
611 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
612 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800613 clientToDisconnect->disconnect();
614 }
615}
616
Austin Borgered99f642023-06-01 16:51:35 -0700617void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800618 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700619 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
620 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
621 if (res != OK) {
622 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700623 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700624 return;
625 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800626 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700627 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800628}
629
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700630
Austin Borgered99f642023-06-01 16:51:35 -0700631void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700632 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
633 Mutex::Autolock al(mTorchStatusMutex);
634 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
635}
636
Austin Borgered99f642023-06-01 16:51:35 -0700637void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800638 int32_t newStrengthLevel) {
639 Mutex::Autolock lock(mStatusListenerLock);
640 for (auto& i : mListenerList) {
Austin Borgered99f642023-06-01 16:51:35 -0700641 auto ret = i->getListener()->onTorchStrengthLevelChanged(cameraId, newStrengthLevel);
Austin Borgere8e2c422022-05-12 13:45:24 -0700642 i->handleBinderStatus(ret,
643 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
644 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800645 }
646}
647
Austin Borgered99f642023-06-01 16:51:35 -0700648void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700649 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800650 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700651 __FUNCTION__, cameraId.c_str(), newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800652
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800653 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800654 status_t res = getTorchStatusLocked(cameraId, &status);
655 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700656 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700657 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800658 return;
659 }
660 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800661 return;
662 }
663
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800664 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800665 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800666 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
667 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800668 return;
669 }
670
Ruben Brunkcc776712015-02-17 20:18:47 -0800671 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700672 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700673 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700674 auto iter = mTorchUidMap.find(cameraId);
675 if (iter != mTorchUidMap.end()) {
676 int oldUid = iter->second.second;
677 int newUid = iter->second.first;
678 BatteryNotifier& notifier(BatteryNotifier::getInstance());
679 if (oldUid != newUid) {
680 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800681 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700682 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700683 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800684 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700685 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700686 }
687 iter->second.second = newUid;
688 } else {
689 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800690 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700691 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700692 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700693 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700694 }
695 }
696 }
697 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700698 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800699}
700
Joanne Chung02c13d02023-01-16 12:58:05 +0000701static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
702 permission::PermissionChecker permissionChecker;
703 AttributionSourceState attributionSource{};
704 attributionSource.pid = callingPid;
705 attributionSource.uid = callingUid;
706 bool checkPermissionForSystemCamera = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -0700707 toString16(sSystemCameraPermission), attributionSource, String16(),
708 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Joanne Chung02c13d02023-01-16 12:58:05 +0000709 bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -0700710 toString16(sCameraPermission), attributionSource, String16(),
711 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Joanne Chung02c13d02023-01-16 12:58:05 +0000712 return checkPermissionForSystemCamera && checkPermissionForCamera;
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700713}
714
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800715Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700716 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100717 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700718 bool hasSystemCameraPermissions =
719 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
720 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700721 switch (type) {
722 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700723 if (hasSystemCameraPermissions) {
724 *numCameras = static_cast<int>(mNormalDeviceIds.size());
725 } else {
726 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
727 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800728 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700729 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700730 if (hasSystemCameraPermissions) {
731 *numCameras = mNumberOfCameras;
732 } else {
733 *numCameras = mNumberOfCamerasWithoutSystemCamera;
734 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800735 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700736 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800737 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700738 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800739 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
740 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700741 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800742 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700743}
744
malikakash82ed4352023-07-21 22:44:34 +0000745Status CameraService::remapCameraIds(const hardware::CameraIdRemapping&
746 cameraIdRemapping) {
Austin Borgered99f642023-06-01 16:51:35 -0700747 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
malikakash82ed4352023-07-21 22:44:34 +0000748 const int pid = CameraThreadState::getCallingPid();
749 const int uid = CameraThreadState::getCallingUid();
750 ALOGE("%s: Permission Denial: can't configure camera ID mapping pid=%d, uid=%d",
751 __FUNCTION__, pid, uid);
752 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
753 "Permission Denial: no permission to configure camera id mapping");
754 }
755 TCameraIdRemapping cameraIdRemappingMap{};
malikakash214f6e62023-08-10 23:50:56 +0000756 binder::Status parseStatus = parseCameraIdRemapping(cameraIdRemapping, &cameraIdRemappingMap);
malikakash82ed4352023-07-21 22:44:34 +0000757 if (!parseStatus.isOk()) {
758 return parseStatus;
759 }
760 remapCameraIds(cameraIdRemappingMap);
761 return Status::ok();
762}
763
764Status CameraService::parseCameraIdRemapping(
765 const hardware::CameraIdRemapping& cameraIdRemapping,
malikakash214f6e62023-08-10 23:50:56 +0000766 /* out */ TCameraIdRemapping* cameraIdRemappingMap) {
Austin Borgered99f642023-06-01 16:51:35 -0700767 std::string packageName;
768 std::string cameraIdToReplace, updatedCameraId;
malikakash214f6e62023-08-10 23:50:56 +0000769 for(const auto& packageIdRemapping: cameraIdRemapping.packageIdRemappings) {
malikakash82ed4352023-07-21 22:44:34 +0000770 packageName = packageIdRemapping.packageName;
Austin Borgered99f642023-06-01 16:51:35 -0700771 if (packageName == "") {
malikakash82ed4352023-07-21 22:44:34 +0000772 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
773 "CameraIdRemapping: Package name cannot be empty");
774 }
malikakash214f6e62023-08-10 23:50:56 +0000775
776 if (packageIdRemapping.cameraIdsToReplace.size()
777 != packageIdRemapping.updatedCameraIds.size()) {
malikakash82ed4352023-07-21 22:44:34 +0000778 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
779 "CameraIdRemapping: Mismatch in CameraId Remapping lists sizes for package %s",
Austin Borgered99f642023-06-01 16:51:35 -0700780 packageName.c_str());
malikakash82ed4352023-07-21 22:44:34 +0000781 }
malikakash214f6e62023-08-10 23:50:56 +0000782 for(size_t i = 0; i < packageIdRemapping.cameraIdsToReplace.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700783 cameraIdToReplace = packageIdRemapping.cameraIdsToReplace[i];
784 updatedCameraId = packageIdRemapping.updatedCameraIds[i];
785 if (cameraIdToReplace == "" || updatedCameraId == "") {
malikakash214f6e62023-08-10 23:50:56 +0000786 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
787 "CameraIdRemapping: Camera Id cannot be empty for package %s",
Austin Borgered99f642023-06-01 16:51:35 -0700788 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +0000789 }
790 if (cameraIdToReplace == updatedCameraId) {
791 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
792 "CameraIdRemapping: CameraIdToReplace cannot be the same"
793 " as updatedCameraId for %s",
Austin Borgered99f642023-06-01 16:51:35 -0700794 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +0000795 }
796 (*cameraIdRemappingMap)[packageName][cameraIdToReplace] = updatedCameraId;
malikakash82ed4352023-07-21 22:44:34 +0000797 }
798 }
799 return Status::ok();
800}
801
802void CameraService::remapCameraIds(const TCameraIdRemapping& cameraIdRemapping) {
803 // Acquire mServiceLock and prevent other clients from connecting
804 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
805 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
806
malikakashedb38962023-09-06 00:03:35 +0000807 // Collect all existing clients for camera Ids that are being
808 // remapped in the new cameraIdRemapping, but only if they were being used by a
809 // targeted packageName.
malikakash82ed4352023-07-21 22:44:34 +0000810 std::vector<sp<BasicClient>> clientsToDisconnect;
Austin Borgered99f642023-06-01 16:51:35 -0700811 std::vector<std::string> cameraIdsToUpdate;
malikakash82ed4352023-07-21 22:44:34 +0000812 for (const auto& [packageName, injectionMap] : cameraIdRemapping) {
813 for (auto& [id0, id1] : injectionMap) {
Austin Borgered99f642023-06-01 16:51:35 -0700814 ALOGI("%s: UPDATE:= %s: %s: %s", __FUNCTION__, packageName.c_str(),
malikakash82ed4352023-07-21 22:44:34 +0000815 id0.c_str(), id1.c_str());
816 auto clientDescriptor = mActiveClientManager.get(id0);
817 if (clientDescriptor != nullptr) {
818 sp<BasicClient> clientSp = clientDescriptor->getValue();
819 if (clientSp->getPackageName() == packageName) {
malikakashedb38962023-09-06 00:03:35 +0000820 // This camera is being used by a targeted packageName and
821 // being remapped to a new camera Id. We should disconnect it.
malikakash82ed4352023-07-21 22:44:34 +0000822 clientsToDisconnect.push_back(clientSp);
823 cameraIdsToUpdate.push_back(id0);
824 }
825 }
826 }
827 }
828
malikakashedb38962023-09-06 00:03:35 +0000829 for (auto& clientSp : clientsToDisconnect) {
malikakashf4c80f22023-09-25 21:50:28 +0000830 // Notify the clients about the disconnection.
831 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
malikakashedb38962023-09-06 00:03:35 +0000832 CaptureResultExtras{});
833 }
malikakash82ed4352023-07-21 22:44:34 +0000834
835 // Do not hold mServiceLock while disconnecting clients, but retain the condition
836 // blocking other clients from connecting in mServiceLockWrapper if held.
837 mServiceLock.unlock();
838
malikakashedb38962023-09-06 00:03:35 +0000839 // Clear calling identity for disconnect() PID checks.
840 int64_t token = CameraThreadState::clearCallingIdentity();
841
malikakash82ed4352023-07-21 22:44:34 +0000842 // Disconnect clients.
843 for (auto& clientSp : clientsToDisconnect) {
malikakashedb38962023-09-06 00:03:35 +0000844 // This also triggers a call to updateStatus() which also reads mCameraIdRemapping
845 // and requires mCameraIdRemappingLock.
malikakash82ed4352023-07-21 22:44:34 +0000846 clientSp->disconnect();
847 }
848
malikakashedb38962023-09-06 00:03:35 +0000849 // Invoke destructors (which call disconnect()) now while we don't hold the mServiceLock.
850 clientsToDisconnect.clear();
851
852 CameraThreadState::restoreCallingIdentity(token);
malikakash82ed4352023-07-21 22:44:34 +0000853 mServiceLock.lock();
malikakashedb38962023-09-06 00:03:35 +0000854
855 {
856 Mutex::Autolock lock(mCameraIdRemappingLock);
857 // Update mCameraIdRemapping.
858 mCameraIdRemapping.clear();
859 mCameraIdRemapping.insert(cameraIdRemapping.begin(), cameraIdRemapping.end());
860 }
malikakash82ed4352023-07-21 22:44:34 +0000861}
862
Austin Borgered99f642023-06-01 16:51:35 -0700863std::vector<std::string> CameraService::findOriginalIdsForRemappedCameraId(
864 const std::string& inputCameraId, int clientUid) {
865 std::string packageName = getPackageNameFromUid(clientUid);
866 std::vector<std::string> cameraIds;
malikakash82ed4352023-07-21 22:44:34 +0000867 Mutex::Autolock lock(mCameraIdRemappingLock);
868 if (auto packageMapIter = mCameraIdRemapping.find(packageName);
869 packageMapIter != mCameraIdRemapping.end()) {
870 for (auto& [id0, id1]: packageMapIter->second) {
871 if (id1 == inputCameraId) {
872 cameraIds.push_back(id0);
873 }
874 }
875 }
876 return cameraIds;
877}
878
Austin Borgered99f642023-06-01 16:51:35 -0700879std::string CameraService::resolveCameraId(
880 const std::string& inputCameraId,
malikakashedb38962023-09-06 00:03:35 +0000881 int clientUid,
Austin Borgered99f642023-06-01 16:51:35 -0700882 const std::string& packageName) {
883 std::string packageNameVal = packageName;
malikakashedb38962023-09-06 00:03:35 +0000884 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +0000885 packageNameVal = getPackageNameFromUid(clientUid);
886 }
malikakashedb38962023-09-06 00:03:35 +0000887 if (clientUid < AID_APP_START || packageNameVal.empty()) {
888 // We shouldn't remap cameras for processes with system/vendor UIDs.
889 return inputCameraId;
890 }
malikakash82ed4352023-07-21 22:44:34 +0000891 Mutex::Autolock lock(mCameraIdRemappingLock);
892 if (auto packageMapIter = mCameraIdRemapping.find(packageNameVal);
893 packageMapIter != mCameraIdRemapping.end()) {
malikakash82ed4352023-07-21 22:44:34 +0000894 auto packageMap = packageMapIter->second;
895 if (auto replacementIdIter = packageMap.find(inputCameraId);
896 replacementIdIter != packageMap.end()) {
malikakashedb38962023-09-06 00:03:35 +0000897 ALOGI("%s: resolveCameraId: remapping cameraId %s for %s to %s",
malikakash82ed4352023-07-21 22:44:34 +0000898 __FUNCTION__, inputCameraId.c_str(),
malikakashedb38962023-09-06 00:03:35 +0000899 packageNameVal.c_str(),
malikakash82ed4352023-07-21 22:44:34 +0000900 replacementIdIter->second.c_str());
901 return replacementIdIter->second;
902 }
903 }
904 return inputCameraId;
905}
906
Austin Borger18b30a72022-10-27 12:20:29 -0700907Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800908 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700909 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100910 Mutex::Autolock l(mServiceLock);
malikakashedb38962023-09-06 00:03:35 +0000911 std::string unresolvedCameraId = cameraIdIntToStrLocked(cameraId);
912 std::string cameraIdStr = resolveCameraId(
913 unresolvedCameraId, CameraThreadState::getCallingUid());
914
Austin Borgered99f642023-06-01 16:51:35 -0700915 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700916 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
917 "characteristics for system only device %s: ", cameraIdStr.c_str());
918 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100919
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800920 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -0700921 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800922 return STATUS_ERROR(ERROR_DISCONNECTED,
923 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700924 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700925 bool hasSystemCameraPermissions =
926 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
927 CameraThreadState::getCallingUid());
928 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
929 if (hasSystemCameraPermissions) {
930 cameraIdBound = mNumberOfCameras;
931 }
932 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800933 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
934 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700935 }
936
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800937 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -0700938 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800939 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borgered99f642023-06-01 16:51:35 -0700940 cameraIdStr, overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100941 if (err != OK) {
942 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
943 "Error retrieving camera info from device %d: %s (%d)", cameraId,
944 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -0700945 logServiceError(std::string("Error retrieving camera info from device ")
946 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -0800947 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100948
Ruben Brunkcc776712015-02-17 20:18:47 -0800949 return ret;
950}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700951
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800952std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700953 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
954 auto callingPid = CameraThreadState::getCallingPid();
955 auto callingUid = CameraThreadState::getCallingUid();
Joanne Chung02c13d02023-01-16 12:58:05 +0000956 permission::PermissionChecker permissionChecker;
957 AttributionSourceState attributionSource{};
958 attributionSource.pid = callingPid;
959 attributionSource.uid = callingUid;
960 bool checkPermissionForSystemCamera = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -0700961 toString16(sSystemCameraPermission), attributionSource, String16(),
962 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Joanne Chung02c13d02023-01-16 12:58:05 +0000963 if (checkPermissionForSystemCamera || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700964 deviceIds = &mNormalDeviceIds;
965 }
966 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800967 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700968 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800969 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800970 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800971
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700972 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800973}
974
Austin Borgered99f642023-06-01 16:51:35 -0700975std::string CameraService::cameraIdIntToStr(int cameraIdInt) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800976 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -0700977 return cameraIdIntToStrLocked(cameraIdInt);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800978}
979
Austin Borgered99f642023-06-01 16:51:35 -0700980Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Austin Borger18b30a72022-10-27 12:20:29 -0700981 int targetSdkVersion, bool overrideToPortrait, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700982 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -0700983
malikakashedb38962023-09-06 00:03:35 +0000984 const std::string cameraId = resolveCameraId(unresolvedCameraId,
985 CameraThreadState::getCallingUid());
Austin Borgered99f642023-06-01 16:51:35 -0700986
Zhijun He2b59be82013-09-25 10:14:30 -0700987 if (!cameraInfo) {
988 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800989 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700990 }
991
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800992 if (!mInitialized) {
993 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -0700994 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800995 return STATUS_ERROR(ERROR_DISCONNECTED,
996 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700997 }
998
Austin Borgered99f642023-06-01 16:51:35 -0700999 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001000 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001001 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001002 }
1003
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001004 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001005
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001006 bool overrideForPerfClass =
1007 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001008 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001009 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borgered99f642023-06-01 16:51:35 -07001010 cameraId, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001011 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001012 if (res == NAME_NOT_FOUND) {
1013 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001014 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001015 strerror(-res), res);
1016 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001017 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1018 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001019 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001020 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001021 strerror(-res), res);
1022 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001023 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001024 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Austin Borgered99f642023-06-01 16:51:35 -07001025 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1026 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001027 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
Austin Borgered99f642023-06-01 16:51:35 -07001028 "for device %s", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001029 }
Jayant Chowdhary12361932018-08-27 14:46:13 -07001030 int callingPid = CameraThreadState::getCallingPid();
1031 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +01001032 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001033 // If it's not calling from cameraserver, check the permission only if
1034 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
1035 // it would've already been checked in shouldRejectSystemCameraConnection.
Joanne Chung02c13d02023-01-16 12:58:05 +00001036 permission::PermissionChecker permissionChecker;
1037 AttributionSourceState attributionSource{};
1038 attributionSource.pid = callingPid;
1039 attributionSource.uid = callingUid;
1040 bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -07001041 toString16(sCameraPermission), attributionSource, String16(),
1042 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Emilian Peeve20c6372018-08-14 18:45:53 +01001043 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001044 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001045 !checkPermissionForCamera) {
Emilian Peeve20c6372018-08-14 18:45:53 +01001046 res = cameraInfo->removePermissionEntries(
Austin Borgered99f642023-06-01 16:51:35 -07001047 mCameraProviderManager->getProviderTagIdLocked(cameraId),
Emilian Peeve20c6372018-08-14 18:45:53 +01001048 &tagsRemoved);
1049 if (res != OK) {
1050 cameraInfo->clear();
1051 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
1052 " characteristics needing camera permission for device %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07001053 cameraId.c_str(), strerror(-res), res);
Emilian Peeve20c6372018-08-14 18:45:53 +01001054 }
1055 }
1056
1057 if (!tagsRemoved.empty()) {
1058 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1059 tagsRemoved.data(), tagsRemoved.size());
1060 if (res != OK) {
1061 cameraInfo->clear();
1062 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
Austin Borgered99f642023-06-01 16:51:35 -07001063 "keys needing permission for device %s: %s (%d)", cameraId.c_str(),
Emilian Peeve20c6372018-08-14 18:45:53 +01001064 strerror(-res), res);
1065 }
1066 }
1067
Zhijun He2b59be82013-09-25 10:14:30 -07001068 return ret;
1069}
1070
malikakashedb38962023-09-06 00:03:35 +00001071Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -08001072 int32_t* torchStrength) {
1073 ATRACE_CALL();
1074 Mutex::Autolock l(mServiceLock);
malikakashedb38962023-09-06 00:03:35 +00001075 const std::string cameraId = resolveCameraId(
1076 unresolvedCameraId, CameraThreadState::getCallingUid());
Rucha Katakwar38284522021-11-10 11:25:21 -08001077 if (!mInitialized) {
1078 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1079 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1080 }
1081
1082 if(torchStrength == NULL) {
1083 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1084 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1085 }
1086
Austin Borgered99f642023-06-01 16:51:35 -07001087 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001088 if (res != OK) {
1089 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001090 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001091 strerror(-res), res);
1092 }
1093 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1094 return Status::ok();
1095}
1096
Austin Borgered99f642023-06-01 16:51:35 -07001097std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001098 time_t now = time(nullptr);
1099 char formattedTime[64];
1100 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001101 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001102}
1103
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001104Status CameraService::getCameraVendorTagDescriptor(
1105 /*out*/
1106 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001107 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001108 if (!mInitialized) {
1109 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001110 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001111 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001112 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1113 if (globalDescriptor != nullptr) {
1114 *desc = *(globalDescriptor.get());
1115 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001116 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001117}
1118
Emilian Peev71c73a22017-03-21 16:35:51 +00001119Status CameraService::getCameraVendorTagCache(
1120 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1121 ATRACE_CALL();
1122 if (!mInitialized) {
1123 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1124 return STATUS_ERROR(ERROR_DISCONNECTED,
1125 "Camera subsystem not available");
1126 }
1127 sp<VendorTagDescriptorCache> globalCache =
1128 VendorTagDescriptorCache::getGlobalVendorTagCache();
1129 if (globalCache != nullptr) {
1130 *cache = *(globalCache.get());
1131 }
1132 return Status::ok();
1133}
1134
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001135void CameraService::clearCachedVariables() {
1136 BasicClient::BasicClient::sCameraService = nullptr;
1137}
1138
Austin Borgered99f642023-06-01 16:51:35 -07001139std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001140 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001141 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001142
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001143 int deviceVersion = 0;
1144
Emilian Peevf53f66e2017-04-11 14:29:43 +01001145 status_t res;
1146 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001147 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001148 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001149 if (res != OK || transport == IPCTransport::INVALID) {
1150 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001151 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001152 return std::make_pair(-1, IPCTransport::INVALID) ;
1153 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001154 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001155
Emilian Peevf53f66e2017-04-11 14:29:43 +01001156 hardware::CameraInfo info;
1157 if (facing) {
Austin Borgered99f642023-06-01 16:51:35 -07001158 res = mCameraProviderManager->getCameraInfo(cameraId, overrideToPortrait,
Austin Borger18b30a72022-10-27 12:20:29 -07001159 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001160 if (res != OK) {
1161 return std::make_pair(-1, IPCTransport::INVALID);
1162 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001163 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001164 if (orientation) {
1165 *orientation = info.orientation;
1166 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001167 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001168
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001169 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001170}
1171
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001172Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001173 switch(err) {
1174 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001175 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001176 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001177 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1178 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001179 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001180 return STATUS_ERROR(ERROR_DISCONNECTED,
1181 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001182 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001183 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1184 "Camera HAL encountered error %d: %s",
1185 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001186 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001187}
1188
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001189Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001190 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1191 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001192 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001193 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001194 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
Austin Borgered99f642023-06-01 16:51:35 -07001195 bool forceSlowJpegMode, const std::string& originalCameraId, /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001196 // For HIDL devices
1197 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1198 // Create CameraClient based on device version reported by the HAL.
1199 int deviceVersion = deviceVersionAndTransport.first;
1200 switch(deviceVersion) {
1201 case CAMERA_DEVICE_API_VERSION_1_0:
1202 ALOGE("Camera using old HAL version: %d", deviceVersion);
1203 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1204 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001205 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001206 break;
1207 case CAMERA_DEVICE_API_VERSION_3_0:
1208 case CAMERA_DEVICE_API_VERSION_3_1:
1209 case CAMERA_DEVICE_API_VERSION_3_2:
1210 case CAMERA_DEVICE_API_VERSION_3_3:
1211 case CAMERA_DEVICE_API_VERSION_3_4:
1212 case CAMERA_DEVICE_API_VERSION_3_5:
1213 case CAMERA_DEVICE_API_VERSION_3_6:
1214 case CAMERA_DEVICE_API_VERSION_3_7:
1215 break;
1216 default:
1217 // Should not be reachable
1218 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1219 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1220 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001221 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001222 }
1223 }
1224 if (effectiveApiLevel == API_1) { // Camera1 API route
1225 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001226 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borgered99f642023-06-01 16:51:35 -07001227 packageName, featureId, cameraId,
1228 api1CameraId, facing, sensorOrientation,
Chengfei Taobe683db2023-01-31 18:52:49 +00001229 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait,
1230 forceSlowJpegMode);
1231 ALOGI("%s: Camera1 API (legacy), override to portrait %d, forceSlowJpegMode %d",
1232 __FUNCTION__, overrideToPortrait, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001233 } else { // Camera2 API route
1234 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1235 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001236 *client = new CameraDeviceClient(cameraService, tmp,
1237 cameraService->mCameraServiceProxyWrapper, packageName, systemNativeClient,
1238 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
malikakash82ed4352023-07-21 22:44:34 +00001239 overrideForPerfClass, overrideToPortrait, originalCameraId);
Austin Borger18b30a72022-10-27 12:20:29 -07001240 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001241 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001242 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001243}
1244
Austin Borgered99f642023-06-01 16:51:35 -07001245std::string CameraService::toString(std::set<userid_t> intSet) {
1246 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001247 bool first = true;
1248 for (userid_t i : intSet) {
1249 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001250 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001251 first = false;
1252 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001253 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001254 }
1255 }
Austin Borgered99f642023-06-01 16:51:35 -07001256 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001257}
1258
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001259int32_t CameraService::mapToInterface(TorchModeStatus status) {
1260 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1261 switch (status) {
1262 case TorchModeStatus::NOT_AVAILABLE:
1263 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1264 break;
1265 case TorchModeStatus::AVAILABLE_OFF:
1266 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1267 break;
1268 case TorchModeStatus::AVAILABLE_ON:
1269 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1270 break;
1271 default:
1272 ALOGW("Unknown new flash status: %d", status);
1273 }
1274 return serviceStatus;
1275}
1276
1277CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1278 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1279 switch (status) {
1280 case CameraDeviceStatus::NOT_PRESENT:
1281 serviceStatus = StatusInternal::NOT_PRESENT;
1282 break;
1283 case CameraDeviceStatus::PRESENT:
1284 serviceStatus = StatusInternal::PRESENT;
1285 break;
1286 case CameraDeviceStatus::ENUMERATING:
1287 serviceStatus = StatusInternal::ENUMERATING;
1288 break;
1289 default:
1290 ALOGW("Unknown new HAL device status: %d", status);
1291 }
1292 return serviceStatus;
1293}
1294
1295int32_t CameraService::mapToInterface(StatusInternal status) {
1296 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1297 switch (status) {
1298 case StatusInternal::NOT_PRESENT:
1299 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1300 break;
1301 case StatusInternal::PRESENT:
1302 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1303 break;
1304 case StatusInternal::ENUMERATING:
1305 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1306 break;
1307 case StatusInternal::NOT_AVAILABLE:
1308 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1309 break;
1310 case StatusInternal::UNKNOWN:
1311 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1312 break;
1313 default:
1314 ALOGW("Unknown new internal device status: %d", status);
1315 }
1316 return serviceStatus;
1317}
1318
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001319Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001320 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001321
Austin Borgered99f642023-06-01 16:51:35 -07001322 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001323 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001324 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001325 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001326 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1327 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001328 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Chengfei Taobe683db2023-01-31 18:52:49 +00001329 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true,
Austin Borgered99f642023-06-01 16:51:35 -07001330 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001331 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001332 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001333 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001334 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001335}
1336
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001337Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001338 /*out*/
1339 CameraParameters* parameters) {
1340
1341 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1342
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001343 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001344
1345 if (parameters == NULL) {
1346 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001347 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001348 }
1349
malikakashedb38962023-09-06 00:03:35 +00001350 std::string unresolvedCameraId = std::to_string(cameraId);
1351 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
1352 CameraThreadState::getCallingUid());
Ruben Brunkcc776712015-02-17 20:18:47 -08001353
1354 // Check if we already have parameters
1355 {
1356 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001357 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001358 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001359 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001360 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001361 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001362 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001363 }
1364 CameraParameters p = cameraState->getShimParams();
1365 if (!p.isEmpty()) {
1366 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001367 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001368 }
1369 }
1370
Jayant Chowdhary12361932018-08-27 14:46:13 -07001371 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001372 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001373 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001374 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001375 // Error already logged by callee
1376 return ret;
1377 }
1378
1379 // Check for parameters again
1380 {
1381 // Scope for service lock
1382 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001383 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001384 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001385 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001386 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001387 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001388 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001389 CameraParameters p = cameraState->getShimParams();
1390 if (!p.isEmpty()) {
1391 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001392 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001393 }
1394 }
1395
Ruben Brunkcc776712015-02-17 20:18:47 -08001396 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1397 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001398 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001399}
1400
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001401// Can camera service trust the caller based on the calling UID?
1402static bool isTrustedCallingUid(uid_t uid) {
1403 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001404 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001405 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001406 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001407 return true;
1408 default:
1409 return false;
1410 }
1411}
1412
Austin Borgered99f642023-06-01 16:51:35 -07001413static status_t getUidForPackage(const std::string &packageName, int userId, /*inout*/uid_t& uid,
1414 int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07001415 PermissionController pc;
Austin Borgered99f642023-06-01 16:51:35 -07001416 uid = pc.getPackageUid(toString16(packageName), 0);
Nicholas Sauera3620332019-04-03 14:05:17 -07001417 if (uid <= 0) {
Austin Borgered99f642023-06-01 16:51:35 -07001418 ALOGE("Unknown package: '%s'", packageName.c_str());
1419 dprintf(err, "Unknown package: '%s'\n", packageName.c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07001420 return BAD_VALUE;
1421 }
1422
1423 if (userId < 0) {
1424 ALOGE("Invalid user: %d", userId);
1425 dprintf(err, "Invalid user: %d\n", userId);
1426 return BAD_VALUE;
1427 }
1428
1429 uid = multiuser_get_uid(userId, uid);
1430 return NO_ERROR;
1431}
1432
Austin Borgered99f642023-06-01 16:51:35 -07001433Status CameraService::validateConnectLocked(const std::string& cameraId,
1434 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001435 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001436
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001437#ifdef __BRILLO__
1438 UNUSED(clientName8);
1439 UNUSED(clientUid);
1440 UNUSED(clientPid);
1441 UNUSED(originalClientPid);
1442#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001443 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1444 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001445 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001446 return allowed;
1447 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001448#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001449
Jayant Chowdhary12361932018-08-27 14:46:13 -07001450 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001451
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001452 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001453 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1454 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001455 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001456 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001457 }
1458
Ruben Brunkcc776712015-02-17 20:18:47 -08001459 if (getCameraState(cameraId) == nullptr) {
1460 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001461 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001462 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001463 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001464 }
1465
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001466 status_t err = checkIfDeviceIsUsable(cameraId);
1467 if (err != NO_ERROR) {
1468 switch(err) {
1469 case -ENODEV:
1470 case -EBUSY:
1471 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001472 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001473 default:
1474 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001475 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001476 }
1477 }
1478 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001479}
1480
Austin Borgered99f642023-06-01 16:51:35 -07001481Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1482 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001483 /*out*/int& originalClientPid) const {
Joanne Chung02c13d02023-01-16 12:58:05 +00001484 permission::PermissionChecker permissionChecker;
1485 AttributionSourceState attributionSource{};
1486
Jayant Chowdhary12361932018-08-27 14:46:13 -07001487 int callingPid = CameraThreadState::getCallingPid();
1488 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001489
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001490 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001491 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001492 clientUid = callingUid;
1493 } else if (!isTrustedCallingUid(callingUid)) {
1494 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1495 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001496 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1497 "Untrusted caller (calling PID %d, UID %d) trying to "
1498 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001499 callingPid, callingUid, cameraId.c_str(),
1500 clientName.c_str(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001501 }
1502
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001503 // Check if we can trust clientPid
1504 if (clientPid == USE_CALLING_PID) {
1505 clientPid = callingPid;
1506 } else if (!isTrustedCallingUid(callingUid)) {
1507 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1508 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001509 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1510 "Untrusted caller (calling PID %d, UID %d) trying to "
1511 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001512 callingPid, callingUid, cameraId.c_str(),
1513 clientName.c_str(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001514 }
1515
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001516 if (shouldRejectSystemCameraConnection(cameraId)) {
1517 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1518 cameraId.c_str());
1519 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001520 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001521 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001522 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1523 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001524 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001525 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001526 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001527
1528 }
1529
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001530 // If it's not calling from cameraserver, check the permission if the
1531 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1532 // android.permission.SYSTEM_CAMERA for system only camera devices).
Joanne Chung02c13d02023-01-16 12:58:05 +00001533 attributionSource.pid = clientPid;
1534 attributionSource.uid = clientUid;
Austin Borgered99f642023-06-01 16:51:35 -07001535 attributionSource.packageName = clientName;
Joanne Chung02c13d02023-01-16 12:58:05 +00001536 bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -07001537 toString16(sCameraPermission), attributionSource, String16(), AppOpsManager::OP_NONE)
Joanne Chung02c13d02023-01-16 12:58:05 +00001538 != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001539 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001540 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001541 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001542 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1543 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borgered99f642023-06-01 16:51:35 -07001544 clientName.c_str(), clientUid, clientPid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001545 }
1546
Svet Ganova453d0d2018-01-11 15:37:58 -08001547 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001548 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001549 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001550 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1551 clientPid, clientUid);
1552 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001553 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1554 "calling UID %d proc state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001555 clientName.c_str(), clientUid, clientPid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001556 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001557 }
1558
Michael Grooverd1d435a2018-12-18 17:39:42 -08001559 // If sensor privacy is enabled then prevent access to the camera
1560 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1561 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1562 return STATUS_ERROR_FMT(ERROR_DISABLED,
1563 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borgered99f642023-06-01 16:51:35 -07001564 "is enabled", clientName.c_str(), clientUid, clientPid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001565 }
1566
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001567 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1568 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001569 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001570 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001571
Ruben Brunk6267b532015-04-30 17:44:07 -07001572 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001573
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001574 // For non-system clients : Only allow clients who are being used by the current foreground
1575 // device user, unless calling from our own process.
1576 if (!doesClientHaveSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001577 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001578 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1579 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001580 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001581 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1582 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001583 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001584 }
1585
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001586 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001587}
1588
Austin Borgered99f642023-06-01 16:51:35 -07001589status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001590 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001591 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001592 if (cameraState == nullptr) {
1593 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001594 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001595 return -ENODEV;
1596 }
1597
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001598 StatusInternal currentStatus = cameraState->getStatus();
1599 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001600 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001601 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001602 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001603 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001604 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001605 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001606 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001607 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001608
Ruben Brunkcc776712015-02-17 20:18:47 -08001609 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001610}
1611
Ruben Brunkcc776712015-02-17 20:18:47 -08001612void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001613 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001614
Ruben Brunkcc776712015-02-17 20:18:47 -08001615 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001616 auto clientDescriptor =
1617 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001618 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001619 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1620
1621 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001622 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001623
1624 if (evicted.size() > 0) {
1625 // This should never happen - clients should already have been removed in disconnect
1626 for (auto& i : evicted) {
1627 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001628 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001629 }
1630
1631 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1632 __FUNCTION__);
1633 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001634
1635 // And register a death notification for the client callback. Do
1636 // this last to avoid Binder policy where a nested Binder
1637 // transaction might be pre-empted to service the client death
1638 // notification if the client process dies before linkToDeath is
1639 // invoked.
1640 sp<IBinder> remoteCallback = client->getRemote();
1641 if (remoteCallback != nullptr) {
1642 remoteCallback->linkToDeath(this);
1643 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001644}
1645
Austin Borgered99f642023-06-01 16:51:35 -07001646status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1647 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1648 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001649 /*out*/
1650 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001651 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001652 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001653 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001654 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001655 DescriptorPtr clientDescriptor;
1656 {
1657 if (effectiveApiLevel == API_1) {
1658 // If we are using API1, any existing client for this camera ID with the same remote
1659 // should be returned rather than evicted to allow MediaRecorder to work properly.
1660
1661 auto current = mActiveClientManager.get(cameraId);
1662 if (current != nullptr) {
1663 auto clientSp = current->getValue();
1664 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001665 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001666 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001667 " API level, evicting prior client...");
1668 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001669 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001670 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001671 *client = clientSp;
1672 return NO_ERROR;
1673 }
1674 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001675 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001676 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001677
Ruben Brunkcc776712015-02-17 20:18:47 -08001678 // Get current active client PIDs
1679 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1680 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001681
Emilian Peev8131a262017-02-01 12:33:43 +00001682 std::vector<int> priorityScores(ownerPids.size());
1683 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001684
Emilian Peev8131a262017-02-01 12:33:43 +00001685 // Get priority scores of all active PIDs
1686 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1687 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1688 /*out*/&priorityScores[0]);
1689 if (err != OK) {
1690 ALOGE("%s: Priority score query failed: %d",
1691 __FUNCTION__, err);
1692 return err;
1693 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001694
Ruben Brunkcc776712015-02-17 20:18:47 -08001695 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001696 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001697 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001698 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001699 resource_policy::ClientPriority(priorityScores[i], states[i],
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001700 /* isVendorClient won't get copied over*/ false,
1701 /* oomScoreOffset won't get copied over*/ 0));
Ruben Brunkcc776712015-02-17 20:18:47 -08001702 }
1703 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001704
Ruben Brunkcc776712015-02-17 20:18:47 -08001705 // Get state for the given cameraId
1706 auto state = getCameraState(cameraId);
1707 if (state == nullptr) {
1708 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001709 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001710 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001711 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001712 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001713
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001714 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1715 int32_t actualState = states[states.size() - 1];
1716
1717 // Make descriptor for incoming client. We store the oomScoreOffset
1718 // since we might need it later on new handleEvictionsLocked and
1719 // ProcessInfoService would not take that into account.
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001720 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001721 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001722 state->getConflicting(), actualScore, clientPid, actualState,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001723 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001724
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001725 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1726
Ruben Brunkcc776712015-02-17 20:18:47 -08001727 // Find clients that would be evicted
1728 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1729
1730 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1731 // background, so we cannot do evictions
1732 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1733 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1734 " priority).", clientPid);
1735
1736 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07001737 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08001738 auto incompatibleClients =
1739 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1740
Austin Borgered99f642023-06-01 16:51:35 -07001741 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
1742 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
1743 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001744 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001745
1746 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07001747 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001748 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001749 i->getKey().c_str(),
1750 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00001751 i->getOwnerId(), i->getPriority().getScore(),
1752 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001753 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07001754 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
1755 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001756 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001757 }
1758
1759 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001760 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001761 mEventLog.add(msg);
1762
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001763 auto current = mActiveClientManager.get(cameraId);
1764 if (current != nullptr) {
1765 return -EBUSY; // CAMERA_IN_USE
1766 } else {
1767 return -EUSERS; // MAX_CAMERAS_IN_USE
1768 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001769 }
1770
1771 for (auto& i : evicted) {
1772 sp<BasicClient> clientSp = i->getValue();
1773 if (clientSp.get() == nullptr) {
1774 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1775
1776 // TODO: Remove this
1777 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1778 __FUNCTION__);
1779 mActiveClientManager.remove(i);
1780 continue;
1781 }
1782
1783 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07001784 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001785 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001786
Ruben Brunkcc776712015-02-17 20:18:47 -08001787 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07001788 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001789 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1790 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001791 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00001792 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07001793 i->getPriority().getState(), cameraId.c_str(),
1794 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001795 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001796
1797 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001798 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001799 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001800 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001801 }
1802
Ruben Brunkcc776712015-02-17 20:18:47 -08001803 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1804 // other clients from connecting in mServiceLockWrapper if held
1805 mServiceLock.unlock();
1806
1807 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001808 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001809
1810 // Destroy evicted clients
1811 for (auto& i : evictedClients) {
1812 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001813 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001814 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001815
Jayant Chowdhary12361932018-08-27 14:46:13 -07001816 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001817
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001818 for (const auto& i : evictedClients) {
1819 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001820 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001821 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1822 if (ret == TIMED_OUT) {
1823 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07001824 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
1825 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001826 return -EBUSY;
1827 }
1828 if (ret != NO_ERROR) {
1829 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07001830 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
1831 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001832 return ret;
1833 }
1834 }
1835
1836 evictedClients.clear();
1837
Ruben Brunkcc776712015-02-17 20:18:47 -08001838 // Once clients have been disconnected, relock
1839 mServiceLock.lock();
1840
1841 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1842 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1843 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001844 }
1845
Ruben Brunkcc776712015-02-17 20:18:47 -08001846 *partial = clientDescriptor;
1847 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001848}
1849
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001850Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001851 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001852 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001853 const std::string& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001854 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001855 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001856 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001857 bool overrideToPortrait,
Chengfei Taobe683db2023-01-31 18:52:49 +00001858 bool forceSlowJpegMode,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001859 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001860 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001861
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001862 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001863 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001864
malikakashedb38962023-09-06 00:03:35 +00001865 std::string unresolvedCameraId = cameraIdIntToStr(api1CameraId);
1866 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
1867 CameraThreadState::getCallingUid());
1868
Ruben Brunkcc776712015-02-17 20:18:47 -08001869 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07001870 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
1871 clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07001872 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07001873 overrideToPortrait, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001874
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001875 if(!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07001876 logRejected(cameraIdStr, CameraThreadState::getCallingPid(), clientPackageName,
1877 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001878 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001879 }
1880
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001881 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00001882
1883 const sp<IServiceManager> sm(defaultServiceManager());
1884 const auto& mActivityManager = getActivityManager();
1885 if (mActivityManager) {
1886 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
1887 CameraThreadState::getCallingUid(),
1888 CameraThreadState::getCallingPid());
1889 }
1890
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001891 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001892}
1893
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001894bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1895 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001896 // If the client is not a vendor client, don't add listener if
1897 // a) the camera is a publicly hidden secure camera OR
1898 // b) the camera is a system only camera and the client doesn't
1899 // have android.permission.SYSTEM_CAMERA permissions.
1900 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1901 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1902 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001903 return true;
1904 }
1905 return false;
1906}
1907
Austin Borgered99f642023-06-01 16:51:35 -07001908bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001909 // Rules for rejection:
1910 // 1) If cameraserver tries to access this camera device, accept the
1911 // connection.
1912 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001913 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001914 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1915 // and the serving thread is a non hwbinder thread, the client must have
1916 // android.permission.SYSTEM_CAMERA permissions to connect.
1917
1918 int cPid = CameraThreadState::getCallingPid();
1919 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001920 bool systemClient = doesClientHaveSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001921 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1922 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001923 // This isn't a known camera ID, so it's not a system camera
1924 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1925 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001926 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001927
1928 // (1) Cameraserver trying to connect, accept.
1929 if (CameraThreadState::getCallingPid() == getpid()) {
1930 return false;
1931 }
1932 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001933 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001934 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1935 return true;
1936 }
1937 // (3) Here we only check for permissions if it is a system only camera device. This is since
1938 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1939 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1940 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001941 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001942 !hasPermissionsForSystemCamera(cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001943 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1944 cameraId.c_str());
1945 return true;
1946 }
1947
1948 return false;
1949}
1950
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001951Status CameraService::connectDevice(
1952 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07001953 const std::string& unresolvedCameraId,
1954 const std::string& clientPackageName,
1955 const std::optional<std::string>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001956 int clientUid, int oomScoreOffset, int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001957 bool overrideToPortrait,
Ruben Brunkcc776712015-02-17 20:18:47 -08001958 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001959 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001960
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001961 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001962 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001963 sp<CameraDeviceClient> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07001964 std::string clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001965 int callingPid = CameraThreadState::getCallingPid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001966 bool systemNativeClient = false;
1967 if (doesClientHaveSystemUid() && (clientPackageNameAdj.size() == 0)) {
1968 std::string systemClient =
Austin Borgered99f642023-06-01 16:51:35 -07001969 fmt::sprintf("client.pid<%d>", CameraThreadState::getCallingPid());
1970 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001971 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001972 }
malikakashedb38962023-09-06 00:03:35 +00001973 const std::string cameraId = resolveCameraId(
1974 unresolvedCameraId,
1975 CameraThreadState::getCallingUid(),
1976 clientPackageNameAdj);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001977
1978 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07001979 std::string msg =
1980 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
1981 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
1982 cameraId.c_str());
1983 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1984 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001985 }
1986
Austin Borger9bfa0a72022-08-03 17:50:40 -07001987 userid_t clientUserId = multiuser_get_user_id(clientUid);
1988 int callingUid = CameraThreadState::getCallingUid();
1989 if (clientUid == USE_CALLING_UID) {
1990 clientUserId = multiuser_get_user_id(callingUid);
1991 }
1992
1993 if (mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07001994 std::string msg = "Camera disabled by device policy";
1995 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1996 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07001997 }
1998
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001999 // enforce system camera permissions
2000 if (oomScoreOffset > 0 &&
Austin Borger86a588e2022-05-23 12:41:58 -07002001 !hasPermissionsForSystemCamera(callingPid, CameraThreadState::getCallingUid()) &&
2002 !isTrustedCallingUid(CameraThreadState::getCallingUid())) {
Austin Borgered99f642023-06-01 16:51:35 -07002003 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002004 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07002005 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2006 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2007 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002008 }
2009
Austin Borgered99f642023-06-01 16:51:35 -07002010 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
2011 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002012 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
Chengfei Taobe683db2023-01-31 18:52:49 +00002013 targetSdkVersion, overrideToPortrait, /*forceSlowJpegMode*/false,
Austin Borgered99f642023-06-01 16:51:35 -07002014 unresolvedCameraId, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002015
Austin Borgered99f642023-06-01 16:51:35 -07002016 if (!ret.isOk()) {
2017 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002018 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002019 }
2020
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002021 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002022 Mutex::Autolock lock(mServiceLock);
2023
2024 // Clear the previous cached logs and reposition the
2025 // file offset to beginning of the file to log new data.
2026 // If either truncate or lseek fails, close the previous file and create a new one.
2027 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2028 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2029 // Close the previous memfd.
2030 close(mMemFd);
2031 // If failure to wipe the data, then create a new file and
2032 // assign the new value to mMemFd.
2033 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2034 if (mMemFd == -1) {
2035 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2036 }
2037 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002038 const sp<IServiceManager> sm(defaultServiceManager());
2039 const auto& mActivityManager = getActivityManager();
2040 if (mActivityManager) {
2041 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
2042 CameraThreadState::getCallingUid(),
2043 CameraThreadState::getCallingPid());
2044 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002045 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002046}
2047
Austin Borgered99f642023-06-01 16:51:35 -07002048std::string CameraService::getPackageNameFromUid(int clientUid) {
2049 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002050
2051 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07002052 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002053 if (binder == 0) {
2054 ALOGE("Cannot get permission service");
2055 // Return empty package name and the further interaction
2056 // with camera will likely fail
2057 return packageName;
2058 }
2059
2060 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2061 Vector<String16> packages;
2062
2063 permCtrl->getPackagesForUid(clientUid, packages);
2064
2065 if (packages.isEmpty()) {
2066 ALOGE("No packages for calling UID %d", clientUid);
2067 // Return empty package name and the further interaction
2068 // with camera will likely fail
2069 return packageName;
2070 }
2071
2072 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002073 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002074
2075 return packageName;
2076}
2077
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002078template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002079Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2080 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2081 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002082 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002083 bool overrideToPortrait, bool forceSlowJpegMode, const std::string& originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002084 /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002085 binder::Status ret = binder::Status::ok();
2086
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002087 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002088 std::string clientPackageName;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002089 if (clientPackageNameMaybe.size() <= 0) {
2090 // NDK calls don't come with package names, but we need one for various cases.
2091 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2092 // do exist. For all authentication cases, all packages under the same UID get the
2093 // same permissions, so picking any associated package name is sufficient. For some
2094 // other cases, this may give inaccurate names for clients in logs.
2095 isNonSystemNdk = true;
2096 int packageUid = (clientUid == USE_CALLING_UID) ?
2097 CameraThreadState::getCallingUid() : clientUid;
2098 clientPackageName = getPackageNameFromUid(packageUid);
2099 } else {
2100 clientPackageName = clientPackageNameMaybe;
2101 }
2102
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002103 int originalClientPid = 0;
2104
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002105 int packagePid = (clientPid == USE_CALLING_PID) ?
2106 CameraThreadState::getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002107 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002108 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002109 static_cast<int>(effectiveApiLevel));
2110
Shuzhen Wang316781a2020-08-18 18:11:01 -07002111 nsecs_t openTimeNs = systemTime();
2112
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002113 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002114 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002115 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002116
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002117 {
2118 // Acquire mServiceLock and prevent other clients from connecting
2119 std::unique_ptr<AutoConditionLock> lock =
2120 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2121
2122 if (lock == nullptr) {
2123 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2124 , clientPid);
2125 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2126 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002127 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002128 }
2129
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002130 // Enforce client permissions and do basic validity checks
Austin Borgered99f642023-06-01 16:51:35 -07002131 if(!(ret = validateConnectLocked(cameraId, clientPackageName,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002132 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2133 return ret;
2134 }
2135
2136 // Check the shim parameters after acquiring lock, if they have already been updated and
2137 // we were doing a shim update, return immediately
2138 if (shimUpdateOnly) {
2139 auto cameraState = getCameraState(cameraId);
2140 if (cameraState != nullptr) {
2141 if (!cameraState->getShimParams().isEmpty()) return ret;
2142 }
2143 }
2144
2145 status_t err;
2146
2147 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002148 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002149 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002150 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2151 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002152 switch (err) {
2153 case -ENODEV:
2154 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2155 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002156 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002157 case -EBUSY:
2158 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2159 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002160 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002161 case -EUSERS:
2162 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2163 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002164 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002165 default:
2166 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2167 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002168 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002169 }
2170 }
2171
2172 if (clientTmp.get() != nullptr) {
2173 // Handle special case for API1 MediaRecorder where the existing client is returned
2174 device = static_cast<CLIENT*>(clientTmp.get());
2175 return ret;
2176 }
2177
2178 // give flashlight a chance to close devices if necessary.
2179 mFlashlight->prepareDeviceOpen(cameraId);
2180
Austin Borger18b30a72022-10-27 12:20:29 -07002181 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002182 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07002183 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
2184 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002185 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002186 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002187 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002188 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002189 }
2190
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002191 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002192 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002193 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002194 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002195 clientFeatureId, cameraId, api1CameraId, facing,
2196 orientation, clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002197 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
malikakash82ed4352023-07-21 22:44:34 +00002198 overrideToPortrait, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002199 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002200 return ret;
2201 }
2202 client = static_cast<CLIENT*>(tmp.get());
2203
2204 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2205 __FUNCTION__);
2206
Austin Borgered99f642023-06-01 16:51:35 -07002207 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002208 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002209 if (err != OK) {
2210 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002211 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002212 mServiceLock.unlock();
2213 client->disconnect();
2214 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002215 switch(err) {
2216 case BAD_VALUE:
2217 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002218 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002219 case -EBUSY:
2220 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002221 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002222 case -EUSERS:
2223 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2224 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002225 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002226 case PERMISSION_DENIED:
2227 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002228 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002229 case -EACCES:
2230 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002231 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002232 case -ENODEV:
2233 default:
2234 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002235 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002236 strerror(-err), err);
2237 }
2238 }
2239
2240 // Update shim paremeters for legacy clients
2241 if (effectiveApiLevel == API_1) {
2242 // Assume we have always received a Client subclass for API1
2243 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2244 String8 rawParams = shimClient->getParameters();
2245 CameraParameters params(rawParams);
2246
2247 auto cameraState = getCameraState(cameraId);
2248 if (cameraState != nullptr) {
2249 cameraState->setShimParams(params);
2250 } else {
2251 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002252 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002253 }
2254 }
2255
Ravneetaeb20dc2022-03-30 05:33:03 +00002256 // Enable/disable camera service watchdog
2257 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2258
Emilian Peev6d45db82024-01-18 20:11:54 +00002259 CameraMetadata chars;
2260 bool rotateAndCropSupported = true;
2261 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
2262 &chars, overrideToPortrait);
2263 if (err == OK) {
2264 auto availableRotateCropEntry = chars.find(
2265 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2266 if (availableRotateCropEntry.count <= 1) {
2267 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002268 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002269 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002270 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2271 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002272 }
2273
Emilian Peev6d45db82024-01-18 20:11:54 +00002274 if (rotateAndCropSupported) {
2275 // Set rotate-and-crop override behavior
2276 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2277 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
2278 } else if (overrideToPortrait && portraitRotation != 0) {
2279 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2280 switch (portraitRotation) {
2281 case 90:
2282 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2283 break;
2284 case 180:
2285 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2286 break;
2287 case 270:
2288 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2289 break;
2290 default:
2291 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2292 break;
2293 }
2294 client->setRotateAndCropOverride(rotateAndCropMode);
2295 } else {
2296 client->setRotateAndCropOverride(
2297 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2298 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2299 }
2300 }
2301
2302 bool autoframingSupported = true;
2303 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2304 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2305 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2306 autoframingSupported = false;
2307 }
2308
2309 if (autoframingSupported) {
2310 // Set autoframing override behaviour
2311 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2312 client->setAutoframingOverride(mOverrideAutoframingMode);
2313 } else {
2314 client->setAutoframingOverride(
2315 mCameraServiceProxyWrapper->getAutoframingOverride(
2316 clientPackageName));
2317 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002318 }
2319
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002320 // Set camera muting behavior
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002321 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08002322 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002323 if (client->supportsCameraMute()) {
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002324 client->setCameraMute(
2325 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2326 } else if (isCameraPrivacyEnabled) {
2327 // no camera mute supported, but privacy is on! => disconnect
2328 ALOGI("Camera mute not supported for package: %s, camera id: %s",
Austin Borgered99f642023-06-01 16:51:35 -07002329 client->getPackageName().c_str(), cameraId.c_str());
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002330 // Do not hold mServiceLock while disconnecting clients, but
2331 // retain the condition blocking other clients from connecting
2332 // in mServiceLockWrapper if held.
2333 mServiceLock.unlock();
2334 // Clear caller identity temporarily so client disconnect PID
2335 // checks work correctly
2336 int64_t token = CameraThreadState::clearCallingIdentity();
2337 // Note AppOp to trigger the "Unblock" dialog
2338 client->noteAppOp();
2339 client->disconnect();
2340 CameraThreadState::restoreCallingIdentity(token);
2341 // Reacquire mServiceLock
2342 mServiceLock.lock();
2343
2344 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002345 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002346 }
2347
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002348 if (shimUpdateOnly) {
2349 // If only updating legacy shim parameters, immediately disconnect client
2350 mServiceLock.unlock();
2351 client->disconnect();
2352 mServiceLock.lock();
2353 } else {
2354 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002355 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002356 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002357
2358 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002359 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002360 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002361 } // lock is destroyed, allow further connect calls
2362
2363 // Important: release the mutex here so the client can call back into the service from its
2364 // destructor (can be at the end of the call)
2365 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002366
2367 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002368 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002369 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002370
Cliff Wud3a05312021-04-26 23:07:31 +08002371 {
2372 Mutex::Autolock lock(mInjectionParametersLock);
2373 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2374 mInjectionInitPending = false;
2375 status_t res = NO_ERROR;
2376 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2377 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002378 sp<BasicClient> clientSp = clientDescriptor->getValue();
2379 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2380 if(res != OK) {
2381 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2382 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002383 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002384 }
2385 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002386 if (res != OK) {
2387 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2388 }
2389 } else {
2390 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002391 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002392 res = NO_INIT;
2393 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2394 }
2395 }
2396 }
2397
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002398 return ret;
2399}
2400
Austin Borgered99f642023-06-01 16:51:35 -07002401status_t CameraService::addOfflineClient(const std::string &cameraId,
2402 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002403 if (offlineClient.get() == nullptr) {
2404 return BAD_VALUE;
2405 }
2406
2407 {
2408 // Acquire mServiceLock and prevent other clients from connecting
2409 std::unique_ptr<AutoConditionLock> lock =
2410 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2411
2412 if (lock == nullptr) {
2413 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2414 , __FUNCTION__, offlineClient->getClientPid());
2415 return TIMED_OUT;
2416 }
2417
2418 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2419 if (onlineClientDesc.get() == nullptr) {
2420 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2421 cameraId.c_str());
2422 return BAD_VALUE;
2423 }
2424
2425 // Offline clients do not evict or conflict with other online devices. Resource sharing
2426 // conflicts are handled by the camera provider which will either succeed or fail before
2427 // reaching this method.
2428 const auto& onlinePriority = onlineClientDesc->getPriority();
2429 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2430 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002431 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002432 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002433 // native clients don't have offline processing support.
2434 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002435 if (offlineClientDesc == nullptr) {
2436 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2437 return BAD_VALUE;
2438 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002439
2440 // Allow only one offline device per camera
2441 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2442 if (!incompatibleClients.empty()) {
2443 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2444 return BAD_VALUE;
2445 }
2446
Austin Borgered99f642023-06-01 16:51:35 -07002447 std::string monitorTags = isClientWatched(offlineClient.get())
2448 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002449 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002450 if (err != OK) {
2451 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2452 return err;
2453 }
2454
2455 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2456 if (evicted.size() > 0) {
2457 for (auto& i : evicted) {
2458 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002459 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002460 }
2461
2462 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2463 "properly", __FUNCTION__);
2464
2465 return BAD_VALUE;
2466 }
2467
2468 logConnectedOffline(offlineClientDesc->getKey(),
2469 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002470 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002471
2472 sp<IBinder> remoteCallback = offlineClient->getRemote();
2473 if (remoteCallback != nullptr) {
2474 remoteCallback->linkToDeath(this);
2475 }
2476 } // lock is destroyed, allow further connect calls
2477
2478 return OK;
2479}
2480
Austin Borgered99f642023-06-01 16:51:35 -07002481Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
malikakash82ed4352023-07-21 22:44:34 +00002482 int32_t torchStrength,
Rucha Katakwar38284522021-11-10 11:25:21 -08002483 const sp<IBinder>& clientBinder) {
2484 Mutex::Autolock lock(mServiceLock);
2485
2486 ATRACE_CALL();
2487 if (clientBinder == nullptr) {
2488 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2489 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2490 "Torch client binder in null.");
2491 }
2492
Rucha Katakwar38284522021-11-10 11:25:21 -08002493 int uid = CameraThreadState::getCallingUid();
malikakashedb38962023-09-06 00:03:35 +00002494 const std::string cameraId = resolveCameraId(unresolvedCameraId, uid);
Austin Borgered99f642023-06-01 16:51:35 -07002495 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002496 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002497 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002498 }
2499
2500 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002501 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002502 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002503 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002504 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002505 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002506 }
2507
2508 StatusInternal cameraStatus = state->getStatus();
2509 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2510 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002511 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002512 (int)cameraStatus);
2513 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002514 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002515 }
2516
2517 {
2518 Mutex::Autolock al(mTorchStatusMutex);
2519 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002520 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002521 if (err != OK) {
2522 if (err == NAME_NOT_FOUND) {
2523 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002524 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002525 }
2526 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002527 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002528 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2529 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002530 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002531 }
2532
2533 if (status == TorchModeStatus::NOT_AVAILABLE) {
2534 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2535 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002536 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002537 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2538 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002539 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002540 } else {
2541 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002542 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002543 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2544 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002545 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002546 }
2547 }
2548 }
2549
2550 {
2551 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002552 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002553 }
2554 // Check if the current torch strength level is same as the new one.
2555 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002556 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002557
Austin Borgered99f642023-06-01 16:51:35 -07002558 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002559
2560 if (err != OK) {
2561 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002562 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002563 switch (err) {
2564 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002565 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2566 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002567 errorCode = ERROR_ILLEGAL_ARGUMENT;
2568 break;
2569 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002570 msg = fmt::sprintf("Camera \"%s\" is in use",
2571 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002572 errorCode = ERROR_CAMERA_IN_USE;
2573 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002574 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002575 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002576 "valid range.", torchStrength);
2577 errorCode = ERROR_ILLEGAL_ARGUMENT;
2578 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002579 default:
Austin Borgered99f642023-06-01 16:51:35 -07002580 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002581 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002582 }
Austin Borgered99f642023-06-01 16:51:35 -07002583 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2584 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002585 }
2586
2587 {
2588 // update the link to client's death
2589 // Store the last client that turns on each camera's torch mode.
2590 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002591 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002592 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002593 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002594 } else {
2595 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2596 mTorchClientMap.replaceValueAt(index, clientBinder);
2597 }
2598 clientBinder->linkToDeath(this);
2599 }
2600
2601 int clientPid = CameraThreadState::getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002602 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002603 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002604 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002605 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002606 }
2607 return Status::ok();
2608}
2609
Austin Borgered99f642023-06-01 16:51:35 -07002610Status CameraService::setTorchMode(const std::string& unresolvedCameraId,
malikakash82ed4352023-07-21 22:44:34 +00002611 bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002612 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002613 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002614
2615 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002616 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002617 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002618 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2619 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002620 }
2621
Jayant Chowdhary12361932018-08-27 14:46:13 -07002622 int uid = CameraThreadState::getCallingUid();
malikakashedb38962023-09-06 00:03:35 +00002623 const std::string cameraId = resolveCameraId(unresolvedCameraId, uid);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002624
Austin Borgered99f642023-06-01 16:51:35 -07002625 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002626 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07002627 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002628 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002629 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07002630 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08002631 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002632 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002633 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002634 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002635 }
2636
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002637 StatusInternal cameraStatus = state->getStatus();
2638 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002639 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07002640 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
2641 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002642 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002643 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002644 }
2645
2646 {
2647 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002648 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002649 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002650 if (err != OK) {
2651 if (err == NAME_NOT_FOUND) {
2652 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002653 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002654 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002655 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002656 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002657 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002658 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002659 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002660 }
2661
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002662 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002663 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002664 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002665 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002666 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2667 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002668 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002669 } else {
2670 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002671 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002672 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2673 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002674 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002675 }
2676 }
2677 }
2678
Ruben Brunk99e69712015-05-26 17:25:07 -07002679 {
2680 // Update UID map - this is used in the torch status changed callbacks, so must be done
2681 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002682 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002683 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07002684 }
2685
Austin Borgered99f642023-06-01 16:51:35 -07002686 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002687
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002688 if (err != OK) {
2689 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002690 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002691 switch (err) {
2692 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002693 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
2694 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002695 errorCode = ERROR_ILLEGAL_ARGUMENT;
2696 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08002697 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002698 msg = fmt::sprintf("Camera \"%s\" is in use",
2699 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08002700 errorCode = ERROR_CAMERA_IN_USE;
2701 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002702 default:
Austin Borgered99f642023-06-01 16:51:35 -07002703 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002704 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002705 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002706 errorCode = ERROR_INVALID_OPERATION;
2707 }
Austin Borgered99f642023-06-01 16:51:35 -07002708 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2709 logServiceError(msg, errorCode);
2710 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002711 }
2712
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002713 {
2714 // update the link to client's death
2715 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002716 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002717 if (enabled) {
2718 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002719 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002720 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07002721 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002722 mTorchClientMap.replaceValueAt(index, clientBinder);
2723 }
2724 clientBinder->linkToDeath(this);
2725 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07002726 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002727 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002728 }
2729
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002730 int clientPid = CameraThreadState::getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07002731 std::string torchState = enabled ? "on" : "off";
2732 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
2733 torchState.c_str(), clientPid);
2734 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002735 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002736}
2737
Austin Borgered99f642023-06-01 16:51:35 -07002738void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
2739 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
2740 mTorchUidMap[cameraId].first = uid;
2741 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08002742 } else {
2743 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07002744 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08002745 }
2746}
2747
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002748Status CameraService::notifySystemEvent(int32_t eventId,
2749 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002750 const int pid = CameraThreadState::getCallingPid();
2751 const int selfPid = getpid();
2752
2753 // Permission checks
2754 if (pid != selfPid) {
2755 // Ensure we're being called by system_server, or similar process with
2756 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07002757 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002758 const int uid = CameraThreadState::getCallingUid();
2759 ALOGE("Permission Denial: cannot send updates to camera service about system"
2760 " events from pid=%d, uid=%d", pid, uid);
2761 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09002762 "No permission to send updates to camera service about system events"
2763 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002764 }
2765 }
2766
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002767 ATRACE_CALL();
2768
Ruben Brunk36597b22015-03-20 22:15:57 -07002769 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002770 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002771 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002772 // from a system server crash
2773 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002774 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002775 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002776 break;
2777 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02002778 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
2779 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00002780 if (args.size() != 1) {
2781 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
2782 "USB Device Event requires 1 argument");
2783 }
2784
Valentin Iftime29e2e152021-08-13 15:17:33 +02002785 // Notify CameraProviderManager for lazy HALs
2786 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
2787 std::to_string(args[0]));
2788 break;
2789 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002790 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002791 default: {
2792 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2793 eventId);
2794 break;
2795 }
2796 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002797 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002798}
2799
Emilian Peev53722fa2019-02-22 17:47:20 -08002800void CameraService::notifyMonitoredUids() {
2801 Mutex::Autolock lock(mStatusListenerLock);
2802
2803 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002804 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07002805 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
2806 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08002807 }
2808}
2809
Austin Borgerdddb7552023-03-30 17:53:01 -07002810void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
2811 Mutex::Autolock lock(mStatusListenerLock);
2812
2813 for (const auto& it : mListenerList) {
2814 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
2815 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
2816 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
2817 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
2818 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
2819 }
2820 }
2821}
2822
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002823Status CameraService::notifyDeviceStateChange(int64_t newState) {
2824 const int pid = CameraThreadState::getCallingPid();
2825 const int selfPid = getpid();
2826
2827 // Permission checks
2828 if (pid != selfPid) {
2829 // Ensure we're being called by system_server, or similar process with
2830 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07002831 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002832 const int uid = CameraThreadState::getCallingUid();
2833 ALOGE("Permission Denial: cannot send updates to camera service about device"
2834 " state changes from pid=%d, uid=%d", pid, uid);
2835 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2836 "No permission to send updates to camera service about device state"
2837 " changes from pid=%d, uid=%d", pid, uid);
2838 }
2839 }
2840
2841 ATRACE_CALL();
2842
Austin Borger18b30a72022-10-27 12:20:29 -07002843 {
2844 Mutex::Autolock lock(mServiceLock);
2845 mDeviceState = newState;
2846 }
2847
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07002848 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002849
2850 return Status::ok();
2851}
2852
Emilian Peev8b64f282021-03-25 16:49:57 -07002853Status CameraService::notifyDisplayConfigurationChange() {
2854 ATRACE_CALL();
2855 const int callingPid = CameraThreadState::getCallingPid();
2856 const int selfPid = getpid();
2857
2858 // Permission checks
2859 if (callingPid != selfPid) {
2860 // Ensure we're being called by system_server, or similar process with
2861 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07002862 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Emilian Peev8b64f282021-03-25 16:49:57 -07002863 const int uid = CameraThreadState::getCallingUid();
2864 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2865 " changes from pid=%d, uid=%d", callingPid, uid);
2866 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2867 "No permission to send updates to camera service about orientation"
2868 " changes from pid=%d, uid=%d", callingPid, uid);
2869 }
2870 }
2871
2872 Mutex::Autolock lock(mServiceLock);
2873
2874 // Don't do anything if rotate-and-crop override via cmd is active
2875 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2876
2877 const auto clients = mActiveClientManager.getAll();
2878 for (auto& current : clients) {
2879 if (current != nullptr) {
2880 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07002881 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
2882 basicClient->setRotateAndCropOverride(
2883 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2884 basicClient->getPackageName(),
2885 basicClient->getCameraFacing(),
2886 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07002887 }
2888 }
2889 }
2890
2891 return Status::ok();
2892}
2893
2894Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002895 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2896 ATRACE_CALL();
2897 if (!concurrentCameraIds) {
2898 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2899 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2900 }
2901
2902 if (!mInitialized) {
2903 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07002904 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002905 return STATUS_ERROR(ERROR_DISCONNECTED,
2906 "Camera subsystem is not available");
2907 }
2908 // First call into the provider and get the set of concurrent camera
2909 // combinations
2910 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002911 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002912 for (auto &combination : concurrentCameraCombinations) {
2913 std::vector<std::string> validCombination;
2914 for (auto &cameraId : combination) {
2915 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07002916 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002917 if (state == nullptr) {
2918 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2919 continue;
2920 }
2921 StatusInternal status = state->getStatus();
2922 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2923 continue;
2924 }
Austin Borgered99f642023-06-01 16:51:35 -07002925 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002926 continue;
2927 }
2928 validCombination.push_back(cameraId);
2929 }
2930 if (validCombination.size() != 0) {
2931 concurrentCameraIds->push_back(std::move(validCombination));
2932 }
2933 }
2934 return Status::ok();
2935}
2936
2937Status CameraService::isConcurrentSessionConfigurationSupported(
2938 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002939 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002940 if (!isSupported) {
2941 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2942 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2943 }
2944
2945 if (!mInitialized) {
2946 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2947 return STATUS_ERROR(ERROR_DISCONNECTED,
2948 "Camera subsystem is not available");
2949 }
2950
2951 // Check for camera permissions
2952 int callingPid = CameraThreadState::getCallingPid();
2953 int callingUid = CameraThreadState::getCallingUid();
Joanne Chung02c13d02023-01-16 12:58:05 +00002954 permission::PermissionChecker permissionChecker;
2955 AttributionSourceState attributionSource{};
2956 attributionSource.pid = callingPid;
2957 attributionSource.uid = callingUid;
2958 bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -07002959 toString16(sCameraPermission), attributionSource, String16(),
2960 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Joanne Chung02c13d02023-01-16 12:58:05 +00002961 if ((callingPid != getpid()) && !checkPermissionForCamera) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002962 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2963 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2964 "android.permission.CAMERA needed to call"
2965 "isConcurrentSessionConfigurationSupported");
2966 }
2967
2968 status_t res =
2969 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002970 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
2971 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002972 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07002973 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07002974 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002975 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2976 "support %s (%d)", strerror(-res), res);
2977 }
2978 return Status::ok();
2979}
2980
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002981Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2982 /*out*/
2983 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002984 return addListenerHelper(listener, cameraStatuses);
2985}
2986
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002987binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2988 std::vector<hardware::CameraStatus>* cameraStatuses) {
2989 return addListenerHelper(listener, cameraStatuses, false, true);
2990}
2991
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002992Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2993 /*out*/
2994 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002995 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002996
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002997 ATRACE_CALL();
2998
Igor Murashkinbfc99152013-02-27 12:55:20 -08002999 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003000
Ruben Brunk3450ba72015-06-16 11:00:37 -07003001 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003002 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003003 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003004 }
3005
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003006 auto clientUid = CameraThreadState::getCallingUid();
3007 auto clientPid = CameraThreadState::getCallingPid();
Joanne Chung02c13d02023-01-16 12:58:05 +00003008 permission::PermissionChecker permissionChecker;
3009 AttributionSourceState attributionSource{};
3010 attributionSource.uid = clientUid;
3011 attributionSource.pid = clientPid;
3012 bool openCloseCallbackAllowed = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -07003013 toString16(sCameraOpenCloseListenerPermission), attributionSource, String16(),
Joanne Chung02c13d02023-01-16 12:58:05 +00003014 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003015
Igor Murashkinbfc99152013-02-27 12:55:20 -08003016 Mutex::Autolock lock(mServiceLock);
3017
Ruben Brunkcc776712015-02-17 20:18:47 -08003018 {
3019 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003020 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003021 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003022 ALOGW("%s: Tried to add listener %p which was already subscribed",
3023 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003024 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003025 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003026 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003027
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003028 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003029 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3030 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003031 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003032 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003033 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003034 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003035 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3036 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3037 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003038 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003039 // The listener still needs to be added to the list of listeners, regardless of what
3040 // permissions the listener process has / whether it is a vendor listener. Since it might be
3041 // eligible to listen to other camera ids.
3042 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003043 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003044 }
3045
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003046 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003047 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003048 Mutex::Autolock lock(mCameraStatesLock);
3049 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003050 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003051 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Austin Borgered99f642023-06-01 16:51:35 -07003052 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string());
Igor Murashkincba2c162013-03-20 15:56:31 -07003053 }
3054 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003055 // Remove the camera statuses that should be hidden from the client, we do
3056 // this after collecting the states in order to avoid holding
3057 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3058 // the same time.
3059 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3060 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
3061 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3062 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
3063 ALOGE("%s: Invalid camera id %s, skipping status update",
3064 __FUNCTION__, s.cameraId.c_str());
3065 return true;
3066 }
3067 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3068 clientUid);}), cameraStatuses->end());
3069
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003070 //cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003071 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003072 for (const auto &s : *cameraStatuses) {
Austin Borgered99f642023-06-01 16:51:35 -07003073 idsChosenForCallback.insert(s.cameraId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003074 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003075
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003076 /*
3077 * Immediately signal current torch status to this listener only
3078 * This may be a subset of all the devices, so don't include it in the response directly
3079 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003080 {
3081 Mutex::Autolock al(mTorchStatusMutex);
3082 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003083 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003084 // The camera id is visible to the client. Fine to send torch
3085 // callback.
3086 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
3087 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
3088 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003089 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003090 }
3091
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003092 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003093}
Ruben Brunkcc776712015-02-17 20:18:47 -08003094
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003095Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003096 ATRACE_CALL();
3097
Igor Murashkinbfc99152013-02-27 12:55:20 -08003098 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3099
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003100 if (listener == 0) {
3101 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003102 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003103 }
3104
Igor Murashkinbfc99152013-02-27 12:55:20 -08003105 Mutex::Autolock lock(mServiceLock);
3106
Ruben Brunkcc776712015-02-17 20:18:47 -08003107 {
3108 Mutex::Autolock lock(mStatusListenerLock);
3109 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003110 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003111 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003112 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003113 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003114 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003115 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003116 }
3117 }
3118
3119 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3120 __FUNCTION__, listener.get());
3121
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003122 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003123}
3124
Austin Borgered99f642023-06-01 16:51:35 -07003125Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003126
3127 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003128 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3129
3130 if (parameters == NULL) {
3131 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003132 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003133 }
3134
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003135 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003136
3137 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003138 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003139 // Error logged by caller
3140 return ret;
3141 }
3142
3143 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003144
Austin Borgered99f642023-06-01 16:51:35 -07003145 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003146
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003147 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003148}
3149
Austin Borgered99f642023-06-01 16:51:35 -07003150Status CameraService::supportsCameraApi(const std::string& unresolvedCameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003151 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003152 ATRACE_CALL();
3153
malikakashedb38962023-09-06 00:03:35 +00003154 const std::string cameraId = resolveCameraId(
3155 unresolvedCameraId, CameraThreadState::getCallingUid());
malikakash82ed4352023-07-21 22:44:34 +00003156
Austin Borgered99f642023-06-01 16:51:35 -07003157 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003158
3159 switch (apiVersion) {
3160 case API_VERSION_1:
3161 case API_VERSION_2:
3162 break;
3163 default:
Austin Borgered99f642023-06-01 16:51:35 -07003164 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3165 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3166 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003167 }
3168
Austin Borger18b30a72022-10-27 12:20:29 -07003169 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -07003170 auto deviceVersionAndTransport = getDeviceVersion(cameraId, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003171 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003172 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3173 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3174 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003175 }
3176 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3177 int deviceVersion = deviceVersionAndTransport.first;
3178 switch (deviceVersion) {
3179 case CAMERA_DEVICE_API_VERSION_1_0:
3180 case CAMERA_DEVICE_API_VERSION_3_0:
3181 case CAMERA_DEVICE_API_VERSION_3_1:
3182 if (apiVersion == API_VERSION_2) {
3183 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003184 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003185 *isSupported = false;
3186 } else { // if (apiVersion == API_VERSION_1) {
3187 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003188 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003189 *isSupported = true;
3190 }
3191 break;
3192 case CAMERA_DEVICE_API_VERSION_3_2:
3193 case CAMERA_DEVICE_API_VERSION_3_3:
3194 case CAMERA_DEVICE_API_VERSION_3_4:
3195 case CAMERA_DEVICE_API_VERSION_3_5:
3196 case CAMERA_DEVICE_API_VERSION_3_6:
3197 case CAMERA_DEVICE_API_VERSION_3_7:
3198 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003199 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003200 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003201 break;
3202 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003203 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3204 deviceVersion, cameraId.c_str());
3205 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3206 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003207 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003208 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003209 } else {
3210 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003211 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003212 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003213}
3214
Austin Borgered99f642023-06-01 16:51:35 -07003215Status CameraService::isHiddenPhysicalCamera(const std::string& unresolvedCameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003216 /*out*/ bool *isSupported) {
3217 ATRACE_CALL();
3218
malikakashedb38962023-09-06 00:03:35 +00003219 const std::string cameraId = resolveCameraId(unresolvedCameraId,
3220 CameraThreadState::getCallingUid());
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003221
Austin Borgered99f642023-06-01 16:51:35 -07003222 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3223 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003224
3225 return Status::ok();
3226}
3227
Cliff Wud8cae102021-03-11 01:37:42 +08003228Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003229 const std::string& packageName, const std::string& internalCamId,
3230 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003231 const sp<ICameraInjectionCallback>& callback,
3232 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003233 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003234 ATRACE_CALL();
3235
Austin Borgered99f642023-06-01 16:51:35 -07003236 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Cliff Wud8cae102021-03-11 01:37:42 +08003237 const int pid = CameraThreadState::getCallingPid();
3238 const int uid = CameraThreadState::getCallingUid();
3239 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3240 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3241 "Permission Denial: no permission to inject camera");
3242 }
3243
3244 ALOGV(
3245 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3246 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003247 __FUNCTION__, packageName.c_str(),
3248 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003249
Cliff Wud3a05312021-04-26 23:07:31 +08003250 {
3251 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003252 mInjectionInternalCamId = internalCamId;
3253 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003254 mInjectionStatusListener->addListener(callback);
3255 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003256 status_t res = NO_ERROR;
3257 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3258 // If the client already exists, we can directly connect to the camera device through the
3259 // client's injectCamera(), otherwise we need to wait until the client is established
3260 // (execute connectHelper()) before injecting the camera to the camera device.
3261 if (clientDescriptor != nullptr) {
3262 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003263 sp<BasicClient> clientSp = clientDescriptor->getValue();
3264 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3265 if(res != OK) {
3266 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3267 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003268 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003269 }
3270 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08003271 if(res != OK) {
3272 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3273 }
3274 } else {
3275 mInjectionInitPending = true;
3276 }
3277 }
Cliff Wud8cae102021-03-11 01:37:42 +08003278
Cliff Wud3a05312021-04-26 23:07:31 +08003279 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003280}
3281
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003282Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003283 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003284 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3285 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3286 return Status::ok();
3287}
3288
Ruben Brunkcc776712015-02-17 20:18:47 -08003289void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003290 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003291 for (auto& i : mActiveClientManager.getAll()) {
3292 auto clientSp = i->getValue();
3293 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003294 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003295 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003296 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003297 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003298 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003299}
3300
Ruben Brunkcc776712015-02-17 20:18:47 -08003301bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003302 bool ret = false;
3303 {
3304 // Acquire mServiceLock and prevent other clients from connecting
3305 std::unique_ptr<AutoConditionLock> lock =
3306 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003307
Igor Murashkin634a5152013-02-20 17:15:11 -08003308
Ruben Brunkcc776712015-02-17 20:18:47 -08003309 std::vector<sp<BasicClient>> evicted;
3310 for (auto& i : mActiveClientManager.getAll()) {
3311 auto clientSp = i->getValue();
3312 if (clientSp.get() == nullptr) {
3313 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3314 mActiveClientManager.remove(i);
3315 continue;
3316 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003317 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003318 mActiveClientManager.remove(i);
3319 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003320
Ruben Brunkcc776712015-02-17 20:18:47 -08003321 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003322 clientSp->notifyError(
3323 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003324 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003325 }
3326 }
3327
Ruben Brunkcc776712015-02-17 20:18:47 -08003328 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3329 // other clients from connecting in mServiceLockWrapper if held
3330 mServiceLock.unlock();
3331
Ruben Brunk36597b22015-03-20 22:15:57 -07003332 // Do not clear caller identity, remote caller should be client proccess
3333
Ruben Brunkcc776712015-02-17 20:18:47 -08003334 for (auto& i : evicted) {
3335 if (i.get() != nullptr) {
3336 i->disconnect();
3337 ret = true;
3338 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003339 }
3340
Ruben Brunkcc776712015-02-17 20:18:47 -08003341 // Reacquire mServiceLock
3342 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003343
Ruben Brunkcc776712015-02-17 20:18:47 -08003344 } // lock is destroyed, allow further connect calls
3345
3346 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003347}
3348
Ruben Brunkcc776712015-02-17 20:18:47 -08003349std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003350 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003351 std::shared_ptr<CameraState> state;
3352 {
3353 Mutex::Autolock lock(mCameraStatesLock);
3354 auto iter = mCameraStates.find(cameraId);
3355 if (iter != mCameraStates.end()) {
3356 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003357 }
3358 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003359 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003360}
3361
Austin Borgered99f642023-06-01 16:51:35 -07003362sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003363 // Remove from active clients list
3364 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3365 if (clientDescriptorPtr == nullptr) {
3366 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003367 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003368 return sp<BasicClient>{nullptr};
3369 }
3370
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003371 sp<BasicClient> client = clientDescriptorPtr->getValue();
3372 if (client.get() != nullptr) {
3373 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3374 }
3375 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003376}
3377
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003378void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003379 // Acquire mServiceLock and prevent other clients from connecting
3380 std::unique_ptr<AutoConditionLock> lock =
3381 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3382
Ruben Brunk6267b532015-04-30 17:44:07 -07003383 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003384 for (size_t i = 0; i < newUserIds.size(); i++) {
3385 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003386 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003387 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003388 return;
3389 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003390 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003391 }
3392
Ruben Brunka8ca9152015-04-07 14:23:40 -07003393
Ruben Brunk6267b532015-04-30 17:44:07 -07003394 if (newAllowedUsers == mAllowedUsers) {
3395 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3396 return;
3397 }
3398
3399 logUserSwitch(mAllowedUsers, newAllowedUsers);
3400
3401 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003402
3403 // Current user has switched, evict all current clients.
3404 std::vector<sp<BasicClient>> evicted;
3405 for (auto& i : mActiveClientManager.getAll()) {
3406 auto clientSp = i->getValue();
3407
3408 if (clientSp.get() == nullptr) {
3409 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3410 continue;
3411 }
3412
Ruben Brunk6267b532015-04-30 17:44:07 -07003413 // Don't evict clients that are still allowed.
3414 uid_t clientUid = clientSp->getClientUid();
3415 userid_t clientUserId = multiuser_get_user_id(clientUid);
3416 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3417 continue;
3418 }
3419
Ruben Brunk36597b22015-03-20 22:15:57 -07003420 evicted.push_back(clientSp);
3421
Ruben Brunk36597b22015-03-20 22:15:57 -07003422 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003423 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003424
Ruben Brunk36597b22015-03-20 22:15:57 -07003425 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003426 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003427 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003428 " to user switch.", i->getKey().c_str(),
3429 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003430 i->getOwnerId(), i->getPriority().getScore(),
3431 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003432
3433 }
3434
3435 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3436 // blocking other clients from connecting in mServiceLockWrapper if held.
3437 mServiceLock.unlock();
3438
3439 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07003440 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003441
3442 for (auto& i : evicted) {
3443 i->disconnect();
3444 }
3445
Jayant Chowdhary12361932018-08-27 14:46:13 -07003446 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003447
3448 // Reacquire mServiceLock
3449 mServiceLock.lock();
3450}
Ruben Brunkcc776712015-02-17 20:18:47 -08003451
Austin Borgered99f642023-06-01 16:51:35 -07003452void CameraService::logEvent(const std::string &event) {
3453 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003454 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003455 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003456 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003457 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003458 mEventLog.add(msg);
3459 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3460 // Error event not added to the dumpsys log before
3461 mEventLog.add(msg);
3462 sServiceErrorEventSet.insert(msg);
3463 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003464}
3465
Austin Borgered99f642023-06-01 16:51:35 -07003466void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3467 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003468 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003469 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3470 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003471}
3472
Austin Borgered99f642023-06-01 16:51:35 -07003473void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3474 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003475 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003476 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3477 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003478}
3479
Austin Borgered99f642023-06-01 16:51:35 -07003480void CameraService::logConnected(const std::string &cameraId, int clientPid,
3481 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003482 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003483 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3484 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003485}
3486
Austin Borgered99f642023-06-01 16:51:35 -07003487void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3488 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003489 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003490 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3491 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003492}
3493
Austin Borgered99f642023-06-01 16:51:35 -07003494void CameraService::logRejected(const std::string &cameraId, int clientPid,
3495 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003496 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003497 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3498 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003499}
3500
Austin Borgered99f642023-06-01 16:51:35 -07003501void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3502 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003503 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003504 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3505 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003506}
3507
Ruben Brunk6267b532015-04-30 17:44:07 -07003508void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3509 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003510 std::string newUsers = toString(newUserIds);
3511 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003512 if (oldUsers.size() == 0) {
3513 oldUsers = "<None>";
3514 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003515 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003516 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3517 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003518}
3519
Austin Borgered99f642023-06-01 16:51:35 -07003520void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003521 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003522 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003523}
3524
Austin Borgered99f642023-06-01 16:51:35 -07003525void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003526 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003527 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003528}
3529
Austin Borgered99f642023-06-01 16:51:35 -07003530void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003531 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003532 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003533}
3534
Austin Borgered99f642023-06-01 16:51:35 -07003535void CameraService::logServiceError(const std::string &msg, int errorCode) {
3536 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3537 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003538}
3539
Ruben Brunk36597b22015-03-20 22:15:57 -07003540status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3541 uint32_t flags) {
3542
Mathias Agopian65ab4712010-07-14 17:59:35 -07003543 // Permission checks
3544 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003545 case SHELL_COMMAND_TRANSACTION: {
3546 int in = data.readFileDescriptor();
3547 int out = data.readFileDescriptor();
3548 int err = data.readFileDescriptor();
3549 int argc = data.readInt32();
3550 Vector<String16> args;
3551 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3552 args.add(data.readString16());
3553 }
3554 sp<IBinder> unusedCallback;
3555 sp<IResultReceiver> resultReceiver;
3556 status_t status;
3557 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3558 return status;
3559 }
3560 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3561 return status;
3562 }
3563 status = shellCommand(in, out, err, args);
3564 if (resultReceiver != nullptr) {
3565 resultReceiver->send(status);
3566 }
3567 return NO_ERROR;
3568 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003569 }
3570
3571 return BnCameraService::onTransact(code, data, reply, flags);
3572}
3573
Mathias Agopian65ab4712010-07-14 17:59:35 -07003574// We share the media players for shutter and recording sound for all clients.
3575// A reference count is kept to determine when we will actually release the
3576// media players.
3577
Jaekyun Seokef498052018-03-23 13:09:44 +09003578sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3579 sp<MediaPlayer> mp = new MediaPlayer();
3580 status_t error;
3581 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003582 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003583 error = mp->prepare();
3584 }
3585 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003586 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003587 mp->disconnect();
3588 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003589 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003590 }
3591 return mp;
3592}
3593
username5755fea2018-12-27 09:48:08 +08003594void CameraService::increaseSoundRef() {
3595 Mutex::Autolock lock(mSoundLock);
3596 mSoundRef++;
3597}
3598
3599void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003600 ATRACE_CALL();
3601
username5755fea2018-12-27 09:48:08 +08003602 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3603 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3604 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3605 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3606 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3607 }
3608 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3609 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3610 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3611 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003612 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003613 }
3614 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3615 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3616 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3617 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3618 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003619 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003620}
3621
username5755fea2018-12-27 09:48:08 +08003622void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003623 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003624 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003625 if (--mSoundRef) return;
3626
3627 for (int i = 0; i < NUM_SOUNDS; i++) {
3628 if (mSoundPlayer[i] != 0) {
3629 mSoundPlayer[i]->disconnect();
3630 mSoundPlayer[i].clear();
3631 }
3632 }
3633}
3634
3635void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003636 ATRACE_CALL();
3637
Mathias Agopian65ab4712010-07-14 17:59:35 -07003638 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07003639 if (kind < 0 || kind >= NUM_SOUNDS) {
3640 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
3641 return;
3642 }
3643
Mathias Agopian65ab4712010-07-14 17:59:35 -07003644 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003645 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003646 sp<MediaPlayer> player = mSoundPlayer[kind];
3647 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08003648 player->seekTo(0);
3649 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003650 }
3651}
3652
3653// ----------------------------------------------------------------------------
3654
3655CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07003656 const sp<ICameraClient>& cameraClient,
Austin Borgered99f642023-06-01 16:51:35 -07003657 const std::string& clientPackageName, bool systemNativeClient,
3658 const std::optional<std::string>& clientFeatureId,
3659 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003660 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003661 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003662 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003663 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003664 IInterface::asBinder(cameraClient),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003665 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003666 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003667 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003668 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003669 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003670{
Jayant Chowdhary12361932018-08-27 14:46:13 -07003671 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003672 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003673
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003674 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003675
username5755fea2018-12-27 09:48:08 +08003676 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003677
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003678 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003679}
3680
Mathias Agopian65ab4712010-07-14 17:59:35 -07003681// tear down the client
3682CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003683 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08003684 mDestructionStarted = true;
3685
username5755fea2018-12-27 09:48:08 +08003686 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003687 // unconditionally disconnect. function is idempotent
3688 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003689}
3690
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003691sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
3692
Igor Murashkin634a5152013-02-20 17:15:11 -08003693CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003694 const sp<IBinder>& remoteCallback,
Austin Borgered99f642023-06-01 16:51:35 -07003695 const std::string& clientPackageName, bool nativeClient,
3696 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003697 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003698 int servicePid, bool overrideToPortrait):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003699 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07003700 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003701 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
3702 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003703 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003704 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07003705 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07003706 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003707 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003708 mRemoteBinder(remoteCallback),
3709 mOpsActive(false),
3710 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08003711{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003712 if (sCameraService == nullptr) {
3713 sCameraService = cameraService;
3714 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08003715
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003716 // There are 2 scenarios in which a client won't have AppOps operations
3717 // (both scenarios : native clients)
3718 // 1) It's an system native client*, the package name will be empty
3719 // and it will return from this function in the previous if condition
3720 // (This is the same as the previously existing behavior).
3721 // 2) It is a system native client, but its package name has been
3722 // modified for debugging, however it still must not use AppOps since
3723 // the package name is not a real one.
3724 //
3725 // * system native client - native client with UID < AID_APP_START. It
3726 // doesn't exclude clients not on the system partition.
3727 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003728 mAppOpsManager = std::make_unique<AppOpsManager>();
3729 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07003730
3731 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08003732}
3733
3734CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003735 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08003736 mDestructionStarted = true;
3737}
3738
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003739binder::Status CameraService::BasicClient::disconnect() {
3740 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003741 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003742 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07003743 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07003744 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08003745
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003746 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07003747 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07003748 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07003749 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08003750
3751 sp<IBinder> remote = getRemote();
3752 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003753 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08003754 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003755
3756 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07003757 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003758 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07003759 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003760 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003761
Igor Murashkincba2c162013-03-20 15:56:31 -07003762 // client shouldn't be able to call into us anymore
3763 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003764
Kunal Malhotrabfc96052023-02-28 23:25:34 +00003765 const auto& mActivityManager = getActivityManager();
3766 if (mActivityManager) {
3767 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
3768 CameraThreadState::getCallingUid(),
3769 CameraThreadState::getCallingPid());
3770 }
3771
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003772 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08003773}
3774
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003775status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
3776 // No dumping of clients directly over Binder,
3777 // must go through CameraService::dump
3778 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003779 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003780 return OK;
3781}
3782
Austin Borgered99f642023-06-01 16:51:35 -07003783status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07003784 // Can't watch tags directly, must go through CameraService::startWatchingTags
3785 return OK;
3786}
3787
3788status_t CameraService::BasicClient::stopWatchingTags(int) {
3789 // Can't watch tags directly, must go through CameraService::stopWatchingTags
3790 return OK;
3791}
3792
3793status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
3794 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
3795 return OK;
3796}
3797
Austin Borgered99f642023-06-01 16:51:35 -07003798std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003799 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08003800}
3801
Emilian Peev8b64f282021-03-25 16:49:57 -07003802int CameraService::BasicClient::getCameraFacing() const {
3803 return mCameraFacing;
3804}
3805
3806int CameraService::BasicClient::getCameraOrientation() const {
3807 return mOrientation;
3808}
Ruben Brunkcc776712015-02-17 20:18:47 -08003809
3810int CameraService::BasicClient::getClientPid() const {
3811 return mClientPid;
3812}
3813
Ruben Brunk6267b532015-04-30 17:44:07 -07003814uid_t CameraService::BasicClient::getClientUid() const {
3815 return mClientUid;
3816}
3817
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003818bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
3819 // Defaults to API2.
3820 return level == API_2;
3821}
3822
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003823status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003824 {
3825 Mutex::Autolock l(mAudioRestrictionLock);
3826 mAudioRestriction = mode;
3827 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003828 sCameraService->updateAudioRestriction();
3829 return OK;
3830}
3831
3832int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003833 return sCameraService->updateAudioRestriction();
3834}
3835
3836int32_t CameraService::BasicClient::getAudioRestriction() const {
3837 Mutex::Autolock l(mAudioRestrictionLock);
3838 return mAudioRestriction;
3839}
3840
3841bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
3842 switch (mode) {
3843 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
3844 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
3845 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
3846 return true;
3847 default:
3848 return false;
3849 }
3850}
3851
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003852status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
3853 if (mode == AppOpsManager::MODE_ERRORED) {
3854 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07003855 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003856 return PERMISSION_DENIED;
3857 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
3858 // If the calling Uid is trusted (a native service), the AppOpsManager could
3859 // return MODE_IGNORED. Do not treat such case as error.
3860 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
3861 mClientPackageName);
3862 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08003863 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayana8143e572023-01-09 08:46:49 -08003864 // We don't want to return EACCESS if the CameraPrivacy is enabled.
3865 // We prefer to successfully open the camera and perform camera muting
3866 // or blocking in connectHelper as handleAppOpMode can be called before the
3867 // connection has been fully established and at that time camera muting
3868 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003869 if (!isUidActive || !isCameraPrivacyEnabled) {
3870 ALOGI("Camera %s: Access for \"%s\" has been restricted",
Austin Borgered99f642023-06-01 16:51:35 -07003871 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003872 // Return the same error as for device policy manager rejection
3873 return -EACCES;
3874 }
3875 }
3876 return OK;
3877}
3878
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003879status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003880 ATRACE_CALL();
3881
Igor Murashkine6800ce2013-03-04 17:25:57 -08003882 {
3883 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07003884 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003885 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003886 if (mAppOpsManager != nullptr) {
3887 // Notify app ops that the camera is not available
3888 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003889 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07003890 toString16(mClientPackageName), mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003891
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003892 // Just check for camera acccess here on open - delay startOp until
3893 // camera frames start streaming in startCameraStreamingOps
3894 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07003895 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003896 status_t res = handleAppOpMode(mode);
3897 if (res != OK) {
3898 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003899 }
Svetoslav28e8ef72015-05-11 19:21:31 -07003900 }
3901
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003902 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003903
3904 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003905 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003906
Austin Borgerdddb7552023-03-30 17:53:01 -07003907 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08003908
Shuzhen Wang695044d2020-03-06 09:02:23 -08003909 // Notify listeners of camera open/close status
3910 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
3911
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003912 return OK;
3913}
3914
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003915status_t CameraService::BasicClient::startCameraStreamingOps() {
3916 ATRACE_CALL();
3917
3918 if (!mOpsActive) {
3919 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3920 return INVALID_OPERATION;
3921 }
3922 if (mOpsStreaming) {
3923 ALOGV("%s: Streaming already active!", __FUNCTION__);
3924 return OK;
3925 }
3926
3927 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07003928 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003929
3930 if (mAppOpsManager != nullptr) {
3931 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07003932 toString16(mClientPackageName), /*startIfModeDefault*/ false,
3933 toString16(mClientFeatureId),
3934 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003935 status_t res = handleAppOpMode(mode);
3936 if (res != OK) {
3937 return res;
3938 }
3939 }
3940
3941 mOpsStreaming = true;
3942
3943 return OK;
3944}
3945
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003946status_t CameraService::BasicClient::noteAppOp() {
3947 ATRACE_CALL();
3948
3949 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07003950 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003951
3952 // noteAppOp is only used for when camera mute is not supported, in order
3953 // to trigger the sensor privacy "Unblock" dialog
3954 if (mAppOpsManager != nullptr) {
3955 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07003956 toString16(mClientPackageName), toString16(mClientFeatureId),
3957 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003958 status_t res = handleAppOpMode(mode);
3959 if (res != OK) {
3960 return res;
3961 }
3962 }
3963
3964 return OK;
3965}
3966
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003967status_t CameraService::BasicClient::finishCameraStreamingOps() {
3968 ATRACE_CALL();
3969
3970 if (!mOpsActive) {
3971 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3972 return INVALID_OPERATION;
3973 }
3974 if (!mOpsStreaming) {
3975 ALOGV("%s: Streaming not active!", __FUNCTION__);
3976 return OK;
3977 }
3978
3979 if (mAppOpsManager != nullptr) {
3980 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07003981 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003982 mOpsStreaming = false;
3983 }
3984
3985 return OK;
3986}
3987
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003988status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003989 ATRACE_CALL();
3990
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003991 if (mOpsStreaming) {
3992 // Make sure we've notified everyone about camera stopping
3993 finishCameraStreamingOps();
3994 }
3995
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003996 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003997 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003998 mOpsActive = false;
3999
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004000 // This function is called when a client disconnects. This should
4001 // release the camera, but actually only if it was in a proper
4002 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004003 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004004 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004005
Ruben Brunkcc776712015-02-17 20:18:47 -08004006 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004007 sCameraService->updateStatus(StatusInternal::PRESENT,
4008 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004009 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004010 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004011 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4012 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004013 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004014 mOpsCallback.clear();
4015
Austin Borgerdddb7552023-03-30 17:53:01 -07004016 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004017
Shuzhen Wang695044d2020-03-06 09:02:23 -08004018 // Notify listeners of camera open/close status
4019 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4020
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004021 return OK;
4022}
4023
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004024void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004025 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004026 if (mAppOpsManager == nullptr) {
4027 return;
4028 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004029 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004030 if (op != AppOpsManager::OP_CAMERA) {
4031 ALOGW("Unexpected app ops notification received: %d", op);
4032 return;
4033 }
4034
4035 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004036 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004037 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004038 ALOGV("checkOp returns: %d, %s ", res,
4039 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4040 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4041 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4042 "UNKNOWN");
4043
Shuzhen Wang64900852021-02-05 09:03:29 -08004044 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004045 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4046 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004047 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004048 } else if (res == AppOpsManager::MODE_IGNORED) {
4049 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08004050 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004051 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Shuzhen Wang64900852021-02-05 09:03:29 -08004052 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
Austin Borgered99f642023-06-01 16:51:35 -07004053 mCameraIdStr.c_str(), mClientPackageName.c_str(),
Shuzhen Wang64900852021-02-05 09:03:29 -08004054 mUidIsTrusted, isUidActive);
4055 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
4056 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
4057 // error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004058 if (!mUidIsTrusted) {
4059 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4060 setCameraMute(true);
4061 } else if (!isUidActive
4062 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4063 block();
4064 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004065 }
Evan Severson09ab4002021-02-10 14:15:19 -08004066 } else if (res == AppOpsManager::MODE_ALLOWED) {
4067 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004068 }
4069}
4070
Svet Ganova453d0d2018-01-11 15:37:58 -08004071void CameraService::BasicClient::block() {
4072 ATRACE_CALL();
4073
4074 // Reset the client PID to allow server-initiated disconnect,
4075 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004076 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004077 CaptureResultExtras resultExtras; // a dummy result (invalid)
4078 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4079 disconnect();
4080}
4081
Mathias Agopian65ab4712010-07-14 17:59:35 -07004082// ----------------------------------------------------------------------------
4083
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004084void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004085 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004086 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004087 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4088 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4089 api1ErrorCode = CAMERA_ERROR_DISABLED;
4090 }
4091 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004092 } else {
4093 ALOGE("mRemoteCallback is NULL!!");
4094 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004095}
4096
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004097// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004098binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004099 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004100 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004101}
4102
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004103bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4104 return level == API_1;
4105}
4106
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004107CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4108 mClient(client) {
4109}
4110
4111void CameraService::Client::OpsCallback::opChanged(int32_t op,
4112 const String16& packageName) {
4113 sp<BasicClient> client = mClient.promote();
4114 if (client != NULL) {
4115 client->opChanged(op, packageName);
4116 }
4117}
4118
Mathias Agopian65ab4712010-07-14 17:59:35 -07004119// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004120// UidPolicy
4121// ----------------------------------------------------------------------------
4122
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004123void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004124 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004125 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004126
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004127 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004128 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004129 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004130 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004131 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4132 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004133 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004134 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004135 if (res == OK) {
4136 mRegistered = true;
4137 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004138 } else {
4139 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004140 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004141}
4142
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004143void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004144 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004145 return;
4146 }
4147
4148 registerWithActivityManager();
4149}
4150
4151void CameraService::UidPolicy::registerSelf() {
4152 // Use check service to see if the activity service is available
4153 // If not available then register for notifications, instead of blocking
4154 // till the service is ready
4155 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004156 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004157 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004158 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004159 } else {
4160 registerWithActivityManager();
4161 }
4162}
4163
Svet Ganova453d0d2018-01-11 15:37:58 -08004164void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004165 Mutex::Autolock _l(mUidLock);
4166
Steven Moreland2f348142019-07-02 15:59:07 -07004167 mAm.unregisterUidObserver(this);
4168 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004169 mRegistered = false;
4170 mActiveUids.clear();
4171 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004172}
4173
4174void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4175 onUidIdle(uid, disabled);
4176}
4177
4178void CameraService::UidPolicy::onUidActive(uid_t uid) {
4179 Mutex::Autolock _l(mUidLock);
4180 mActiveUids.insert(uid);
4181}
4182
4183void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4184 bool deleted = false;
4185 {
4186 Mutex::Autolock _l(mUidLock);
4187 if (mActiveUids.erase(uid) > 0) {
4188 deleted = true;
4189 }
4190 }
4191 if (deleted) {
4192 sp<CameraService> service = mService.promote();
4193 if (service != nullptr) {
4194 service->blockClientsForUid(uid);
4195 }
4196 }
4197}
4198
Emilian Peev53722fa2019-02-22 17:47:20 -08004199void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004200 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004201 bool procStateChange = false;
4202 {
4203 Mutex::Autolock _l(mUidLock);
4204 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4205 mMonitoredUids[uid].procState != procState) {
4206 mMonitoredUids[uid].procState = procState;
4207 procStateChange = true;
4208 }
4209 }
4210
4211 if (procStateChange) {
4212 sp<CameraService> service = mService.promote();
4213 if (service != nullptr) {
4214 service->notifyMonitoredUids();
4215 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004216 }
4217}
4218
Austin Borgerdddb7552023-03-30 17:53:01 -07004219/**
4220 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4221 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4222 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4223 * monitoredUids. If it is revised above some other monitoredUid, signal
4224 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4225 * foreground apps in split screen - state changes will capture all other cases.
4226 */
4227void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4228 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004229 {
4230 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004231 auto it = mMonitoredUids.find(uid);
4232
4233 if (it != mMonitoredUids.end()) {
4234 if (it->second.hasCamera) {
4235 for (auto &monitoredUid : mMonitoredUids) {
4236 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004237 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004238 notifyUidSet.emplace(monitoredUid.first);
4239 }
4240 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004241 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004242 notifyUidSet.emplace(uid);
4243 } else {
4244 for (auto &monitoredUid : mMonitoredUids) {
4245 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004246 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004247 notifyUidSet.emplace(uid);
4248 }
4249 }
4250 }
4251 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004252 }
4253 }
4254
Austin Borgerdddb7552023-03-30 17:53:01 -07004255 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004256 sp<CameraService> service = mService.promote();
4257 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004258 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004259 }
4260 }
4261}
4262
Austin Borgerdddb7552023-03-30 17:53:01 -07004263/**
4264 * Register a uid for monitoring, and note whether it owns a camera.
4265 */
4266void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004267 Mutex::Autolock _l(mUidLock);
4268 auto it = mMonitoredUids.find(uid);
4269 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004270 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004271 } else {
Austin Borger65577682022-02-17 00:25:43 +00004272 MonitoredUid monitoredUid;
4273 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004274 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004275 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004276 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004277 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004278 if (res != OK) {
4279 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4280 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004281 }
4282
4283 if (openCamera) {
4284 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004285 }
4286}
4287
Austin Borgerdddb7552023-03-30 17:53:01 -07004288/**
4289 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4290 */
4291void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004292 Mutex::Autolock _l(mUidLock);
4293 auto it = mMonitoredUids.find(uid);
4294 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004295 it->second.refCount--;
4296 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004297 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004298 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004299 if (res != OK) {
4300 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4301 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004302 } else if (closeCamera) {
4303 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004304 }
4305 } else {
4306 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4307 }
4308}
4309
Austin Borgered99f642023-06-01 16:51:35 -07004310bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004311 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004312 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004313}
4314
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004315static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4316static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004317
Austin Borgered99f642023-06-01 16:51:35 -07004318bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004319 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004320 // If activity manager is unreachable, assume everything is active
4321 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004322 return true;
4323 }
4324 auto it = mOverrideUids.find(uid);
4325 if (it != mOverrideUids.end()) {
4326 return it->second;
4327 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004328 bool active = mActiveUids.find(uid) != mActiveUids.end();
4329 if (!active) {
4330 // We want active UIDs to always access camera with their first attempt since
4331 // there is no guarantee the app is robustly written and would retry getting
4332 // the camera on failure. The inverse case is not a problem as we would take
4333 // camera away soon once we get the callback that the uid is no longer active.
4334 ActivityManager am;
4335 // Okay to access with a lock held as UID changes are dispatched without
4336 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004337 int64_t startTimeMillis = 0;
4338 do {
4339 // TODO: Fix this b/109950150!
4340 // Okay this is a hack. There is a race between the UID turning active and
4341 // activity being resumed. The proper fix is very risky, so we temporary add
4342 // some polling which should happen pretty rarely anyway as the race is hard
4343 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004344 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004345 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004346 if (active) {
4347 break;
4348 }
4349 if (startTimeMillis <= 0) {
4350 startTimeMillis = uptimeMillis();
4351 }
4352 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004353 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004354 if (remainingTimeMillis <= 0) {
4355 break;
4356 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004357 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4358
4359 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004360 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004361 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004362 } while (true);
4363
Svet Ganov7b4ab782018-03-25 12:48:10 -07004364 if (active) {
4365 // Now that we found out the UID is actually active, cache that
4366 mActiveUids.insert(uid);
4367 }
4368 }
4369 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004370}
4371
Varun Shahb42f1eb2019-04-16 14:45:13 -07004372int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4373 Mutex::Autolock _l(mUidLock);
4374 return getProcStateLocked(uid);
4375}
4376
4377int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4378 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4379 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004380 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004381 }
4382 return procState;
4383}
4384
Austin Borgered99f642023-06-01 16:51:35 -07004385void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4386 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004387 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004388}
4389
Austin Borgered99f642023-06-01 16:51:35 -07004390void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004391 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004392}
4393
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004394void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4395 Mutex::Autolock _l(mUidLock);
4396 ALOGV("UidPolicy: ActivityManager has died");
4397 mRegistered = false;
4398 mActiveUids.clear();
4399}
4400
Austin Borgered99f642023-06-01 16:51:35 -07004401void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004402 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004403 bool wasActive = false;
4404 bool isActive = false;
4405 {
4406 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004407 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004408 mOverrideUids.erase(uid);
4409 if (insert) {
4410 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4411 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004412 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004413 }
4414 if (wasActive != isActive && !isActive) {
4415 sp<CameraService> service = mService.promote();
4416 if (service != nullptr) {
4417 service->blockClientsForUid(uid);
4418 }
4419 }
4420}
4421
4422// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004423// SensorPrivacyPolicy
4424// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004425
4426void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4427{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004428 Mutex::Autolock _l(mSensorPrivacyLock);
4429 if (mRegistered) {
4430 return;
4431 }
Evan Severson09ab4002021-02-10 14:15:19 -08004432 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004433 mSpm.addSensorPrivacyListener(this);
4434 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
4435 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004436 if (res == OK) {
4437 mRegistered = true;
4438 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4439 }
4440}
4441
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004442void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4443 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004444 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004445 return;
4446 }
4447
4448 registerWithSensorPrivacyManager();
4449}
4450
4451void CameraService::SensorPrivacyPolicy::registerSelf() {
4452 // Use checkservice to see if the sensor_privacy service is available
4453 // If service is not available then register for notification
4454 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004455 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004456 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004457 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004458 } else {
4459 registerWithSensorPrivacyManager();
4460 }
4461}
4462
Michael Grooverd1d435a2018-12-18 17:39:42 -08004463void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4464 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004465 mSpm.removeSensorPrivacyListener(this);
4466 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004467 mRegistered = false;
4468 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4469}
4470
4471bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004472 if (!mRegistered) {
4473 registerWithSensorPrivacyManager();
4474 }
4475
Michael Grooverd1d435a2018-12-18 17:39:42 -08004476 Mutex::Autolock _l(mSensorPrivacyLock);
4477 return mSensorPrivacyEnabled;
4478}
4479
Evan Seversond0b69922022-01-27 10:47:34 -08004480bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004481 if (!hasCameraPrivacyFeature()) {
4482 return false;
4483 }
Evan Seversond0b69922022-01-27 10:47:34 -08004484 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004485}
4486
Evan Seversond0b69922022-01-27 10:47:34 -08004487binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
4488 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08004489 {
4490 Mutex::Autolock _l(mSensorPrivacyLock);
Kwangkyu Parke3af2992022-11-05 02:46:52 +09004491 mSensorPrivacyEnabled = enabled;
Michael Grooverd1d435a2018-12-18 17:39:42 -08004492 }
4493 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08004494 if (enabled) {
4495 sp<CameraService> service = mService.promote();
4496 if (service != nullptr) {
4497 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004498 }
4499 }
4500 return binder::Status::ok();
4501}
4502
4503void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4504 Mutex::Autolock _l(mSensorPrivacyLock);
4505 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
4506 mRegistered = false;
4507}
4508
Evan Severson09ab4002021-02-10 14:15:19 -08004509bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08004510 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
4511 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4512 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
4513 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4514 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08004515}
4516
Michael Grooverd1d435a2018-12-18 17:39:42 -08004517// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004518// CameraState
4519// ----------------------------------------------------------------------------
4520
Austin Borgered99f642023-06-01 16:51:35 -07004521CameraService::CameraState::CameraState(const std::string& id, int cost,
4522 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004523 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004524 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004525 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08004526
4527CameraService::CameraState::~CameraState() {}
4528
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004529CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004530 Mutex::Autolock lock(mStatusLock);
4531 return mStatus;
4532}
4533
Austin Borgered99f642023-06-01 16:51:35 -07004534std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08004535 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07004536 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08004537 return res;
4538}
4539
Ruben Brunkcc776712015-02-17 20:18:47 -08004540CameraParameters CameraService::CameraState::getShimParams() const {
4541 return mShimParams;
4542}
4543
4544void CameraService::CameraState::setShimParams(const CameraParameters& params) {
4545 mShimParams = params;
4546}
4547
4548int CameraService::CameraState::getCost() const {
4549 return mCost;
4550}
4551
Austin Borgered99f642023-06-01 16:51:35 -07004552std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004553 return mConflicting;
4554}
4555
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004556SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
4557 return mSystemCameraKind;
4558}
4559
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004560bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
4561 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
4562 != mPhysicalCameras.end();
4563}
4564
Austin Borgered99f642023-06-01 16:51:35 -07004565bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004566 Mutex::Autolock lock(mStatusLock);
4567 auto result = mUnavailablePhysicalIds.insert(physicalId);
4568 return result.second;
4569}
4570
Austin Borgered99f642023-06-01 16:51:35 -07004571bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004572 Mutex::Autolock lock(mStatusLock);
4573 auto count = mUnavailablePhysicalIds.erase(physicalId);
4574 return count > 0;
4575}
4576
Austin Borgered99f642023-06-01 16:51:35 -07004577void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004578 Mutex::Autolock lock(mStatusLock);
4579 mClientPackage = clientPackage;
4580}
4581
Austin Borgered99f642023-06-01 16:51:35 -07004582std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004583 Mutex::Autolock lock(mStatusLock);
4584 return mClientPackage;
4585}
4586
Ruben Brunkcc776712015-02-17 20:18:47 -08004587// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07004588// ClientEventListener
4589// ----------------------------------------------------------------------------
4590
4591void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07004592 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07004593 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004594 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004595 if (basicClient.get() != nullptr) {
4596 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07004597 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07004598 static_cast<int>(basicClient->getClientUid()));
4599 }
4600}
4601
4602void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07004603 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07004604 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004605 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004606 if (basicClient.get() != nullptr) {
4607 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07004608 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07004609 static_cast<int>(basicClient->getClientUid()));
4610 }
4611}
4612
4613
4614// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004615// CameraClientManager
4616// ----------------------------------------------------------------------------
4617
Ruben Brunk99e69712015-05-26 17:25:07 -07004618CameraService::CameraClientManager::CameraClientManager() {
4619 setListener(std::make_shared<ClientEventListener>());
4620}
4621
Ruben Brunkcc776712015-02-17 20:18:47 -08004622CameraService::CameraClientManager::~CameraClientManager() {}
4623
4624sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07004625 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004626 auto descriptor = get(id);
4627 if (descriptor == nullptr) {
4628 return sp<BasicClient>{nullptr};
4629 }
4630 return descriptor->getValue();
4631}
4632
Austin Borgered99f642023-06-01 16:51:35 -07004633std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004634 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07004635 std::ostringstream ret;
4636 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08004637 bool hasAny = false;
4638 for (auto& i : all) {
4639 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07004640 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08004641 int32_t cost = i->getCost();
4642 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00004643 int32_t score = i->getPriority().getScore();
4644 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08004645 auto conflicting = i->getConflicting();
4646 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07004647 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07004648 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08004649 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07004650 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07004651 uid_t clientUid = clientSp->getClientUid();
4652 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004653 }
Austin Borgered99f642023-06-01 16:51:35 -07004654 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
4655 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08004656
Ruben Brunk6267b532015-04-30 17:44:07 -07004657 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07004658 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07004659 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004660 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07004661 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08004662 }
4663
Austin Borgered99f642023-06-01 16:51:35 -07004664 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08004665 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07004666 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08004667 }
Austin Borgered99f642023-06-01 16:51:35 -07004668 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08004669 }
Austin Borgered99f642023-06-01 16:51:35 -07004670 if (hasAny) ret << "\n";
4671 ret << "]\n";
4672 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08004673}
4674
4675CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07004676 const std::string& key, const sp<BasicClient>& value, int32_t cost,
4677 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004678 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004679
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004680 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07004681 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07004682
Austin Borgered99f642023-06-01 16:51:35 -07004683 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004684 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
4685 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08004686}
4687
4688CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004689 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004690 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004691 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00004692 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004693 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
4694 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08004695}
4696
4697// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08004698// InjectionStatusListener
4699// ----------------------------------------------------------------------------
4700
4701void CameraService::InjectionStatusListener::addListener(
4702 const sp<ICameraInjectionCallback>& callback) {
4703 Mutex::Autolock lock(mListenerLock);
4704 if (mCameraInjectionCallback) return;
4705 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
4706 if (res == OK) {
4707 mCameraInjectionCallback = callback;
4708 }
4709}
4710
4711void CameraService::InjectionStatusListener::removeListener() {
4712 Mutex::Autolock lock(mListenerLock);
4713 if (mCameraInjectionCallback == nullptr) {
4714 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4715 return;
4716 }
4717 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
4718 mCameraInjectionCallback = nullptr;
4719}
4720
4721void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07004722 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08004723 if (mCameraInjectionCallback == nullptr) {
4724 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4725 return;
4726 }
Cliff Wud3a05312021-04-26 23:07:31 +08004727
4728 switch (err) {
4729 case -ENODEV:
4730 mCameraInjectionCallback->onInjectionError(
4731 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4732 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07004733 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004734 break;
4735 case -EBUSY:
4736 mCameraInjectionCallback->onInjectionError(
4737 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4738 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07004739 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004740 break;
4741 case DEAD_OBJECT:
4742 mCameraInjectionCallback->onInjectionError(
4743 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4744 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07004745 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004746 break;
4747 case INVALID_OPERATION:
4748 mCameraInjectionCallback->onInjectionError(
4749 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4750 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07004751 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004752 break;
4753 case UNKNOWN_TRANSACTION:
4754 mCameraInjectionCallback->onInjectionError(
4755 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
4756 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07004757 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004758 break;
4759 default:
4760 mCameraInjectionCallback->onInjectionError(
4761 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
4762 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07004763 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004764 }
Cliff Wud8cae102021-03-11 01:37:42 +08004765}
4766
4767void CameraService::InjectionStatusListener::binderDied(
4768 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08004769 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
4770 auto parent = mParent.promote();
4771 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08004772 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4773 if (clientDescriptor != nullptr) {
4774 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4775 baseClientPtr->stopInjection();
4776 }
Cliff Wu3b268182021-07-06 15:44:43 +08004777 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004778 }
4779}
4780
4781// ----------------------------------------------------------------------------
4782// CameraInjectionSession
4783// ----------------------------------------------------------------------------
4784
4785binder::Status CameraService::CameraInjectionSession::stopInjection() {
4786 Mutex::Autolock lock(mInjectionSessionLock);
4787 auto parent = mParent.promote();
4788 if (parent == nullptr) {
4789 ALOGE("CameraInjectionSession: Parent is gone");
4790 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
4791 "Camera service encountered error");
4792 }
Cliff Wud3a05312021-04-26 23:07:31 +08004793
4794 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08004795 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4796 if (clientDescriptor != nullptr) {
4797 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4798 res = baseClientPtr->stopInjection();
4799 if (res != OK) {
4800 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
4801 " ret != NO_ERROR: %d", res);
4802 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
4803 "Camera session encountered error");
4804 }
4805 }
Cliff Wu3b268182021-07-06 15:44:43 +08004806 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004807 return binder::Status::ok();
4808}
4809
4810// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07004811
4812static const int kDumpLockRetries = 50;
4813static const int kDumpLockSleep = 60000;
4814
4815static bool tryLock(Mutex& mutex)
4816{
4817 bool locked = false;
4818 for (int i = 0; i < kDumpLockRetries; ++i) {
4819 if (mutex.tryLock() == NO_ERROR) {
4820 locked = true;
4821 break;
4822 }
4823 usleep(kDumpLockSleep);
4824 }
4825 return locked;
4826}
4827
Rucha Katakwardf223072021-06-15 10:21:00 -07004828void CameraService::cacheDump() {
4829 if (mMemFd != -1) {
4830 const Vector<String16> args;
4831 ATRACE_CALL();
4832 // Acquiring service lock here will avoid the deadlock since
4833 // cacheDump will not be called during the second disconnect.
4834 Mutex::Autolock lock(mServiceLock);
4835
4836 Mutex::Autolock l(mCameraStatesLock);
4837 // Start collecting the info for open sessions and store it in temp file.
4838 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07004839 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07004840 auto clientDescriptor = mActiveClientManager.get(cameraId);
4841 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07004842 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07004843 // Log the current open session info before device is disconnected.
4844 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
4845 }
4846 }
4847 }
4848}
4849
Mathias Agopian65ab4712010-07-14 17:59:35 -07004850status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004851 ATRACE_CALL();
4852
Austin Borgered99f642023-06-01 16:51:35 -07004853 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004854 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004855 CameraThreadState::getCallingPid(),
4856 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004857 return NO_ERROR;
4858 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004859 bool locked = tryLock(mServiceLock);
4860 // failed to lock - CameraService is probably deadlocked
4861 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004862 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004863 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004864
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004865 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004866 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07004867
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004868 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004869 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08004870
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004871 if (locked) mServiceLock.unlock();
4872 return NO_ERROR;
4873 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004874 dprintf(fd, "\n== Service global info: ==\n\n");
4875 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004876 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07004877 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
4878 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004879 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
4880 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
4881 }
Austin Borgered99f642023-06-01 16:51:35 -07004882 std::string activeClientString = mActiveClientManager.toString();
4883 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
4884 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08004885 if (mStreamUseCaseOverrides.size() > 0) {
4886 dprintf(fd, "Active stream use case overrides:");
4887 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
4888 dprintf(fd, " %" PRId64, useCaseOverride);
4889 }
4890 dprintf(fd, "\n");
4891 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004892
4893 dumpEventLog(fd);
4894
4895 bool stateLocked = tryLock(mCameraStatesLock);
4896 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004897 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004898 }
4899
Emilian Peevbd8c5032018-02-14 23:05:40 +00004900 int argSize = args.size();
4901 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07004902 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00004903 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07004904 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00004905 }
4906 break;
4907 }
4908 }
4909
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004910 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07004911 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004912
Austin Borgered99f642023-06-01 16:51:35 -07004913 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004914
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004915 CameraParameters p = state.second->getShimParams();
4916 if (!p.isEmpty()) {
4917 dprintf(fd, " Camera1 API shim is using parameters:\n ");
4918 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004919 }
4920
4921 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004922 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004923 // log the current open session info
4924 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004925 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07004926 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004927 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004928
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004929 }
4930
4931 if (stateLocked) mCameraStatesLock.unlock();
4932
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004933 if (locked) mServiceLock.unlock();
4934
Emilian Peevf53f66e2017-04-11 14:29:43 +01004935 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004936
4937 dprintf(fd, "\n== Vendor tags: ==\n\n");
4938
4939 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
4940 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00004941 sp<VendorTagDescriptorCache> cache =
4942 VendorTagDescriptorCache::getGlobalVendorTagCache();
4943 if (cache == NULL) {
4944 dprintf(fd, "No vendor tags.\n");
4945 } else {
4946 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
4947 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004948 } else {
4949 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
4950 }
4951
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004952 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004953 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004954 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004955
4956 // Process dump arguments, if any
4957 int n = args.size();
4958 String16 verboseOption("-v");
4959 String16 unreachableOption("--unreachable");
4960 for (int i = 0; i < n; i++) {
4961 if (args[i] == verboseOption) {
4962 // change logging level
4963 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07004964 std::string levelStr = toStdString(args[i+1]);
4965 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004966 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004967 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004968 } else if (args[i] == unreachableOption) {
4969 // Dump memory analysis
4970 // TODO - should limit be an argument parameter?
4971 UnreachableMemoryInfo info;
4972 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
4973 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004974 dprintf(fd, "\n== Unable to dump unreachable memory. "
4975 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004976 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004977 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004978 std::string s = info.ToString(/*log_contents*/ true);
4979 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004980 }
4981 }
4982 }
Rucha Katakwardf223072021-06-15 10:21:00 -07004983
4984 bool serviceLocked = tryLock(mServiceLock);
4985
4986 // Dump info from previous open sessions.
4987 // Reposition the offset to beginning of the file before reading
4988
4989 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
4990 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
4991 ssize_t size_read;
4992 char buf[4096];
4993 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
4994 // Read data from file to a small buffer and write it to fd.
4995 write(fd, buf, size_read);
4996 if (size_read == -1) {
4997 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4998 break;
4999 }
5000 }
5001 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5002 } else {
5003 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5004 }
5005
5006 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005007 return NO_ERROR;
5008}
5009
Rucha Katakwardf223072021-06-15 10:21:00 -07005010void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005011 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005012 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005013 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005014 getFormattedCurrentTime().c_str(),
5015 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005016 dprintf(fd, " Client priority score: %d state: %d\n",
5017 clientDescriptor->getPriority().getScore(),
5018 clientDescriptor->getPriority().getState());
5019 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5020
5021 auto client = clientDescriptor->getValue();
5022 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005023 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005024
5025 client->dumpClient(fd, args);
5026}
5027
Austin Borgered99f642023-06-01 16:51:35 -07005028void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005029 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005030 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005031}
5032
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005033void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005034 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005035
5036 Mutex::Autolock l(mLogLock);
5037 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005038 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005039 }
5040
5041 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005042 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005043 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005044 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005045 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005046 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005047}
5048
Austin Borgered99f642023-06-01 16:51:35 -07005049void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005050 Mutex::Autolock lock(mLogLock);
5051 if (!isClientWatchedLocked(client)) { return; }
5052
5053 std::vector<std::string> dumpVector;
5054 client->dumpWatchedEventsToVector(dumpVector);
5055
5056 if (dumpVector.empty()) { return; }
5057
Austin Borgered99f642023-06-01 16:51:35 -07005058 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005059
Austin Borgered99f642023-06-01 16:51:35 -07005060 std::string currentTime = getFormattedCurrentTime();
5061 dumpString << "Cached @ ";
5062 dumpString << currentTime;
5063 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005064
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005065 size_t i = dumpVector.size();
5066
5067 // Store the string in reverse order (latest last)
5068 while (i > 0) {
5069 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005070 dumpString << cameraId;
5071 dumpString << ":";
5072 dumpString << client->getPackageName();
5073 dumpString << " ";
5074 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005075 }
5076
Austin Borgered99f642023-06-01 16:51:35 -07005077 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005078}
5079
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005080void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005081 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005082 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5083 if (mTorchClientMap[i] == who) {
5084 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005085 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005086 status_t res = mFlashlight->setTorchMode(cameraId, false);
5087 if (res) {
5088 ALOGE("%s: torch client died but couldn't turn off torch: "
5089 "%s (%d)", __FUNCTION__, strerror(-res), res);
5090 return;
5091 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005092 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005093 break;
5094 }
5095 }
5096}
5097
Ruben Brunkcc776712015-02-17 20:18:47 -08005098/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005099
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005100 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005101 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5102 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005103 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005104 // PID here is approximate and can be wrong.
Austin Borgered99f642023-06-01 16:51:35 -07005105 logClientDied(CameraThreadState::getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005106
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005107 // check torch client
5108 handleTorchClientBinderDied(who);
5109
5110 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005111 if(!evictClientIdByRemote(who)) {
5112 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005113 return;
5114 }
5115
Ruben Brunkcc776712015-02-17 20:18:47 -08005116 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5117 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005118}
5119
Austin Borgered99f642023-06-01 16:51:35 -07005120void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005121 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005122}
5123
Austin Borgered99f642023-06-01 16:51:35 -07005124void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005125 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005126 // Do not lock mServiceLock here or can get into a deadlock from
5127 // connect() -> disconnect -> updateStatus
5128
5129 auto state = getCameraState(cameraId);
5130
5131 if (state == nullptr) {
5132 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005133 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005134 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005135 }
5136
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005137 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5138 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5139 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005140 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005141 return;
5142 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005143
5144 // Collect the logical cameras without holding mStatusLock in updateStatus
5145 // as that can lead to a deadlock(b/162192331).
5146 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005147 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005148 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005149 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005150 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005151 (const std::string& cameraId, StatusInternal status) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005152 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005153 // Update torch status if it has a flash unit.
5154 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005155 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005156 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5157 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005158 TorchModeStatus newTorchStatus =
5159 status == StatusInternal::PRESENT ?
5160 TorchModeStatus::AVAILABLE_OFF :
5161 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005162 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07005163 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005164 }
5165 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005166 }
5167
5168 Mutex::Autolock lock(mStatusListenerLock);
Austin Borgered99f642023-06-01 16:51:35 -07005169 notifyPhysicalCameraStatusLocked(mapToInterface(status), cameraId,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005170 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08005171
Ruben Brunkcc776712015-02-17 20:18:47 -08005172 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07005173 bool isVendorListener = listener->isVendorListener();
5174 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5175 listener->getListenerPid(), listener->getListenerUid()) ||
Shuzhen Wangb8259792021-05-27 09:27:06 -07005176 isVendorListener) {
5177 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07005178 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08005179 continue;
5180 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005181 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
Austin Borgered99f642023-06-01 16:51:35 -07005182 cameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005183 listener->handleBinderStatus(ret,
malikakash82ed4352023-07-21 22:44:34 +00005184 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
Austin Borgere8e2c422022-05-12 13:45:24 -07005185 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5186 ret.exceptionCode());
malikakash82ed4352023-07-21 22:44:34 +00005187 // Also trigger the callbacks for cameras that were remapped to the current
5188 // cameraId for the specific package that this listener belongs to.
Austin Borgered99f642023-06-01 16:51:35 -07005189 std::vector<std::string> remappedCameraIds =
malikakash82ed4352023-07-21 22:44:34 +00005190 findOriginalIdsForRemappedCameraId(cameraId, listener->getListenerUid());
5191 for (auto& remappedCameraId : remappedCameraIds) {
5192 ret = listener->getListener()->onStatusChanged(
Austin Borgered99f642023-06-01 16:51:35 -07005193 mapToInterface(status), remappedCameraId);
malikakash82ed4352023-07-21 22:44:34 +00005194 listener->handleBinderStatus(ret,
5195 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
5196 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5197 ret.exceptionCode());
5198 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005199 }
5200 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005201}
5202
Austin Borgered99f642023-06-01 16:51:35 -07005203void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5204 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005205 auto state = getCameraState(cameraId);
5206 if (state == nullptr) {
5207 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005208 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005209 return;
5210 }
5211 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005212 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005213 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005214 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005215 }
5216
Shuzhen Wang695044d2020-03-06 09:02:23 -08005217 Mutex::Autolock lock(mStatusListenerLock);
5218
5219 for (const auto& it : mListenerList) {
5220 if (!it->isOpenCloseCallbackAllowed()) {
5221 continue;
5222 }
5223
5224 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005225 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005226 ret = it->getListener()->onCameraOpened(cameraId, clientPackageName);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005227 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005228 ret = it->getListener()->onCameraClosed(cameraId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005229 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005230
5231 it->handleBinderStatus(ret,
5232 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5233 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005234 }
5235}
5236
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005237template<class Func>
5238void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005239 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005240 std::initializer_list<StatusInternal> rejectSourceStates,
5241 Func onStatusUpdatedLocked) {
5242 Mutex::Autolock lock(mStatusLock);
5243 StatusInternal oldStatus = mStatus;
5244 mStatus = status;
5245
5246 if (oldStatus == status) {
5247 return;
5248 }
5249
5250 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005251 cameraId.c_str(), oldStatus, status);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005252
5253 if (oldStatus == StatusInternal::NOT_PRESENT &&
5254 (status != StatusInternal::PRESENT &&
5255 status != StatusInternal::ENUMERATING)) {
5256
5257 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5258 __FUNCTION__);
5259 mStatus = oldStatus;
5260 return;
5261 }
5262
5263 /**
5264 * Sometimes we want to conditionally do a transition.
5265 * For example if a client disconnects, we want to go to PRESENT
5266 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5267 */
5268 for (auto& rejectStatus : rejectSourceStates) {
5269 if (oldStatus == rejectStatus) {
5270 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005271 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005272 mStatus = oldStatus;
5273 return;
5274 }
5275 }
5276
5277 onStatusUpdatedLocked(cameraId, status);
5278}
5279
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005280status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005281 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005282 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005283 if (!status) {
5284 return BAD_VALUE;
5285 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005286 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5287 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005288 // invalid camera ID or the camera doesn't have a flash unit
5289 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005290 }
5291
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005292 *status = mTorchStatusMap.valueAt(index);
5293 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005294}
5295
Austin Borgered99f642023-06-01 16:51:35 -07005296status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005297 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005298 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5299 if (index == NAME_NOT_FOUND) {
5300 return BAD_VALUE;
5301 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005302 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005303
5304 return OK;
5305}
5306
Austin Borgered99f642023-06-01 16:51:35 -07005307std::list<std::string> CameraService::getLogicalCameras(
5308 const std::string& physicalCameraId) {
5309 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005310 Mutex::Autolock lock(mCameraStatesLock);
5311 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005312 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5313 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005314 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005315 }
5316 return retList;
5317}
5318
5319void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005320 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005321 SystemCameraKind deviceKind) {
5322 // mStatusListenerLock is expected to be locked
5323 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005324 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005325 // Note: we check only the deviceKind of the physical camera id
5326 // since, logical camera ids and their physical camera ids are
5327 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005328 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5329 listener->getListenerPid(), listener->getListenerUid())) {
5330 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005331 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005332 continue;
5333 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005334 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005335 logicalCameraId, physicalCameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005336 listener->handleBinderStatus(ret,
5337 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5338 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5339 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005340 }
5341 }
5342}
5343
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005344
Svet Ganova453d0d2018-01-11 15:37:58 -08005345void CameraService::blockClientsForUid(uid_t uid) {
5346 const auto clients = mActiveClientManager.getAll();
5347 for (auto& current : clients) {
5348 if (current != nullptr) {
5349 const auto basicClient = current->getValue();
5350 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5351 basicClient->block();
5352 }
5353 }
5354 }
5355}
5356
Michael Grooverd1d435a2018-12-18 17:39:42 -08005357void CameraService::blockAllClients() {
5358 const auto clients = mActiveClientManager.getAll();
5359 for (auto& current : clients) {
5360 if (current != nullptr) {
5361 const auto basicClient = current->getValue();
5362 if (basicClient.get() != nullptr) {
5363 basicClient->block();
5364 }
5365 }
5366 }
5367}
5368
Svet Ganova453d0d2018-01-11 15:37:58 -08005369// NOTE: This is a remote API - make sure all args are validated
5370status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005371 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005372 return PERMISSION_DENIED;
5373 }
5374 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5375 return BAD_VALUE;
5376 }
Austin Borgered99f642023-06-01 16:51:35 -07005377 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005378 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005379 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005380 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005381 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005382 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005383 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005384 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005385 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005386 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005387 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005388 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005389 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005390 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005391 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005392 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005393 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005394 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005395 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005396 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005397 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005398 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005399 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005400 handleClearStreamUseCaseOverrides();
5401 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005402 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005403 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07005404 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005405 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07005406 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00005407 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07005408 } else if (args.size() >= 4 && args[0] == toString16("remap-camera-id")) {
malikakash82ed4352023-07-21 22:44:34 +00005409 return handleCameraIdRemapping(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005410 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005411 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005412 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005413 }
5414 printHelp(err);
5415 return BAD_VALUE;
5416}
5417
malikakash82ed4352023-07-21 22:44:34 +00005418status_t CameraService::handleCameraIdRemapping(const Vector<String16>& args, int err) {
5419 uid_t uid = IPCThreadState::self()->getCallingUid();
5420 if (uid != AID_ROOT) {
5421 dprintf(err, "Must be adb root\n");
5422 return PERMISSION_DENIED;
5423 }
5424 if (args.size() != 4) {
5425 dprintf(err, "Expected format: remap-camera-id <PACKAGE> <Id0> <Id1>\n");
5426 return BAD_VALUE;
5427 }
Austin Borgered99f642023-06-01 16:51:35 -07005428 std::string packageName = toStdString(args[1]);
5429 std::string cameraIdToReplace = toStdString(args[2]);
5430 std::string cameraIdNew = toStdString(args[3]);
malikakash82ed4352023-07-21 22:44:34 +00005431 remapCameraIds({{packageName, {{cameraIdToReplace, cameraIdNew}}}});
5432 return OK;
5433}
5434
Svet Ganova453d0d2018-01-11 15:37:58 -08005435status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005436 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005437
Svet Ganova453d0d2018-01-11 15:37:58 -08005438 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07005439 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005440 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07005441 } else if ((args[2] != toString16("idle"))) {
5442 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08005443 return BAD_VALUE;
5444 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005445
5446 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005447 if (args.size() >= 5 && args[3] == toString16("--user")) {
5448 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005449 }
5450
5451 uid_t uid;
5452 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5453 return BAD_VALUE;
5454 }
5455
5456 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005457 return NO_ERROR;
5458}
5459
5460status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005461 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005462
5463 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005464 if (args.size() >= 4 && args[2] == toString16("--user")) {
5465 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005466 }
5467
5468 uid_t uid;
5469 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005470 return BAD_VALUE;
5471 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005472
5473 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005474 return NO_ERROR;
5475}
5476
5477status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005478 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005479
5480 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005481 if (args.size() >= 4 && args[2] == toString16("--user")) {
5482 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005483 }
5484
5485 uid_t uid;
5486 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005487 return BAD_VALUE;
5488 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005489
5490 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005491 return dprintf(out, "active\n");
5492 } else {
5493 return dprintf(out, "idle\n");
5494 }
5495}
5496
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005497status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005498 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005499 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
5500 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
5501 Mutex::Autolock lock(mServiceLock);
5502
5503 mOverrideRotateAndCropMode = rotateValue;
5504
5505 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
5506
5507 const auto clients = mActiveClientManager.getAll();
5508 for (auto& current : clients) {
5509 if (current != nullptr) {
5510 const auto basicClient = current->getValue();
5511 if (basicClient.get() != nullptr) {
5512 basicClient->setRotateAndCropOverride(rotateValue);
5513 }
5514 }
5515 }
5516
5517 return OK;
5518}
5519
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005520status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
5521 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07005522 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005523 if ((*end != '\0') ||
5524 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
5525 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
5526 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
5527 return BAD_VALUE;
5528 }
5529
5530 Mutex::Autolock lock(mServiceLock);
5531 mOverrideAutoframingMode = autoframingValue;
5532
5533 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
5534
5535 const auto clients = mActiveClientManager.getAll();
5536 for (auto& current : clients) {
5537 if (current != nullptr) {
5538 const auto basicClient = current->getValue();
5539 if (basicClient.get() != nullptr) {
5540 basicClient->setAutoframingOverride(autoframingValue);
5541 }
5542 }
5543 }
5544
5545 return OK;
5546}
5547
Ravneetaeb20dc2022-03-30 05:33:03 +00005548status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005549 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00005550
5551 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
5552
5553 Mutex::Autolock lock(mServiceLock);
5554
5555 mCameraServiceWatchdogEnabled = enableWatchdog;
5556
5557 const auto clients = mActiveClientManager.getAll();
5558 for (auto& current : clients) {
5559 if (current != nullptr) {
5560 const auto basicClient = current->getValue();
5561 if (basicClient.get() != nullptr) {
5562 basicClient->setCameraServiceWatchdog(enableWatchdog);
5563 }
5564 }
5565 }
5566
5567 return OK;
5568}
5569
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005570status_t CameraService::handleGetRotateAndCrop(int out) {
5571 Mutex::Autolock lock(mServiceLock);
5572
5573 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
5574}
5575
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005576status_t CameraService::handleGetAutoframing(int out) {
5577 Mutex::Autolock lock(mServiceLock);
5578
5579 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
5580}
5581
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005582status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
5583 char *endPtr;
5584 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005585 std::string maskString = toStdString(args[1]);
5586 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005587
5588 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07005589 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005590 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
5591
5592 Mutex::Autolock lock(mServiceLock);
5593
5594 mImageDumpMask = maskValue;
5595
5596 return OK;
5597}
5598
5599status_t CameraService::handleGetImageDumpMask(int out) {
5600 Mutex::Autolock lock(mServiceLock);
5601
5602 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
5603}
5604
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005605status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005606 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005607 if (errno != 0) return BAD_VALUE;
5608
5609 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
5610 Mutex::Autolock lock(mServiceLock);
5611
5612 mOverrideCameraMuteMode = (muteValue == 1);
5613
5614 const auto clients = mActiveClientManager.getAll();
5615 for (auto& current : clients) {
5616 if (current != nullptr) {
5617 const auto basicClient = current->getValue();
5618 if (basicClient.get() != nullptr) {
5619 if (basicClient->supportsCameraMute()) {
5620 basicClient->setCameraMute(mOverrideCameraMuteMode);
5621 }
5622 }
5623 }
5624 }
5625
5626 return OK;
5627}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005628
Shuzhen Wang16610a62022-12-15 22:38:07 -08005629status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
5630 std::vector<int64_t> useCasesOverride;
5631 for (size_t i = 1; i < args.size(); i++) {
5632 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07005633 std::string arg = toStdString(args[i]);
5634 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005635 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07005636 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005637 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07005638 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005639 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07005640 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005641 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07005642 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005643 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07005644 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005645 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07005646 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005647 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
5648 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005649 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005650 return BAD_VALUE;
5651 }
5652 useCasesOverride.push_back(useCase);
5653 }
5654
5655 Mutex::Autolock lock(mServiceLock);
5656 mStreamUseCaseOverrides = std::move(useCasesOverride);
5657
5658 return OK;
5659}
5660
5661void CameraService::handleClearStreamUseCaseOverrides() {
5662 Mutex::Autolock lock(mServiceLock);
5663 mStreamUseCaseOverrides.clear();
5664}
5665
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005666status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
5667 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07005668 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005669 if ((*end != '\0') ||
5670 (zoomOverrideValue != -1 &&
5671 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
5672 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
5673 return BAD_VALUE;
5674 }
5675
5676 Mutex::Autolock lock(mServiceLock);
5677 mZoomOverrideValue = zoomOverrideValue;
5678
5679 const auto clients = mActiveClientManager.getAll();
5680 for (auto& current : clients) {
5681 if (current != nullptr) {
5682 const auto basicClient = current->getValue();
5683 if (basicClient.get() != nullptr) {
5684 if (basicClient->supportsZoomOverride()) {
5685 basicClient->setZoomOverride(mZoomOverrideValue);
5686 }
5687 }
5688 }
5689 }
5690
5691 return OK;
5692}
5693
Avichal Rakesh84147132021-11-11 17:47:11 -08005694status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07005695 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005696 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07005697 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005698 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07005699 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005700 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07005701 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005702 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07005703 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005704 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005705 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005706 dprintf(outFd, "Camera service watch commands:\n"
5707 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
5708 " starts watching the provided tags for clients with provided package\n"
5709 " recognizes tag shorthands like '3a'\n"
5710 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005711 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005712 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005713 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005714 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08005715 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005716 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005717 return BAD_VALUE;
5718}
5719
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005720status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
5721 Mutex::Autolock lock(mLogLock);
5722 size_t tagsIdx; // index of '-m'
5723 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07005724 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005725 if (tagsIdx < args.size() - 1) {
5726 tags = args[tagsIdx + 1];
5727 } else {
5728 dprintf(outFd, "No tags provided.\n");
5729 return BAD_VALUE;
5730 }
5731
5732 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07005733 // watch all clients if no clients are provided
5734 String16 clients = toString16(kWatchAllClientsFlag);
5735 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005736 clientsIdx++);
5737 if (clientsIdx < args.size() - 1) {
5738 clients = args[clientsIdx + 1];
5739 }
Austin Borgered99f642023-06-01 16:51:35 -07005740 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005741
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005742 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07005743 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005744
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005745 bool serviceLock = tryLock(mServiceLock);
5746 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005747 auto cameraClients = mActiveClientManager.getAll();
5748 for (const auto &clientDescriptor: cameraClients) {
5749 if (clientDescriptor == nullptr) { continue; }
5750 sp<BasicClient> client = clientDescriptor->getValue();
5751 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005752
5753 if (isClientWatchedLocked(client.get())) {
5754 client->startWatchingTags(mMonitorTags, outFd);
5755 numWatchedClients++;
5756 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005757 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005758 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
5759
5760 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005761 return OK;
5762}
5763
5764status_t CameraService::stopWatchingTags(int outFd) {
5765 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005766 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07005767 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005768
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005769 mWatchedClientPackages.clear();
5770 mWatchedClientsDumpCache.clear();
5771
5772 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005773 auto cameraClients = mActiveClientManager.getAll();
5774 for (const auto &clientDescriptor : cameraClients) {
5775 if (clientDescriptor == nullptr) { continue; }
5776 sp<BasicClient> client = clientDescriptor->getValue();
5777 if (client.get() == nullptr) { continue; }
5778 client->stopWatchingTags(outFd);
5779 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005780 dprintf(outFd, "Stopped watching all clients.\n");
5781 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005782 return OK;
5783}
5784
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005785status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
5786 Mutex::Autolock lock(mLogLock);
5787 size_t clearedSize = mWatchedClientsDumpCache.size();
5788 mWatchedClientsDumpCache.clear();
5789 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
5790 return OK;
5791}
5792
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005793status_t CameraService::printWatchedTags(int outFd) {
5794 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07005795 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005796
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005797 bool printedSomething = false; // tracks if any monitoring information was printed
5798 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005799
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005800 bool serviceLock = tryLock(mServiceLock);
5801 // get all watched clients that are currently connected
5802 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
5803 if (clientDescriptor == nullptr) { continue; }
5804
5805 sp<BasicClient> client = clientDescriptor->getValue();
5806 if (client.get() == nullptr) { continue; }
5807 if (!isClientWatchedLocked(client.get())) { continue; }
5808
5809 std::vector<std::string> dumpVector;
5810 client->dumpWatchedEventsToVector(dumpVector);
5811
5812 size_t printIdx = dumpVector.size();
5813 if (printIdx == 0) {
5814 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005815 }
5816
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005817 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07005818 const std::string &cameraId = clientDescriptor->getKey();
5819 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005820 while(printIdx > 0) {
5821 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07005822 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005823 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005824 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005825 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005826 printedSomething = true;
5827
5828 connectedMonitoredClients.emplace(client->getPackageName());
5829 }
5830 if (serviceLock) { mServiceLock.unlock(); }
5831
5832 // Print entries in mWatchedClientsDumpCache for clients that are not connected
5833 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07005834 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005835 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
5836 continue;
5837 }
5838
Austin Borgered99f642023-06-01 16:51:35 -07005839 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005840 dprintf(outFd, "%s\n", kv.second.c_str());
5841 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005842 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005843
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005844 if (!printedSomething) {
5845 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005846 }
5847
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005848 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005849}
5850
Avichal Rakesh84147132021-11-11 17:47:11 -08005851// Print all events in vector `events' that came after lastPrintedEvent
5852void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07005853 const std::string &cameraId,
5854 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08005855 const std::vector<std::string> &events,
5856 const std::string &lastPrintedEvent) {
5857 if (events.empty()) { return; }
5858
5859 // index of lastPrintedEvent in events.
5860 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
5861 size_t lastPrintedIdx;
5862 for (lastPrintedIdx = 0;
5863 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
5864 lastPrintedIdx++);
5865
5866 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
5867
Avichal Rakesh84147132021-11-11 17:47:11 -08005868 // print events in chronological order (latest event last)
5869 size_t idxToPrint = lastPrintedIdx;
5870 do {
5871 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07005872 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
5873 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08005874 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08005875}
5876
5877// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
5878// command should be interrupted if the user presses the return key, or if user loses any way to
5879// signal interrupt.
5880// If timeoutMs == 0, this function will always return false
5881bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
5882 struct timeval startTime;
5883 int startTimeError = gettimeofday(&startTime, nullptr);
5884 if (startTimeError) {
5885 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5886 return true;
5887 }
5888
5889 const nfds_t numFds = 1;
5890 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
5891
5892 struct timeval currTime;
5893 char buffer[2];
5894 while(true) {
5895 int currTimeError = gettimeofday(&currTime, nullptr);
5896 if (currTimeError) {
5897 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5898 return true;
5899 }
5900
5901 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
5902 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
5903 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
5904
5905 if (remainingTimeMs <= 0) {
5906 // No user interrupt within timeoutMs, don't interrupt watch command
5907 return false;
5908 }
5909
5910 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
5911 if (numFdsUpdated < 0) {
5912 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5913 return true;
5914 }
5915
5916 if (numFdsUpdated == 0) {
5917 // No user input within timeoutMs, don't interrupt watch command
5918 return false;
5919 }
5920
5921 if (!(pollFd.revents & POLLIN)) {
5922 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5923 return true;
5924 }
5925
5926 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
5927 if (sizeRead < 0) {
5928 dprintf(outFd, "Error reading user input. Exiting.\n");
5929 return true;
5930 }
5931
5932 if (sizeRead == 0) {
5933 // Reached end of input fd (can happen if input is piped)
5934 // User has no way to signal an interrupt, so interrupt here
5935 return true;
5936 }
5937
5938 if (buffer[0] == '\n') {
5939 // User pressed return, interrupt watch command.
5940 return true;
5941 }
5942 }
5943}
5944
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005945status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
5946 int inFd, int outFd) {
5947 // Figure out refresh interval, if present in args
5948 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005949 if (args.size() > 2) {
5950 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07005951 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005952 intervalIdx++);
5953
5954 size_t intervalValIdx = intervalIdx + 1;
5955 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07005956 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005957 if (errno) { return BAD_VALUE; }
5958 }
5959 }
5960
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005961 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
5962 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005963
Avichal Rakesh84147132021-11-11 17:47:11 -08005964 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07005965 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005966
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005967 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005968 bool serviceLock = tryLock(mServiceLock);
5969 auto cameraClients = mActiveClientManager.getAll();
5970 if (serviceLock) { mServiceLock.unlock(); }
5971
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005972 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005973 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005974 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005975
5976 sp<BasicClient> client = clientDescriptor->getValue();
5977 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005978 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005979
Austin Borgered99f642023-06-01 16:51:35 -07005980 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08005981 // This also initializes the map entries with an empty string
5982 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
5983
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005984 std::vector<std::string> latestEvents;
5985 client->dumpWatchedEventsToVector(latestEvents);
5986
5987 if (!latestEvents.empty()) {
5988 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07005989 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08005990 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005991 latestEvents,
5992 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08005993 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005994 }
5995 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005996 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005997 break;
5998 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005999 }
6000 return OK;
6001}
6002
Austin Borgered99f642023-06-01 16:51:35 -07006003void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006004 mWatchedClientPackages.clear();
6005
Austin Borgered99f642023-06-01 16:51:35 -07006006 std::istringstream iss(clients);
6007 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006008
Austin Borgered99f642023-06-01 16:51:35 -07006009 while (std::getline(iss, nextClient, ',')) {
6010 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006011 // Don't need to track any other package if 'all' is present
6012 mWatchedClientPackages.clear();
6013 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6014 break;
6015 }
6016
6017 // track package names
6018 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006019 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006020}
6021
Svet Ganova453d0d2018-01-11 15:37:58 -08006022status_t CameraService::printHelp(int out) {
6023 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006024 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6025 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6026 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006027 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6028 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6029 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006030 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6031 " Valid values 0=false, 1=true, 2=auto\n"
6032 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006033 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6034 " Valid values 0=OFF, 1=ON for JPEG\n"
6035 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006036 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006037 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6038 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6039 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6040 " on. In case the number of usecases is smaller than the number of streams, the\n"
6041 " last use case is assigned to all the remaining streams. In case of multiple\n"
6042 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6043 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6044 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6045 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006046 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6047 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
malikakash82ed4352023-07-21 22:44:34 +00006048 " remap-camera-id <PACKAGE> <Id0> <Id1> remaps camera ids. Must use adb root\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006049 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006050 " help print this message\n");
6051}
6052
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006053bool CameraService::isClientWatched(const BasicClient *client) {
6054 Mutex::Autolock lock(mLogLock);
6055 return isClientWatchedLocked(client);
6056}
6057
6058bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6059 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6060 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6061}
6062
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006063int32_t CameraService::updateAudioRestriction() {
6064 Mutex::Autolock lock(mServiceLock);
6065 return updateAudioRestrictionLocked();
6066}
6067
6068int32_t CameraService::updateAudioRestrictionLocked() {
6069 int32_t mode = 0;
6070 // iterate through all active client
6071 for (const auto& i : mActiveClientManager.getAll()) {
6072 const auto clientSp = i->getValue();
6073 mode |= clientSp->getAudioRestriction();
6074 }
6075
6076 bool modeChanged = (mAudioRestriction != mode);
6077 mAudioRestriction = mode;
6078 if (modeChanged) {
6079 mAppOps.setCameraAudioRestriction(mode);
6080 }
6081 return mode;
6082}
6083
Austin Borgered99f642023-06-01 16:51:35 -07006084status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006085 sp<BasicClient> clientSp) {
6086 std::unique_ptr<AutoConditionLock> lock =
6087 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6088 status_t res = NO_ERROR;
6089 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006090 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006091 mInjectionStatusListener->notifyInjectionError(
6092 externalCamId, UNKNOWN_TRANSACTION);
6093 clientSp->notifyError(
6094 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6095 CaptureResultExtras());
6096
6097 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6098 // other clients from connecting in mServiceLockWrapper if held
6099 mServiceLock.unlock();
6100
6101 // Clear caller identity temporarily so client disconnect PID checks work correctly
6102 int64_t token = CameraThreadState::clearCallingIdentity();
6103 clientSp->disconnect();
6104 CameraThreadState::restoreCallingIdentity(token);
6105
6106 // Reacquire mServiceLock
6107 mServiceLock.lock();
6108 }
6109
6110 return res;
6111}
6112
Cliff Wud3a05312021-04-26 23:07:31 +08006113void CameraService::clearInjectionParameters() {
6114 {
6115 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006116 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006117 mInjectionInternalCamId = "";
6118 }
6119 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006120 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006121}
6122
Mathias Agopian65ab4712010-07-14 17:59:35 -07006123}; // namespace android