blob: 3cdcf6ae7f3a182d20a3434147bede8b44f14a1b [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>
27#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080029#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <pthread.h>
Avichal Rakesh84147132021-11-11 17:47:11 -080031#include <poll.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080033#include <android/hardware/ICamera.h>
34#include <android/hardware/ICameraClient.h>
35
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -070036#include <aidl/AidlCameraService.h>
Alex Deymo9c2a2c22016-08-25 11:59:14 -070037#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080038#include <android-base/parseint.h>
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070039#include <android-base/stringprintf.h>
Joanne Chung02c13d02023-01-16 12:58:05 +000040#include <android/permission/PermissionChecker.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080041#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080042#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044#include <binder/MemoryBase.h>
45#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080046#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080047#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080048#include <binderthreadstate/CallerUtils.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070049#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070050#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080051#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080052#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070053#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070054#include "hidl/HidlCameraService.h"
55#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080056#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070057#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080059#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070060#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070061#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000062#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070063#include <utils/Errors.h>
64#include <utils/Log.h>
65#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070066#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080067#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080068#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080069#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080070#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070071#include <system/camera_metadata.h>
Kunal Malhotrabfc96052023-02-28 23:25:34 +000072#include <binder/IServiceManager.h>
73#include <binder/IActivityManager.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080074
Ruben Brunkb2119af2014-05-09 19:57:56 -070075#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070076
77#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070078#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070079#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070080#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000081#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070082#include "utils/CameraThreadState.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070083#include "utils/CameraServiceProxyWrapper.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070084
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080085namespace {
86 const char* kPermissionServiceName = "permission";
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080087 const char* kActivityServiceName = "activity";
88 const char* kSensorPrivacyServiceName = "sensor_privacy";
89 const char* kAppopsServiceName = "appops";
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080090}; // namespace anonymous
91
Mathias Agopian65ab4712010-07-14 17:59:35 -070092namespace android {
93
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070094using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080095using binder::Status;
Austin Borgerea931242021-12-13 23:10:41 +000096using namespace camera3;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070097using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -070098using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080099using hardware::ICamera;
100using hardware::ICameraClient;
101using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800102using hardware::camera2::ICameraInjectionCallback;
103using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800104using hardware::camera2::utils::CameraIdAndSessionConfiguration;
105using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800106
Mathias Agopian65ab4712010-07-14 17:59:35 -0700107// ----------------------------------------------------------------------------
108// Logging support -- this is for debugging only
109// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700110volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700111
Steve Blockb8a80522011-12-20 16:23:08 +0000112#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
113#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700114
115static void setLogLevel(int level) {
116 android_atomic_write(level, &gLogLevel);
117}
118
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800119// Convenience methods for constructing binder::Status objects for error returns
120
121#define STATUS_ERROR(errorCode, errorString) \
122 binder::Status::fromServiceSpecificError(errorCode, \
123 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
124
125#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
126 binder::Status::fromServiceSpecificError(errorCode, \
127 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
128 __VA_ARGS__))
129
Mathias Agopian65ab4712010-07-14 17:59:35 -0700130// ----------------------------------------------------------------------------
131
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700132static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800133static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700134static const String16 sCameraPermission("android.permission.CAMERA");
135static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
136static const String16
137 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Shuzhen Wang695044d2020-03-06 09:02:23 -0800138static const String16 sCameraOpenCloseListenerPermission(
139 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Cliff Wud8cae102021-03-11 01:37:42 +0800140static const String16
141 sCameraInjectExternalCameraPermission("android.permission.CAMERA_INJECT_EXTERNAL_CAMERA");
Kunal Malhotrabfc96052023-02-28 23:25:34 +0000142// Constant integer for FGS Logging, used to denote the API type for logger
143static const int LOG_FGS_CAMERA_API = 1;
Rucha Katakwardf223072021-06-15 10:21:00 -0700144const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800145static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
146static constexpr int32_t kSystemNativeClientState =
147 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700148
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800149const String8 CameraService::kOfflineDevice("offline-");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -0700150const String16 CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700151
Rucha Katakward9ea6452021-05-06 11:57:16 -0700152// Set to keep track of logged service error events.
153static std::set<String8> sServiceErrorEventSet;
154
Austin Borger74fca042022-05-23 12:41:21 -0700155CameraService::CameraService(
156 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper) :
157 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
158 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800159 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800160 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700161 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700162 mSoundRef(0), mInitialized(false),
163 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000164 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800165 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700166 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
167 if (mMemFd == -1) {
168 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
169 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700170}
171
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800172// The word 'System' here does not refer to clients only on the system
173// partition. They just need to have a android system uid.
174static bool doesClientHaveSystemUid() {
175 return (CameraThreadState::getCallingUid() < AID_APP_START);
176}
177
Charles Chena7b613c2023-01-24 21:57:33 +0000178// Enable processes with isolated AID to request the binder
179void CameraService::instantiate() {
180 CameraService::publish(true);
181}
182
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800183void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
184 if (name != String16(kAppopsServiceName)) {
185 return;
186 }
187
188 ALOGV("appops service registered. setting camera audio restriction");
189 mAppOps.setCameraAudioRestriction(mAudioRestriction);
190}
191
Iliyan Malchev8951a972011-04-14 16:55:59 -0700192void CameraService::onFirstRef()
193{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700194
Ruben Brunkcc776712015-02-17 20:18:47 -0800195 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800196
Iliyan Malchev8951a972011-04-14 16:55:59 -0700197 BnCameraService::onFirstRef();
198
Ruben Brunk99e69712015-05-26 17:25:07 -0700199 // Update battery life tracking if service is restarting
200 BatteryNotifier& notifier(BatteryNotifier::getInstance());
201 notifier.noteResetCamera();
202 notifier.noteResetFlashlight();
203
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800204 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800205
Emilian Peevf53f66e2017-04-11 14:29:43 +0100206 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800207 if (res == OK) {
208 mInitialized = true;
209 }
210
Svet Ganova453d0d2018-01-11 15:37:58 -0800211 mUidPolicy = new UidPolicy(this);
212 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800213 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
214 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800215 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800216
217 // appops function setCamerAudioRestriction uses getService which
218 // is blocking till the appops service is ready. To enable early
219 // boot availability for cameraservice, use checkService which is
220 // non blocking and register for notifications
221 sp<IServiceManager> sm = defaultServiceManager();
222 sp<IBinder> binder = sm->checkService(String16(kAppopsServiceName));
223 if (!binder) {
224 sm->registerForNotifications(String16(kAppopsServiceName), this);
225 } else {
226 mAppOps.setCameraAudioRestriction(mAudioRestriction);
227 }
228
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700229 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
230 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000231 // Deprecated, so it will fail to register on newer devices
232 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700233 __FUNCTION__);
234 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700235
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700236 if (!AidlCameraService::registerService(this)) {
237 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
238 }
239
Shuzhen Wang24b44152019-09-20 10:38:11 -0700240 // This needs to be last call in this function, so that it's as close to
241 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700242 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700243 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800244}
245
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800246status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800247 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100248
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800249 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000250 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800251 {
252 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800253
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800254 if (nullptr == mCameraProviderManager.get()) {
255 mCameraProviderManager = new CameraProviderManager();
256 res = mCameraProviderManager->initialize(this);
257 if (res != OK) {
258 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
259 __FUNCTION__, strerror(-res), res);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700260 logServiceError(String8::format("Unable to initialize camera provider manager"),
261 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800262 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100263 }
264 }
265
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800266
267 // Setup vendor tags before we call get_camera_info the first time
268 // because HAL might need to setup static vendor keys in get_camera_info
269 // TODO: maybe put this into CameraProviderManager::initialize()?
270 mCameraProviderManager->setUpVendorTags();
271
272 if (nullptr == mFlashlight.get()) {
273 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700274 }
275
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800276 res = mFlashlight->findFlashUnits();
277 if (res != OK) {
278 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
279 }
280
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000281 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800282 }
283
284
285 for (auto& cameraId : deviceIds) {
286 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800287 if (getCameraState(id8) == nullptr) {
288 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
289 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000290 if (unavailPhysicalIds.count(cameraId) > 0) {
291 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
292 String8 physicalId8 = String8(physicalId.c_str());
293 onDeviceStatusChanged(id8, physicalId8, CameraDeviceStatus::NOT_PRESENT);
294 }
295 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800296 }
297
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700298 // Derive primary rear/front cameras, and filter their charactierstics.
299 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700300 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700301 // Assume internal cameras are advertised from the same
302 // provider. If multiple providers are registered at different time,
303 // and each provider contains multiple internal color cameras, the current
304 // logic may filter the characteristics of more than one front/rear color
305 // cameras.
306 Mutex::Autolock l(mServiceLock);
307 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700308 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700309
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800310 return OK;
311}
312
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700313void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status,
314 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800315 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800316 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700317 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
318 i->getListenerUid())) {
319 ALOGV("Skipping torch callback for system-only camera device %s",
320 cameraId.c_str());
321 continue;
322 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700323 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
324 String16{cameraId});
325 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
326 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800327 }
328}
329
Mathias Agopian65ab4712010-07-14 17:59:35 -0700330CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800331 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800332 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800333 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800334 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700335}
336
Emilian Peevaee727d2017-05-04 16:35:48 +0100337void CameraService::onNewProviderRegistered() {
338 enumerateProviders();
339}
340
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700341void CameraService::filterAPI1SystemCameraLocked(
342 const std::vector<std::string> &normalDeviceIds) {
343 mNormalDeviceIdsWithoutSystemCamera.clear();
344 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700345 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
346 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
347 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
348 continue;
349 }
350 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700351 // All system camera ids will necessarily come after public camera
352 // device ids as per the HAL interface contract.
353 break;
354 }
355 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
356 }
357 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
358 mNormalDeviceIdsWithoutSystemCamera.size());
359}
360
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700361status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
362 auto state = getCameraState(cameraId);
363 if (state != nullptr) {
364 *kind = state->getSystemCameraKind();
365 return OK;
366 }
367 // Hidden physical camera ids won't have CameraState
368 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
369}
370
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800371void CameraService::updateCameraNumAndIds() {
372 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700373 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
374 // Excludes hidden secure cameras
375 mNumberOfCameras =
376 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
377 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800378 mNormalDeviceIds =
379 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700380 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800381}
382
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700383void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700384 // To claim to be S Performance primary cameras, the cameras must be
385 // backward compatible. So performance class primary camera Ids must be API1
386 // compatible.
387 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
388 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
389 int facing = -1;
390 int orientation = 0;
391 String8 cameraId8(cameraId.c_str());
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800392 int portraitRotation;
393 getDeviceVersion(cameraId8, /*overrideToPortrait*/false, /*out*/&portraitRotation,
394 /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700395 if (facing == -1) {
396 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
397 return;
398 }
399
400 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
401 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700402 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
403 if (res == OK) {
404 mPerfClassPrimaryCameraIds.insert(cameraId);
405 } else {
406 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
407 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
408 break;
409 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700410
411 if (facing == hardware::CAMERA_FACING_BACK) {
412 firstRearCameraSeen = true;
413 }
414 if (facing == hardware::CAMERA_FACING_FRONT) {
415 firstFrontCameraSeen = true;
416 }
417 }
418
419 if (firstRearCameraSeen && firstFrontCameraSeen) {
420 break;
421 }
422 }
423}
424
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100425void CameraService::addStates(const String8 id) {
426 std::string cameraId(id.c_str());
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700427 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100428 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
429 if (res != OK) {
430 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
431 return;
432 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000433 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700434 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
435 if (res != OK) {
436 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
437 return;
438 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000439 std::vector<std::string> physicalCameraIds;
440 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100441 std::set<String8> conflicting;
442 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
443 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
444 }
445
446 {
447 Mutex::Autolock lock(mCameraStatesLock);
448 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000449 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100450 }
451
452 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100453 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100454 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800455
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700456 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100457 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800458
459 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100460 logDeviceAdded(id, "Device added");
461}
462
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100463void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800464 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100465 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100466 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100467 mTorchStatusMap.removeItem(id);
468 }
469
470 {
471 Mutex::Autolock lock(mCameraStatesLock);
472 mCameraStates.erase(id);
473 }
474}
475
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800476void CameraService::onDeviceStatusChanged(const String8& id,
477 CameraDeviceStatus newHalStatus) {
478 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
479 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700480
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800481 StatusInternal newStatus = mapToInternal(newHalStatus);
482
Ruben Brunkcc776712015-02-17 20:18:47 -0800483 std::shared_ptr<CameraState> state = getCameraState(id);
484
485 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700486 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100487 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700488 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100489
490 // First add as absent to make sure clients are notified below
491 addStates(id);
492
493 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700494 } else {
495 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
496 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700497 return;
498 }
499
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800500 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800501
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800502 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800503 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700504 return;
505 }
506
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800507 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700508 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
509 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800510
511 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
512 // to this device until the status changes
513 updateStatus(StatusInternal::NOT_PRESENT, id);
514
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800515 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700516 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800517 // Don't do this in updateStatus to avoid deadlock over mServiceLock
518 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700519
Ruben Brunkcc776712015-02-17 20:18:47 -0800520 // Remove cached shim parameters
521 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700522
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800523 // Remove online as well as offline client from the list of active clients,
524 // if they are present
525 clientToDisconnectOnline = removeClientLocked(id);
526 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700527 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800528
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800529 disconnectClient(id, clientToDisconnectOnline);
530 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700531
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100532 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800533 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800534 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700535 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
536 newStatus));
537 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800538 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700539 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800540}
Igor Murashkincba2c162013-03-20 15:56:31 -0700541
Shuzhen Wang43858162020-01-10 13:42:15 -0800542void CameraService::onDeviceStatusChanged(const String8& id,
543 const String8& physicalId,
544 CameraDeviceStatus newHalStatus) {
545 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
546 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
547
548 StatusInternal newStatus = mapToInternal(newHalStatus);
549
550 std::shared_ptr<CameraState> state = getCameraState(id);
551
552 if (state == nullptr) {
553 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000554 __FUNCTION__, physicalId.string(), id.string());
Shuzhen Wang43858162020-01-10 13:42:15 -0800555 return;
556 }
557
558 StatusInternal logicalCameraStatus = state->getStatus();
559 if (logicalCameraStatus != StatusInternal::PRESENT &&
560 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
561 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
562 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
563 return;
564 }
565
566 bool updated = false;
567 if (newStatus == StatusInternal::PRESENT) {
568 updated = state->removeUnavailablePhysicalId(physicalId);
569 } else {
570 updated = state->addUnavailablePhysicalId(physicalId);
571 }
572
573 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800574 String8 idCombo = id + " : " + physicalId;
575 if (newStatus == StatusInternal::PRESENT) {
576 logDeviceAdded(idCombo,
577 String8::format("Device status changed to %d", newStatus));
578 } else {
579 logDeviceRemoved(idCombo,
580 String8::format("Device status changed to %d", newStatus));
581 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700582 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
583 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
584 if (getSystemCameraKind(id, &deviceKind) != OK) {
585 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
586 return;
587 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800588 String16 id16(id), physicalId16(physicalId);
589 Mutex::Autolock lock(mStatusListenerLock);
590 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700591 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
592 listener->getListenerPid(), listener->getListenerUid())) {
593 ALOGV("Skipping discovery callback for system-only camera device %s",
594 id.c_str());
595 continue;
596 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700597 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
598 mapToInterface(newStatus), id16, physicalId16);
599 listener->handleBinderStatus(ret,
600 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
601 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
602 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800603 }
604 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700605}
606
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800607void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
608 if (clientToDisconnect.get() != nullptr) {
609 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
610 __FUNCTION__, id.string());
611 // Notify the client of disconnection
612 clientToDisconnect->notifyError(
613 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
614 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800615 clientToDisconnect->disconnect();
616 }
617}
618
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800619void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800620 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700621 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
622 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
623 if (res != OK) {
624 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
625 cameraId.string());
626 return;
627 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800628 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700629 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800630}
631
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700632
633void CameraService::onTorchStatusChanged(const String8& cameraId,
634 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
635 Mutex::Autolock al(mTorchStatusMutex);
636 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
637}
638
Rucha Katakwar38284522021-11-10 11:25:21 -0800639void CameraService::broadcastTorchStrengthLevel(const String8& cameraId,
640 int32_t newStrengthLevel) {
641 Mutex::Autolock lock(mStatusListenerLock);
642 for (auto& i : mListenerList) {
Austin Borgere8e2c422022-05-12 13:45:24 -0700643 auto ret = i->getListener()->onTorchStrengthLevelChanged(String16{cameraId},
Rucha Katakwar38284522021-11-10 11:25:21 -0800644 newStrengthLevel);
Austin Borgere8e2c422022-05-12 13:45:24 -0700645 i->handleBinderStatus(ret,
646 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
647 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800648 }
649}
650
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800651void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700652 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800653 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
654 __FUNCTION__, cameraId.string(), newStatus);
655
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800656 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800657 status_t res = getTorchStatusLocked(cameraId, &status);
658 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700659 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
660 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800661 return;
662 }
663 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800664 return;
665 }
666
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800667 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800668 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800669 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
670 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800671 return;
672 }
673
Ruben Brunkcc776712015-02-17 20:18:47 -0800674 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700675 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700676 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700677 auto iter = mTorchUidMap.find(cameraId);
678 if (iter != mTorchUidMap.end()) {
679 int oldUid = iter->second.second;
680 int newUid = iter->second.first;
681 BatteryNotifier& notifier(BatteryNotifier::getInstance());
682 if (oldUid != newUid) {
683 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800684 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700685 notifier.noteFlashlightOff(cameraId, oldUid);
686 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800687 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700688 notifier.noteFlashlightOn(cameraId, newUid);
689 }
690 iter->second.second = newUid;
691 } else {
692 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800693 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700694 notifier.noteFlashlightOn(cameraId, oldUid);
695 } else {
696 notifier.noteFlashlightOff(cameraId, oldUid);
697 }
698 }
699 }
700 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700701 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800702}
703
Joanne Chung02c13d02023-01-16 12:58:05 +0000704static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
705 permission::PermissionChecker permissionChecker;
706 AttributionSourceState attributionSource{};
707 attributionSource.pid = callingPid;
708 attributionSource.uid = callingUid;
709 bool checkPermissionForSystemCamera = permissionChecker.checkPermissionForPreflight(
710 sSystemCameraPermission, attributionSource, String16(), AppOpsManager::OP_NONE)
711 != permission::PermissionChecker::PERMISSION_HARD_DENIED;
712 bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
713 sCameraPermission, attributionSource, String16(), AppOpsManager::OP_NONE)
714 != permission::PermissionChecker::PERMISSION_HARD_DENIED;
715 return checkPermissionForSystemCamera && checkPermissionForCamera;
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700716}
717
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800718Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700719 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100720 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700721 bool hasSystemCameraPermissions =
722 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
723 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700724 switch (type) {
725 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700726 if (hasSystemCameraPermissions) {
727 *numCameras = static_cast<int>(mNormalDeviceIds.size());
728 } else {
729 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
730 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800731 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700732 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700733 if (hasSystemCameraPermissions) {
734 *numCameras = mNumberOfCameras;
735 } else {
736 *numCameras = mNumberOfCamerasWithoutSystemCamera;
737 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800738 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700739 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800740 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700741 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800742 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
743 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700744 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800745 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700746}
747
Austin Borger18b30a72022-10-27 12:20:29 -0700748Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800749 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700750 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100751 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700752 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
753 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
754 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
755 "characteristics for system only device %s: ", cameraIdStr.c_str());
756 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100757
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800758 if (!mInitialized) {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700759 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800760 return STATUS_ERROR(ERROR_DISCONNECTED,
761 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700762 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700763 bool hasSystemCameraPermissions =
764 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
765 CameraThreadState::getCallingUid());
766 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
767 if (hasSystemCameraPermissions) {
768 cameraIdBound = mNumberOfCameras;
769 }
770 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800771 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
772 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700773 }
774
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800775 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -0700776 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800777 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borger18b30a72022-10-27 12:20:29 -0700778 cameraIdStr.c_str(), overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100779 if (err != OK) {
780 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
781 "Error retrieving camera info from device %d: %s (%d)", cameraId,
782 strerror(-err), err);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700783 logServiceError(String8::format("Error retrieving camera info from device %d",cameraId),
784 ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -0800785 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100786
Ruben Brunkcc776712015-02-17 20:18:47 -0800787 return ret;
788}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700789
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800790std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700791 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
792 auto callingPid = CameraThreadState::getCallingPid();
793 auto callingUid = CameraThreadState::getCallingUid();
Joanne Chung02c13d02023-01-16 12:58:05 +0000794 permission::PermissionChecker permissionChecker;
795 AttributionSourceState attributionSource{};
796 attributionSource.pid = callingPid;
797 attributionSource.uid = callingUid;
798 bool checkPermissionForSystemCamera = permissionChecker.checkPermissionForPreflight(
799 sSystemCameraPermission, attributionSource, String16(), AppOpsManager::OP_NONE)
800 != permission::PermissionChecker::PERMISSION_HARD_DENIED;
801 if (checkPermissionForSystemCamera || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700802 deviceIds = &mNormalDeviceIds;
803 }
804 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800805 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700806 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800807 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800808 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800809
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700810 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800811}
812
813String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
814 Mutex::Autolock lock(mServiceLock);
815 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800816}
817
818Status CameraService::getCameraCharacteristics(const String16& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -0700819 int targetSdkVersion, bool overrideToPortrait, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700820 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700821 if (!cameraInfo) {
822 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800823 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700824 }
825
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800826 if (!mInitialized) {
827 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700828 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800829 return STATUS_ERROR(ERROR_DISCONNECTED,
830 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700831 }
832
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700833 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
834 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
835 "characteristics for system only device %s: ", String8(cameraId).string());
836 }
837
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800838 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800839
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700840
841 std::string cameraIdStr = String8(cameraId).string();
842 bool overrideForPerfClass =
843 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
844 cameraIdStr, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100845 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borger18b30a72022-10-27 12:20:29 -0700846 cameraIdStr, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100847 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700848 if (res == NAME_NOT_FOUND) {
849 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
850 "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
851 strerror(-res), res);
852 } else {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700853 logServiceError(String8::format("Unable to retrieve camera characteristics for "
854 "device %s.", String8(cameraId).string()),ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700855 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
856 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
857 strerror(-res), res);
858 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700859 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700860 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
861 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
862 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
863 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
864 "for device %s", String8(cameraId).string());
865 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700866 int callingPid = CameraThreadState::getCallingPid();
867 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100868 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700869 // If it's not calling from cameraserver, check the permission only if
870 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
871 // it would've already been checked in shouldRejectSystemCameraConnection.
Joanne Chung02c13d02023-01-16 12:58:05 +0000872 permission::PermissionChecker permissionChecker;
873 AttributionSourceState attributionSource{};
874 attributionSource.pid = callingPid;
875 attributionSource.uid = callingUid;
876 bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
877 sCameraPermission, attributionSource, String16(), AppOpsManager::OP_NONE)
878 != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Emilian Peeve20c6372018-08-14 18:45:53 +0100879 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700880 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Joanne Chung02c13d02023-01-16 12:58:05 +0000881 !checkPermissionForCamera) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100882 res = cameraInfo->removePermissionEntries(
883 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
884 &tagsRemoved);
885 if (res != OK) {
886 cameraInfo->clear();
887 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
888 " characteristics needing camera permission for device %s: %s (%d)",
889 String8(cameraId).string(), strerror(-res), res);
890 }
891 }
892
893 if (!tagsRemoved.empty()) {
894 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
895 tagsRemoved.data(), tagsRemoved.size());
896 if (res != OK) {
897 cameraInfo->clear();
898 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
899 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
900 strerror(-res), res);
901 }
902 }
903
Zhijun He2b59be82013-09-25 10:14:30 -0700904 return ret;
905}
906
Rucha Katakwar38284522021-11-10 11:25:21 -0800907Status CameraService::getTorchStrengthLevel(const String16& cameraId,
908 int32_t* torchStrength) {
909 ATRACE_CALL();
910 Mutex::Autolock l(mServiceLock);
911 if (!mInitialized) {
912 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
913 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
914 }
915
916 if(torchStrength == NULL) {
917 ALOGE("%s: strength level must not be null.", __FUNCTION__);
918 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
919 }
920
921 status_t res = mCameraProviderManager->getTorchStrengthLevel(String8(cameraId).string(),
922 torchStrength);
923 if (res != OK) {
924 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
925 "strength level for device %s: %s (%d)", String8(cameraId).string(),
926 strerror(-res), res);
927 }
928 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
929 return Status::ok();
930}
931
Ruben Brunkcc776712015-02-17 20:18:47 -0800932String8 CameraService::getFormattedCurrentTime() {
933 time_t now = time(nullptr);
934 char formattedTime[64];
935 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
936 return String8(formattedTime);
937}
938
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800939Status CameraService::getCameraVendorTagDescriptor(
940 /*out*/
941 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700942 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800943 if (!mInitialized) {
944 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800945 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800946 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800947 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
948 if (globalDescriptor != nullptr) {
949 *desc = *(globalDescriptor.get());
950 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800951 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800952}
953
Emilian Peev71c73a22017-03-21 16:35:51 +0000954Status CameraService::getCameraVendorTagCache(
955 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
956 ATRACE_CALL();
957 if (!mInitialized) {
958 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
959 return STATUS_ERROR(ERROR_DISCONNECTED,
960 "Camera subsystem not available");
961 }
962 sp<VendorTagDescriptorCache> globalCache =
963 VendorTagDescriptorCache::getGlobalVendorTagCache();
964 if (globalCache != nullptr) {
965 *cache = *(globalCache.get());
966 }
967 return Status::ok();
968}
969
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700970void CameraService::clearCachedVariables() {
971 BasicClient::BasicClient::sCameraService = nullptr;
972}
973
Austin Borger18b30a72022-10-27 12:20:29 -0700974std::pair<int, IPCTransport> CameraService::getDeviceVersion(const String8& cameraId,
975 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700976 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800977
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800978 int deviceVersion = 0;
979
Emilian Peevf53f66e2017-04-11 14:29:43 +0100980 status_t res;
981 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +0000982 IPCTransport transport = IPCTransport::INVALID;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100983 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +0000984 &maxVersion, &transport);
985 if (res != OK || transport == IPCTransport::INVALID) {
986 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
987 cameraId.string());
988 return std::make_pair(-1, IPCTransport::INVALID) ;
989 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100990 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800991
Emilian Peevf53f66e2017-04-11 14:29:43 +0100992 hardware::CameraInfo info;
993 if (facing) {
Austin Borger18b30a72022-10-27 12:20:29 -0700994 res = mCameraProviderManager->getCameraInfo(cameraId.string(), overrideToPortrait,
995 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +0000996 if (res != OK) {
997 return std::make_pair(-1, IPCTransport::INVALID);
998 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100999 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001000 if (orientation) {
1001 *orientation = info.orientation;
1002 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001003 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001004
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001005 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001006}
1007
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001008Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001009 switch(err) {
1010 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001011 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001012 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001013 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1014 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001015 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001016 return STATUS_ERROR(ERROR_DISCONNECTED,
1017 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001018 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001019 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1020 "Camera HAL encountered error %d: %s",
1021 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001022 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001023}
1024
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001025Status CameraService::makeClient(const sp<CameraService>& cameraService,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001026 const sp<IInterface>& cameraCb, const String16& packageName, bool systemNativeClient,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001027 const std::optional<String16>& featureId, const String8& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001028 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001029 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001030 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
1031 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001032 // For HIDL devices
1033 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1034 // Create CameraClient based on device version reported by the HAL.
1035 int deviceVersion = deviceVersionAndTransport.first;
1036 switch(deviceVersion) {
1037 case CAMERA_DEVICE_API_VERSION_1_0:
1038 ALOGE("Camera using old HAL version: %d", deviceVersion);
1039 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1040 "Camera device \"%s\" HAL version %d no longer supported",
1041 cameraId.string(), deviceVersion);
1042 break;
1043 case CAMERA_DEVICE_API_VERSION_3_0:
1044 case CAMERA_DEVICE_API_VERSION_3_1:
1045 case CAMERA_DEVICE_API_VERSION_3_2:
1046 case CAMERA_DEVICE_API_VERSION_3_3:
1047 case CAMERA_DEVICE_API_VERSION_3_4:
1048 case CAMERA_DEVICE_API_VERSION_3_5:
1049 case CAMERA_DEVICE_API_VERSION_3_6:
1050 case CAMERA_DEVICE_API_VERSION_3_7:
1051 break;
1052 default:
1053 // Should not be reachable
1054 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1055 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1056 "Camera device \"%s\" has unknown HAL version %d",
1057 cameraId.string(), deviceVersion);
1058 }
1059 }
1060 if (effectiveApiLevel == API_1) { // Camera1 API route
1061 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001062 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
1063 packageName, featureId, cameraId, api1CameraId, facing, sensorOrientation,
Austin Borger18b30a72022-10-27 12:20:29 -07001064 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait);
1065 ALOGI("%s: Camera1 API (legacy), override to portrait %d", __FUNCTION__,
1066 overrideToPortrait);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001067 } else { // Camera2 API route
1068 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1069 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001070 *client = new CameraDeviceClient(cameraService, tmp,
1071 cameraService->mCameraServiceProxyWrapper, packageName, systemNativeClient,
1072 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
Austin Borger18b30a72022-10-27 12:20:29 -07001073 overrideForPerfClass, overrideToPortrait);
1074 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001075 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001076 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001077}
1078
Ruben Brunk6267b532015-04-30 17:44:07 -07001079String8 CameraService::toString(std::set<userid_t> intSet) {
1080 String8 s("");
1081 bool first = true;
1082 for (userid_t i : intSet) {
1083 if (first) {
1084 s.appendFormat("%d", i);
1085 first = false;
1086 } else {
1087 s.appendFormat(", %d", i);
1088 }
1089 }
1090 return s;
1091}
1092
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001093int32_t CameraService::mapToInterface(TorchModeStatus status) {
1094 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1095 switch (status) {
1096 case TorchModeStatus::NOT_AVAILABLE:
1097 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1098 break;
1099 case TorchModeStatus::AVAILABLE_OFF:
1100 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1101 break;
1102 case TorchModeStatus::AVAILABLE_ON:
1103 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1104 break;
1105 default:
1106 ALOGW("Unknown new flash status: %d", status);
1107 }
1108 return serviceStatus;
1109}
1110
1111CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1112 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1113 switch (status) {
1114 case CameraDeviceStatus::NOT_PRESENT:
1115 serviceStatus = StatusInternal::NOT_PRESENT;
1116 break;
1117 case CameraDeviceStatus::PRESENT:
1118 serviceStatus = StatusInternal::PRESENT;
1119 break;
1120 case CameraDeviceStatus::ENUMERATING:
1121 serviceStatus = StatusInternal::ENUMERATING;
1122 break;
1123 default:
1124 ALOGW("Unknown new HAL device status: %d", status);
1125 }
1126 return serviceStatus;
1127}
1128
1129int32_t CameraService::mapToInterface(StatusInternal status) {
1130 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1131 switch (status) {
1132 case StatusInternal::NOT_PRESENT:
1133 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1134 break;
1135 case StatusInternal::PRESENT:
1136 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1137 break;
1138 case StatusInternal::ENUMERATING:
1139 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1140 break;
1141 case StatusInternal::NOT_AVAILABLE:
1142 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1143 break;
1144 case StatusInternal::UNKNOWN:
1145 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1146 break;
1147 default:
1148 ALOGW("Unknown new internal device status: %d", status);
1149 }
1150 return serviceStatus;
1151}
1152
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001153Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001154 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001155
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001156 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -08001157 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001158 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001159 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001160 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001161 sp<ICameraClient>{nullptr}, id, cameraId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001162 internalPackageName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001163 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Austin Borger18b30a72022-10-27 12:20:29 -07001164 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001165 ).isOk()) {
1166 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001167 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001168 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001169}
1170
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001171Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001172 /*out*/
1173 CameraParameters* parameters) {
1174
1175 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1176
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001177 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001178
1179 if (parameters == NULL) {
1180 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001181 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001182 }
1183
Ruben Brunkcc776712015-02-17 20:18:47 -08001184 String8 id = String8::format("%d", cameraId);
1185
1186 // Check if we already have parameters
1187 {
1188 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001189 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001190 auto cameraState = getCameraState(id);
1191 if (cameraState == nullptr) {
1192 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001193 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1194 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001195 }
1196 CameraParameters p = cameraState->getShimParams();
1197 if (!p.isEmpty()) {
1198 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001199 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001200 }
1201 }
1202
Jayant Chowdhary12361932018-08-27 14:46:13 -07001203 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001204 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001205 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001206 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001207 // Error already logged by callee
1208 return ret;
1209 }
1210
1211 // Check for parameters again
1212 {
1213 // Scope for service lock
1214 Mutex::Autolock lock(mServiceLock);
1215 auto cameraState = getCameraState(id);
1216 if (cameraState == nullptr) {
1217 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001218 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1219 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001220 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001221 CameraParameters p = cameraState->getShimParams();
1222 if (!p.isEmpty()) {
1223 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001224 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001225 }
1226 }
1227
Ruben Brunkcc776712015-02-17 20:18:47 -08001228 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1229 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001230 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001231}
1232
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001233// Can camera service trust the caller based on the calling UID?
1234static bool isTrustedCallingUid(uid_t uid) {
1235 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001236 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001237 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001238 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001239 return true;
1240 default:
1241 return false;
1242 }
1243}
1244
Nicholas Sauera3620332019-04-03 14:05:17 -07001245static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1246 PermissionController pc;
1247 uid = pc.getPackageUid(packageName, 0);
1248 if (uid <= 0) {
1249 ALOGE("Unknown package: '%s'", String8(packageName).string());
1250 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1251 return BAD_VALUE;
1252 }
1253
1254 if (userId < 0) {
1255 ALOGE("Invalid user: %d", userId);
1256 dprintf(err, "Invalid user: %d\n", userId);
1257 return BAD_VALUE;
1258 }
1259
1260 uid = multiuser_get_uid(userId, uid);
1261 return NO_ERROR;
1262}
1263
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001264Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001265 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1266 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001267
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001268#ifdef __BRILLO__
1269 UNUSED(clientName8);
1270 UNUSED(clientUid);
1271 UNUSED(clientPid);
1272 UNUSED(originalClientPid);
1273#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001274 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1275 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001276 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001277 return allowed;
1278 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001279#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001280
Jayant Chowdhary12361932018-08-27 14:46:13 -07001281 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001282
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001283 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001284 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1285 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001286 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1287 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001288 }
1289
Ruben Brunkcc776712015-02-17 20:18:47 -08001290 if (getCameraState(cameraId) == nullptr) {
1291 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1292 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001293 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1294 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001295 }
1296
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001297 status_t err = checkIfDeviceIsUsable(cameraId);
1298 if (err != NO_ERROR) {
1299 switch(err) {
1300 case -ENODEV:
1301 case -EBUSY:
1302 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1303 "No camera device with ID \"%s\" currently available", cameraId.string());
1304 default:
1305 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1306 "Unknown error connecting to ID \"%s\"", cameraId.string());
1307 }
1308 }
1309 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001310}
1311
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001312Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001313 const String8& clientName8, int& clientUid, int& clientPid,
1314 /*out*/int& originalClientPid) const {
Joanne Chung02c13d02023-01-16 12:58:05 +00001315 permission::PermissionChecker permissionChecker;
1316 AttributionSourceState attributionSource{};
1317
Jayant Chowdhary12361932018-08-27 14:46:13 -07001318 int callingPid = CameraThreadState::getCallingPid();
1319 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001320
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001321 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001322 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001323 clientUid = callingUid;
1324 } else if (!isTrustedCallingUid(callingUid)) {
1325 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1326 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001327 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1328 "Untrusted caller (calling PID %d, UID %d) trying to "
1329 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1330 callingPid, callingUid, cameraId.string(),
1331 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001332 }
1333
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001334 // Check if we can trust clientPid
1335 if (clientPid == USE_CALLING_PID) {
1336 clientPid = callingPid;
1337 } else if (!isTrustedCallingUid(callingUid)) {
1338 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1339 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001340 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1341 "Untrusted caller (calling PID %d, UID %d) trying to "
1342 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1343 callingPid, callingUid, cameraId.string(),
1344 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001345 }
1346
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001347 if (shouldRejectSystemCameraConnection(cameraId)) {
1348 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1349 cameraId.c_str());
1350 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1351 "available", cameraId.string());
1352 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001353 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1354 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1355 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1356 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1357 "found while trying to query device kind", cameraId.string());
1358
1359 }
1360
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001361 // If it's not calling from cameraserver, check the permission if the
1362 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1363 // android.permission.SYSTEM_CAMERA for system only camera devices).
Joanne Chung02c13d02023-01-16 12:58:05 +00001364 attributionSource.pid = clientPid;
1365 attributionSource.uid = clientUid;
1366 attributionSource.packageName = clientName8;
1367 bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
1368 sCameraPermission, attributionSource, String16(), AppOpsManager::OP_NONE)
1369 != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001370 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001371 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001372 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001373 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1374 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1375 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001376 }
1377
Svet Ganova453d0d2018-01-11 15:37:58 -08001378 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001379 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001380 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001381 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1382 clientPid, clientUid);
1383 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001384 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1385 "calling UID %d proc state %" PRId32 ")",
1386 clientName8.string(), clientUid, clientPid, cameraId.string(),
1387 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001388 }
1389
Michael Grooverd1d435a2018-12-18 17:39:42 -08001390 // If sensor privacy is enabled then prevent access to the camera
1391 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1392 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1393 return STATUS_ERROR_FMT(ERROR_DISABLED,
1394 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1395 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1396 }
1397
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001398 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1399 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001400 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001401 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001402
Ruben Brunk6267b532015-04-30 17:44:07 -07001403 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001404
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001405 // For non-system clients : Only allow clients who are being used by the current foreground
1406 // device user, unless calling from our own process.
1407 if (!doesClientHaveSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001408 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001409 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1410 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1411 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001412 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1413 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1414 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001415 }
1416
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001417 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001418}
1419
1420status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1421 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001422 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001423 if (cameraState == nullptr) {
1424 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1425 cameraId.string());
1426 return -ENODEV;
1427 }
1428
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001429 StatusInternal currentStatus = cameraState->getStatus();
1430 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001431 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1432 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001433 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001434 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001435 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1436 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001437 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001438 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001439
Ruben Brunkcc776712015-02-17 20:18:47 -08001440 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001441}
1442
Ruben Brunkcc776712015-02-17 20:18:47 -08001443void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001444 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001445
Ruben Brunkcc776712015-02-17 20:18:47 -08001446 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001447 auto clientDescriptor =
1448 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001449 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001450 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1451
1452 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1453 String8(client->getPackageName()));
1454
1455 if (evicted.size() > 0) {
1456 // This should never happen - clients should already have been removed in disconnect
1457 for (auto& i : evicted) {
1458 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1459 __FUNCTION__, i->getKey().string());
1460 }
1461
1462 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1463 __FUNCTION__);
1464 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001465
1466 // And register a death notification for the client callback. Do
1467 // this last to avoid Binder policy where a nested Binder
1468 // transaction might be pre-empted to service the client death
1469 // notification if the client process dies before linkToDeath is
1470 // invoked.
1471 sp<IBinder> remoteCallback = client->getRemote();
1472 if (remoteCallback != nullptr) {
1473 remoteCallback->linkToDeath(this);
1474 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001475}
1476
1477status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1478 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001479 int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001480 /*out*/
1481 sp<BasicClient>* client,
1482 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001483 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001484 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001485 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001486 DescriptorPtr clientDescriptor;
1487 {
1488 if (effectiveApiLevel == API_1) {
1489 // If we are using API1, any existing client for this camera ID with the same remote
1490 // should be returned rather than evicted to allow MediaRecorder to work properly.
1491
1492 auto current = mActiveClientManager.get(cameraId);
1493 if (current != nullptr) {
1494 auto clientSp = current->getValue();
1495 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001496 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001497 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001498 " API level, evicting prior client...");
1499 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001500 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001501 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001502 *client = clientSp;
1503 return NO_ERROR;
1504 }
1505 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001506 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001507 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001508
Ruben Brunkcc776712015-02-17 20:18:47 -08001509 // Get current active client PIDs
1510 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1511 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001512
Emilian Peev8131a262017-02-01 12:33:43 +00001513 std::vector<int> priorityScores(ownerPids.size());
1514 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001515
Emilian Peev8131a262017-02-01 12:33:43 +00001516 // Get priority scores of all active PIDs
1517 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1518 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1519 /*out*/&priorityScores[0]);
1520 if (err != OK) {
1521 ALOGE("%s: Priority score query failed: %d",
1522 __FUNCTION__, err);
1523 return err;
1524 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001525
Ruben Brunkcc776712015-02-17 20:18:47 -08001526 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001527 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001528 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001529 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001530 resource_policy::ClientPriority(priorityScores[i], states[i],
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001531 /* isVendorClient won't get copied over*/ false,
1532 /* oomScoreOffset won't get copied over*/ 0));
Ruben Brunkcc776712015-02-17 20:18:47 -08001533 }
1534 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001535
Ruben Brunkcc776712015-02-17 20:18:47 -08001536 // Get state for the given cameraId
1537 auto state = getCameraState(cameraId);
1538 if (state == nullptr) {
1539 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1540 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001541 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001542 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001543 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001544
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001545 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1546 int32_t actualState = states[states.size() - 1];
1547
1548 // Make descriptor for incoming client. We store the oomScoreOffset
1549 // since we might need it later on new handleEvictionsLocked and
1550 // ProcessInfoService would not take that into account.
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001551 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001552 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001553 state->getConflicting(), actualScore, clientPid, actualState,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001554 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001555
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001556 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1557
Ruben Brunkcc776712015-02-17 20:18:47 -08001558 // Find clients that would be evicted
1559 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1560
1561 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1562 // background, so we cannot do evictions
1563 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1564 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1565 " priority).", clientPid);
1566
1567 sp<BasicClient> clientSp = clientDescriptor->getValue();
1568 String8 curTime = getFormattedCurrentTime();
1569 auto incompatibleClients =
1570 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1571
1572 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001573 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001574 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001575 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001576
1577 for (auto& i : incompatibleClients) {
1578 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001579 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1580 i->getKey().string(),
1581 String8{i->getValue()->getPackageName()}.string(),
1582 i->getOwnerId(), i->getPriority().getScore(),
1583 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001584 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001585 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001586 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001587 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001588 }
1589
1590 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001591 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001592 mEventLog.add(msg);
1593
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001594 auto current = mActiveClientManager.get(cameraId);
1595 if (current != nullptr) {
1596 return -EBUSY; // CAMERA_IN_USE
1597 } else {
1598 return -EUSERS; // MAX_CAMERAS_IN_USE
1599 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001600 }
1601
1602 for (auto& i : evicted) {
1603 sp<BasicClient> clientSp = i->getValue();
1604 if (clientSp.get() == nullptr) {
1605 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1606
1607 // TODO: Remove this
1608 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1609 __FUNCTION__);
1610 mActiveClientManager.remove(i);
1611 continue;
1612 }
1613
1614 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1615 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001616 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001617
Ruben Brunkcc776712015-02-17 20:18:47 -08001618 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001619 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001620 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1621 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001622 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001623 i->getOwnerId(), i->getPriority().getScore(),
1624 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001625 packageName.string(), clientPid, clientPriority.getScore(),
1626 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001627
1628 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001629 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001630 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001631 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001632 }
1633
Ruben Brunkcc776712015-02-17 20:18:47 -08001634 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1635 // other clients from connecting in mServiceLockWrapper if held
1636 mServiceLock.unlock();
1637
1638 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001639 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001640
1641 // Destroy evicted clients
1642 for (auto& i : evictedClients) {
1643 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001644 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001645 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001646
Jayant Chowdhary12361932018-08-27 14:46:13 -07001647 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001648
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001649 for (const auto& i : evictedClients) {
1650 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1651 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1652 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1653 if (ret == TIMED_OUT) {
1654 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1655 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1656 mActiveClientManager.toString().string());
1657 return -EBUSY;
1658 }
1659 if (ret != NO_ERROR) {
1660 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1661 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1662 ret, mActiveClientManager.toString().string());
1663 return ret;
1664 }
1665 }
1666
1667 evictedClients.clear();
1668
Ruben Brunkcc776712015-02-17 20:18:47 -08001669 // Once clients have been disconnected, relock
1670 mServiceLock.lock();
1671
1672 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1673 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1674 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001675 }
1676
Ruben Brunkcc776712015-02-17 20:18:47 -08001677 *partial = clientDescriptor;
1678 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001679}
1680
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001681Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001682 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001683 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001684 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001685 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001686 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001687 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001688 bool overrideToPortrait,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001689 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001690 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001691
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001692 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001693 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001694
1695 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001696 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001697 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001698 clientPackageName,/*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07001699 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
1700 overrideToPortrait, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001701
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001702 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001703 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001704 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001705 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001706 }
1707
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001708 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00001709
1710 const sp<IServiceManager> sm(defaultServiceManager());
1711 const auto& mActivityManager = getActivityManager();
1712 if (mActivityManager) {
1713 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
1714 CameraThreadState::getCallingUid(),
1715 CameraThreadState::getCallingPid());
1716 }
1717
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001718 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001719}
1720
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001721bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1722 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001723 // If the client is not a vendor client, don't add listener if
1724 // a) the camera is a publicly hidden secure camera OR
1725 // b) the camera is a system only camera and the client doesn't
1726 // have android.permission.SYSTEM_CAMERA permissions.
1727 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1728 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1729 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001730 return true;
1731 }
1732 return false;
1733}
1734
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001735bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1736 // Rules for rejection:
1737 // 1) If cameraserver tries to access this camera device, accept the
1738 // connection.
1739 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001740 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001741 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1742 // and the serving thread is a non hwbinder thread, the client must have
1743 // android.permission.SYSTEM_CAMERA permissions to connect.
1744
1745 int cPid = CameraThreadState::getCallingPid();
1746 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001747 bool systemClient = doesClientHaveSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001748 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1749 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001750 // This isn't a known camera ID, so it's not a system camera
1751 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1752 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001753 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001754
1755 // (1) Cameraserver trying to connect, accept.
1756 if (CameraThreadState::getCallingPid() == getpid()) {
1757 return false;
1758 }
1759 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001760 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001761 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1762 return true;
1763 }
1764 // (3) Here we only check for permissions if it is a system only camera device. This is since
1765 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1766 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1767 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001768 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001769 !hasPermissionsForSystemCamera(cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001770 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1771 cameraId.c_str());
1772 return true;
1773 }
1774
1775 return false;
1776}
1777
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001778Status CameraService::connectDevice(
1779 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001780 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001781 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001782 const std::optional<String16>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001783 int clientUid, int oomScoreOffset, int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001784 bool overrideToPortrait,
Ruben Brunkcc776712015-02-17 20:18:47 -08001785 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001786 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001787
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001788 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001789 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001790 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001791 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001792 String16 clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001793 int callingPid = CameraThreadState::getCallingPid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001794 bool systemNativeClient = false;
1795 if (doesClientHaveSystemUid() && (clientPackageNameAdj.size() == 0)) {
1796 std::string systemClient =
1797 StringPrintf("client.pid<%d>", CameraThreadState::getCallingPid());
1798 clientPackageNameAdj = String16(systemClient.c_str());
1799 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001800 }
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001801
1802 if (oomScoreOffset < 0) {
1803 String8 msg =
1804 String8::format("Cannot increase the priority of a client %s pid %d for "
1805 "camera id %s", String8(clientPackageNameAdj).string(), callingPid,
1806 id.string());
1807 ALOGE("%s: %s", __FUNCTION__, msg.string());
1808 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1809 }
1810
Austin Borger9bfa0a72022-08-03 17:50:40 -07001811 userid_t clientUserId = multiuser_get_user_id(clientUid);
1812 int callingUid = CameraThreadState::getCallingUid();
1813 if (clientUid == USE_CALLING_UID) {
1814 clientUserId = multiuser_get_user_id(callingUid);
1815 }
1816
1817 if (mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borger5f7abe22022-04-26 15:55:10 -07001818 String8 msg =
1819 String8::format("Camera disabled by device policy");
1820 ALOGE("%s: %s", __FUNCTION__, msg.string());
1821 return STATUS_ERROR(ERROR_DISABLED, msg.string());
1822 }
1823
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001824 // enforce system camera permissions
1825 if (oomScoreOffset > 0 &&
Austin Borger86a588e2022-05-23 12:41:58 -07001826 !hasPermissionsForSystemCamera(callingPid, CameraThreadState::getCallingUid()) &&
1827 !isTrustedCallingUid(CameraThreadState::getCallingUid())) {
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001828 String8 msg =
1829 String8::format("Cannot change the priority of a client %s pid %d for "
1830 "camera id %s without SYSTEM_CAMERA permissions",
1831 String8(clientPackageNameAdj).string(), callingPid, id.string());
1832 ALOGE("%s: %s", __FUNCTION__, msg.string());
1833 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.string());
1834 }
1835
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001836 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001837 /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient,clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001838 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
Austin Borger18b30a72022-10-27 12:20:29 -07001839 targetSdkVersion, overrideToPortrait, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001840
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001841 if(!ret.isOk()) {
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001842 logRejected(id, callingPid, String8(clientPackageNameAdj), ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001843 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001844 }
1845
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001846 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07001847 Mutex::Autolock lock(mServiceLock);
1848
1849 // Clear the previous cached logs and reposition the
1850 // file offset to beginning of the file to log new data.
1851 // If either truncate or lseek fails, close the previous file and create a new one.
1852 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
1853 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
1854 // Close the previous memfd.
1855 close(mMemFd);
1856 // If failure to wipe the data, then create a new file and
1857 // assign the new value to mMemFd.
1858 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
1859 if (mMemFd == -1) {
1860 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
1861 }
1862 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00001863 const sp<IServiceManager> sm(defaultServiceManager());
1864 const auto& mActivityManager = getActivityManager();
1865 if (mActivityManager) {
1866 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
1867 CameraThreadState::getCallingUid(),
1868 CameraThreadState::getCallingPid());
1869 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001870 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001871}
1872
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001873String16 CameraService::getPackageNameFromUid(int clientUid) {
1874 String16 packageName("");
1875
1876 sp<IServiceManager> sm = defaultServiceManager();
1877 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
1878 if (binder == 0) {
1879 ALOGE("Cannot get permission service");
1880 // Return empty package name and the further interaction
1881 // with camera will likely fail
1882 return packageName;
1883 }
1884
1885 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
1886 Vector<String16> packages;
1887
1888 permCtrl->getPackagesForUid(clientUid, packages);
1889
1890 if (packages.isEmpty()) {
1891 ALOGE("No packages for calling UID %d", clientUid);
1892 // Return empty package name and the further interaction
1893 // with camera will likely fail
1894 return packageName;
1895 }
1896
1897 // Arbitrarily pick the first name in the list
1898 packageName = packages[0];
1899
1900 return packageName;
1901}
1902
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001903template<class CALLBACK, class CLIENT>
1904Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001905 int api1CameraId, const String16& clientPackageNameMaybe, bool systemNativeClient,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001906 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001907 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001908 bool overrideToPortrait, /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001909 binder::Status ret = binder::Status::ok();
1910
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001911 bool isNonSystemNdk = false;
1912 String16 clientPackageName;
1913 if (clientPackageNameMaybe.size() <= 0) {
1914 // NDK calls don't come with package names, but we need one for various cases.
1915 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
1916 // do exist. For all authentication cases, all packages under the same UID get the
1917 // same permissions, so picking any associated package name is sufficient. For some
1918 // other cases, this may give inaccurate names for clients in logs.
1919 isNonSystemNdk = true;
1920 int packageUid = (clientUid == USE_CALLING_UID) ?
1921 CameraThreadState::getCallingUid() : clientUid;
1922 clientPackageName = getPackageNameFromUid(packageUid);
1923 } else {
1924 clientPackageName = clientPackageNameMaybe;
1925 }
1926
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001927 String8 clientName8(clientPackageName);
1928
1929 int originalClientPid = 0;
1930
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001931 int packagePid = (clientPid == USE_CALLING_PID) ?
1932 CameraThreadState::getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001933 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001934 "Camera API version %d", packagePid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001935 static_cast<int>(effectiveApiLevel));
1936
Shuzhen Wang316781a2020-08-18 18:11:01 -07001937 nsecs_t openTimeNs = systemTime();
1938
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001939 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001940 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07001941 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001942
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001943 {
1944 // Acquire mServiceLock and prevent other clients from connecting
1945 std::unique_ptr<AutoConditionLock> lock =
1946 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1947
1948 if (lock == nullptr) {
1949 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1950 , clientPid);
1951 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1952 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1953 cameraId.string(), clientName8.string(), clientPid);
1954 }
1955
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001956 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001957 if(!(ret = validateConnectLocked(cameraId, clientName8,
1958 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1959 return ret;
1960 }
1961
1962 // Check the shim parameters after acquiring lock, if they have already been updated and
1963 // we were doing a shim update, return immediately
1964 if (shimUpdateOnly) {
1965 auto cameraState = getCameraState(cameraId);
1966 if (cameraState != nullptr) {
1967 if (!cameraState->getShimParams().isEmpty()) return ret;
1968 }
1969 }
1970
1971 status_t err;
1972
1973 sp<BasicClient> clientTmp = nullptr;
1974 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1975 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001976 IInterface::asBinder(cameraCb), clientName8, oomScoreOffset, systemNativeClient,
1977 /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001978 switch (err) {
1979 case -ENODEV:
1980 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1981 "No camera device with ID \"%s\" currently available",
1982 cameraId.string());
1983 case -EBUSY:
1984 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1985 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1986 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001987 case -EUSERS:
1988 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1989 "Too many cameras already open, cannot open camera \"%s\"",
1990 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001991 default:
1992 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1993 "Unexpected error %s (%d) opening camera \"%s\"",
1994 strerror(-err), err, cameraId.string());
1995 }
1996 }
1997
1998 if (clientTmp.get() != nullptr) {
1999 // Handle special case for API1 MediaRecorder where the existing client is returned
2000 device = static_cast<CLIENT*>(clientTmp.get());
2001 return ret;
2002 }
2003
2004 // give flashlight a chance to close devices if necessary.
2005 mFlashlight->prepareDeviceOpen(cameraId);
2006
Austin Borger18b30a72022-10-27 12:20:29 -07002007 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002008 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07002009 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
2010 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002011 if (facing == -1) {
2012 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
2013 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2014 "Unable to get camera device \"%s\" facing", cameraId.string());
2015 }
2016
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002017 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002018 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
2019 mPerfClassPrimaryCameraIds, cameraId.string(), targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002020 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
2021 clientFeatureId, cameraId, api1CameraId, facing, orientation,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07002022 clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002023 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
Austin Borger18b30a72022-10-27 12:20:29 -07002024 overrideToPortrait, /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002025 return ret;
2026 }
2027 client = static_cast<CLIENT*>(tmp.get());
2028
2029 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2030 __FUNCTION__);
2031
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002032 String8 monitorTags = isClientWatched(client.get()) ? mMonitorTags : String8("");
2033 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002034 if (err != OK) {
2035 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002036 // Errors could be from the HAL module open call or from AppOpsManager
2037 switch(err) {
2038 case BAD_VALUE:
2039 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2040 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
2041 case -EBUSY:
2042 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2043 "Camera \"%s\" is already open", cameraId.string());
2044 case -EUSERS:
2045 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2046 "Too many cameras already open, cannot open camera \"%s\"",
2047 cameraId.string());
2048 case PERMISSION_DENIED:
2049 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2050 "No permission to open camera \"%s\"", cameraId.string());
2051 case -EACCES:
2052 return STATUS_ERROR_FMT(ERROR_DISABLED,
2053 "Camera \"%s\" disabled by policy", cameraId.string());
2054 case -ENODEV:
2055 default:
2056 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2057 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
2058 strerror(-err), err);
2059 }
2060 }
2061
2062 // Update shim paremeters for legacy clients
2063 if (effectiveApiLevel == API_1) {
2064 // Assume we have always received a Client subclass for API1
2065 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2066 String8 rawParams = shimClient->getParameters();
2067 CameraParameters params(rawParams);
2068
2069 auto cameraState = getCameraState(cameraId);
2070 if (cameraState != nullptr) {
2071 cameraState->setShimParams(params);
2072 } else {
2073 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
2074 __FUNCTION__, cameraId.string());
2075 }
2076 }
2077
Ravneetaeb20dc2022-03-30 05:33:03 +00002078 // Enable/disable camera service watchdog
2079 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2080
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002081 // Set rotate-and-crop override behavior
2082 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2083 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Austin Borger18b30a72022-10-27 12:20:29 -07002084 } else if (overrideToPortrait && portraitRotation != 0) {
2085 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2086 switch (portraitRotation) {
2087 case 90:
2088 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2089 break;
2090 case 180:
2091 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2092 break;
2093 case 270:
2094 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2095 break;
2096 default:
2097 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2098 break;
2099 }
2100 client->setRotateAndCropOverride(rotateAndCropMode);
Emilian Peev13f35ad2022-04-27 11:28:48 -07002101 } else {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002102 client->setRotateAndCropOverride(
2103 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2104 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2105 }
2106
2107 // Set autoframing override behaviour
2108 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2109 client->setAutoframingOverride(mOverrideAutoframingMode);
2110 } else {
2111 client->setAutoframingOverride(
2112 mCameraServiceProxyWrapper->getAutoframingOverride(
2113 clientPackageName));
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002114 }
2115
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002116 // Set camera muting behavior
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002117 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08002118 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002119 if (client->supportsCameraMute()) {
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002120 client->setCameraMute(
2121 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2122 } else if (isCameraPrivacyEnabled) {
2123 // no camera mute supported, but privacy is on! => disconnect
2124 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2125 String8(client->getPackageName()).string(), cameraId.string());
2126 // Do not hold mServiceLock while disconnecting clients, but
2127 // retain the condition blocking other clients from connecting
2128 // in mServiceLockWrapper if held.
2129 mServiceLock.unlock();
2130 // Clear caller identity temporarily so client disconnect PID
2131 // checks work correctly
2132 int64_t token = CameraThreadState::clearCallingIdentity();
2133 // Note AppOp to trigger the "Unblock" dialog
2134 client->noteAppOp();
2135 client->disconnect();
2136 CameraThreadState::restoreCallingIdentity(token);
2137 // Reacquire mServiceLock
2138 mServiceLock.lock();
2139
2140 return STATUS_ERROR_FMT(ERROR_DISABLED,
2141 "Camera \"%s\" disabled due to camera mute", cameraId.string());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002142 }
2143
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002144 if (shimUpdateOnly) {
2145 // If only updating legacy shim parameters, immediately disconnect client
2146 mServiceLock.unlock();
2147 client->disconnect();
2148 mServiceLock.lock();
2149 } else {
2150 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002151 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002152 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002153
2154 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002155 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002156 } // lock is destroyed, allow further connect calls
2157
2158 // Important: release the mutex here so the client can call back into the service from its
2159 // destructor (can be at the end of the call)
2160 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002161
2162 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002163 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002164 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002165
Cliff Wud3a05312021-04-26 23:07:31 +08002166 {
2167 Mutex::Autolock lock(mInjectionParametersLock);
2168 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2169 mInjectionInitPending = false;
2170 status_t res = NO_ERROR;
2171 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2172 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002173 sp<BasicClient> clientSp = clientDescriptor->getValue();
2174 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2175 if(res != OK) {
2176 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2177 "No camera device with ID \"%s\" currently available",
2178 mInjectionExternalCamId.string());
2179 }
2180 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002181 if (res != OK) {
2182 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2183 }
2184 } else {
2185 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
2186 __FUNCTION__, mInjectionInternalCamId.string());
2187 res = NO_INIT;
2188 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2189 }
2190 }
2191 }
2192
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002193 return ret;
2194}
2195
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002196status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
2197 if (offlineClient.get() == nullptr) {
2198 return BAD_VALUE;
2199 }
2200
2201 {
2202 // Acquire mServiceLock and prevent other clients from connecting
2203 std::unique_ptr<AutoConditionLock> lock =
2204 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2205
2206 if (lock == nullptr) {
2207 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2208 , __FUNCTION__, offlineClient->getClientPid());
2209 return TIMED_OUT;
2210 }
2211
2212 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2213 if (onlineClientDesc.get() == nullptr) {
2214 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2215 cameraId.c_str());
2216 return BAD_VALUE;
2217 }
2218
2219 // Offline clients do not evict or conflict with other online devices. Resource sharing
2220 // conflicts are handled by the camera provider which will either succeed or fail before
2221 // reaching this method.
2222 const auto& onlinePriority = onlineClientDesc->getPriority();
2223 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2224 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
2225 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002226 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002227 // native clients don't have offline processing support.
2228 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002229 if (offlineClientDesc == nullptr) {
2230 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2231 return BAD_VALUE;
2232 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002233
2234 // Allow only one offline device per camera
2235 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2236 if (!incompatibleClients.empty()) {
2237 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2238 return BAD_VALUE;
2239 }
2240
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002241 String8 monitorTags = isClientWatched(offlineClient.get()) ? mMonitorTags : String8("");
2242 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002243 if (err != OK) {
2244 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2245 return err;
2246 }
2247
2248 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2249 if (evicted.size() > 0) {
2250 for (auto& i : evicted) {
2251 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
2252 __FUNCTION__, i->getKey().string());
2253 }
2254
2255 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2256 "properly", __FUNCTION__);
2257
2258 return BAD_VALUE;
2259 }
2260
2261 logConnectedOffline(offlineClientDesc->getKey(),
2262 static_cast<int>(offlineClientDesc->getOwnerId()),
2263 String8(offlineClient->getPackageName()));
2264
2265 sp<IBinder> remoteCallback = offlineClient->getRemote();
2266 if (remoteCallback != nullptr) {
2267 remoteCallback->linkToDeath(this);
2268 }
2269 } // lock is destroyed, allow further connect calls
2270
2271 return OK;
2272}
2273
Rucha Katakwar38284522021-11-10 11:25:21 -08002274Status CameraService::turnOnTorchWithStrengthLevel(const String16& cameraId, int32_t torchStrength,
2275 const sp<IBinder>& clientBinder) {
2276 Mutex::Autolock lock(mServiceLock);
2277
2278 ATRACE_CALL();
2279 if (clientBinder == nullptr) {
2280 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2281 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2282 "Torch client binder in null.");
2283 }
2284
2285 String8 id = String8(cameraId.string());
2286 int uid = CameraThreadState::getCallingUid();
2287
2288 if (shouldRejectSystemCameraConnection(id)) {
2289 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
2290 "for system only device %s: ", id.string());
2291 }
2292
2293 // verify id is valid
2294 auto state = getCameraState(id);
2295 if (state == nullptr) {
2296 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
2297 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2298 "Camera ID \"%s\" is a not valid camera ID", id.string());
2299 }
2300
2301 StatusInternal cameraStatus = state->getStatus();
2302 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2303 cameraStatus != StatusInternal::PRESENT) {
2304 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(),
2305 (int)cameraStatus);
2306 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2307 "Camera ID \"%s\" is a not valid camera ID", id.string());
2308 }
2309
2310 {
2311 Mutex::Autolock al(mTorchStatusMutex);
2312 TorchModeStatus status;
2313 status_t err = getTorchStatusLocked(id, &status);
2314 if (err != OK) {
2315 if (err == NAME_NOT_FOUND) {
2316 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2317 "Camera \"%s\" does not have a flash unit", id.string());
2318 }
2319 ALOGE("%s: getting current torch status failed for camera %s",
2320 __FUNCTION__, id.string());
2321 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2322 "Error changing torch strength level for camera \"%s\": %s (%d)",
2323 id.string(), strerror(-err), err);
2324 }
2325
2326 if (status == TorchModeStatus::NOT_AVAILABLE) {
2327 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2328 ALOGE("%s: torch mode of camera %s is not available because "
2329 "camera is in use.", __FUNCTION__, id.string());
2330 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2331 "Torch for camera \"%s\" is not available due to an existing camera user",
2332 id.string());
2333 } else {
2334 ALOGE("%s: torch mode of camera %s is not available due to "
2335 "insufficient resources", __FUNCTION__, id.string());
2336 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2337 "Torch for camera \"%s\" is not available due to insufficient resources",
2338 id.string());
2339 }
2340 }
2341 }
2342
2343 {
2344 Mutex::Autolock al(mTorchUidMapMutex);
2345 updateTorchUidMapLocked(cameraId, uid);
2346 }
2347 // Check if the current torch strength level is same as the new one.
2348 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
2349 id.string(), torchStrength);
2350
2351 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(id, torchStrength);
2352
2353 if (err != OK) {
2354 int32_t errorCode;
2355 String8 msg;
2356 switch (err) {
2357 case -ENOSYS:
2358 msg = String8::format("Camera \"%s\" has no flashlight.",
2359 id.string());
2360 errorCode = ERROR_ILLEGAL_ARGUMENT;
2361 break;
2362 case -EBUSY:
2363 msg = String8::format("Camera \"%s\" is in use",
2364 id.string());
2365 errorCode = ERROR_CAMERA_IN_USE;
2366 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002367 case -EINVAL:
2368 msg = String8::format("Torch strength level %d is not within the "
2369 "valid range.", torchStrength);
2370 errorCode = ERROR_ILLEGAL_ARGUMENT;
2371 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002372 default:
2373 msg = String8::format("Changing torch strength level failed.");
2374 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002375 }
2376 ALOGE("%s: %s", __FUNCTION__, msg.string());
2377 return STATUS_ERROR(errorCode, msg.string());
2378 }
2379
2380 {
2381 // update the link to client's death
2382 // Store the last client that turns on each camera's torch mode.
2383 Mutex::Autolock al(mTorchClientMapMutex);
2384 ssize_t index = mTorchClientMap.indexOfKey(id);
2385 if (index == NAME_NOT_FOUND) {
2386 mTorchClientMap.add(id, clientBinder);
2387 } else {
2388 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2389 mTorchClientMap.replaceValueAt(index, clientBinder);
2390 }
2391 clientBinder->linkToDeath(this);
2392 }
2393
2394 int clientPid = CameraThreadState::getCallingPid();
2395 const char *id_cstr = id.c_str();
2396 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
2397 __FUNCTION__, id_cstr, torchStrength, clientPid);
2398 if (!shouldSkipTorchStrengthUpdates) {
2399 broadcastTorchStrengthLevel(id, torchStrength);
2400 }
2401 return Status::ok();
2402}
2403
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002404Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002405 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002406 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002407
2408 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002409 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002410 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002411 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2412 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002413 }
2414
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002415 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07002416 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002417
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002418 if (shouldRejectSystemCameraConnection(id)) {
2419 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
2420 " for system only device %s: ", id.string());
2421 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002422 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08002423 auto state = getCameraState(id);
2424 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002425 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002426 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2427 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002428 }
2429
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002430 StatusInternal cameraStatus = state->getStatus();
2431 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002432 cameraStatus != StatusInternal::NOT_AVAILABLE) {
2433 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002434 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2435 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002436 }
2437
2438 {
2439 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002440 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002441 status_t err = getTorchStatusLocked(id, &status);
2442 if (err != OK) {
2443 if (err == NAME_NOT_FOUND) {
2444 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2445 "Camera \"%s\" does not have a flash unit", id.string());
2446 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002447 ALOGE("%s: getting current torch status failed for camera %s",
2448 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002449 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2450 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
2451 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002452 }
2453
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002454 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002455 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002456 ALOGE("%s: torch mode of camera %s is not available because "
2457 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002458 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2459 "Torch for camera \"%s\" is not available due to an existing camera user",
2460 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002461 } else {
2462 ALOGE("%s: torch mode of camera %s is not available due to "
2463 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002464 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2465 "Torch for camera \"%s\" is not available due to insufficient resources",
2466 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002467 }
2468 }
2469 }
2470
Ruben Brunk99e69712015-05-26 17:25:07 -07002471 {
2472 // Update UID map - this is used in the torch status changed callbacks, so must be done
2473 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002474 Mutex::Autolock al(mTorchUidMapMutex);
Rucha Katakwar38284522021-11-10 11:25:21 -08002475 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07002476 }
2477
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002478 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002479
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002480 if (err != OK) {
2481 int32_t errorCode;
2482 String8 msg;
2483 switch (err) {
2484 case -ENOSYS:
2485 msg = String8::format("Camera \"%s\" has no flashlight",
2486 id.string());
2487 errorCode = ERROR_ILLEGAL_ARGUMENT;
2488 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08002489 case -EBUSY:
2490 msg = String8::format("Camera \"%s\" is in use",
2491 id.string());
2492 errorCode = ERROR_CAMERA_IN_USE;
2493 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002494 default:
2495 msg = String8::format(
2496 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
2497 id.string(), enabled, strerror(-err), err);
2498 errorCode = ERROR_INVALID_OPERATION;
2499 }
2500 ALOGE("%s: %s", __FUNCTION__, msg.string());
Rucha Katakward9ea6452021-05-06 11:57:16 -07002501 logServiceError(msg,errorCode);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002502 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002503 }
2504
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002505 {
2506 // update the link to client's death
2507 Mutex::Autolock al(mTorchClientMapMutex);
2508 ssize_t index = mTorchClientMap.indexOfKey(id);
2509 if (enabled) {
2510 if (index == NAME_NOT_FOUND) {
2511 mTorchClientMap.add(id, clientBinder);
2512 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07002513 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002514 mTorchClientMap.replaceValueAt(index, clientBinder);
2515 }
2516 clientBinder->linkToDeath(this);
2517 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07002518 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002519 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002520 }
2521
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002522 int clientPid = CameraThreadState::getCallingPid();
2523 const char *id_cstr = id.c_str();
2524 const char *torchState = enabled ? "on" : "off";
2525 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
2526 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002527 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002528}
2529
Rucha Katakwar38284522021-11-10 11:25:21 -08002530void CameraService::updateTorchUidMapLocked(const String16& cameraId, int uid) {
2531 String8 id = String8(cameraId.string());
2532 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
2533 mTorchUidMap[id].first = uid;
2534 mTorchUidMap[id].second = uid;
2535 } else {
2536 // Set the pending UID
2537 mTorchUidMap[id].first = uid;
2538 }
2539}
2540
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002541Status CameraService::notifySystemEvent(int32_t eventId,
2542 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002543 const int pid = CameraThreadState::getCallingPid();
2544 const int selfPid = getpid();
2545
2546 // Permission checks
2547 if (pid != selfPid) {
2548 // Ensure we're being called by system_server, or similar process with
2549 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002550 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002551 const int uid = CameraThreadState::getCallingUid();
2552 ALOGE("Permission Denial: cannot send updates to camera service about system"
2553 " events from pid=%d, uid=%d", pid, uid);
2554 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09002555 "No permission to send updates to camera service about system events"
2556 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002557 }
2558 }
2559
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002560 ATRACE_CALL();
2561
Ruben Brunk36597b22015-03-20 22:15:57 -07002562 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002563 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002564 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002565 // from a system server crash
2566 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002567 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002568 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002569 break;
2570 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02002571 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
2572 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
2573 // Notify CameraProviderManager for lazy HALs
2574 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
2575 std::to_string(args[0]));
2576 break;
2577 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002578 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002579 default: {
2580 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2581 eventId);
2582 break;
2583 }
2584 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002585 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002586}
2587
Emilian Peev53722fa2019-02-22 17:47:20 -08002588void CameraService::notifyMonitoredUids() {
2589 Mutex::Autolock lock(mStatusListenerLock);
2590
2591 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002592 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07002593 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
2594 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08002595 }
2596}
2597
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002598Status CameraService::notifyDeviceStateChange(int64_t newState) {
2599 const int pid = CameraThreadState::getCallingPid();
2600 const int selfPid = getpid();
2601
2602 // Permission checks
2603 if (pid != selfPid) {
2604 // Ensure we're being called by system_server, or similar process with
2605 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002606 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002607 const int uid = CameraThreadState::getCallingUid();
2608 ALOGE("Permission Denial: cannot send updates to camera service about device"
2609 " state changes from pid=%d, uid=%d", pid, uid);
2610 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2611 "No permission to send updates to camera service about device state"
2612 " changes from pid=%d, uid=%d", pid, uid);
2613 }
2614 }
2615
2616 ATRACE_CALL();
2617
Austin Borger18b30a72022-10-27 12:20:29 -07002618 {
2619 Mutex::Autolock lock(mServiceLock);
2620 mDeviceState = newState;
2621 }
2622
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07002623 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002624
2625 return Status::ok();
2626}
2627
Emilian Peev8b64f282021-03-25 16:49:57 -07002628Status CameraService::notifyDisplayConfigurationChange() {
2629 ATRACE_CALL();
2630 const int callingPid = CameraThreadState::getCallingPid();
2631 const int selfPid = getpid();
2632
2633 // Permission checks
2634 if (callingPid != selfPid) {
2635 // Ensure we're being called by system_server, or similar process with
2636 // permissions to notify the camera service about system events
2637 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2638 const int uid = CameraThreadState::getCallingUid();
2639 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2640 " changes from pid=%d, uid=%d", callingPid, uid);
2641 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2642 "No permission to send updates to camera service about orientation"
2643 " changes from pid=%d, uid=%d", callingPid, uid);
2644 }
2645 }
2646
2647 Mutex::Autolock lock(mServiceLock);
2648
2649 // Don't do anything if rotate-and-crop override via cmd is active
2650 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2651
2652 const auto clients = mActiveClientManager.getAll();
2653 for (auto& current : clients) {
2654 if (current != nullptr) {
2655 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07002656 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
2657 basicClient->setRotateAndCropOverride(
2658 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2659 basicClient->getPackageName(),
2660 basicClient->getCameraFacing(),
2661 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07002662 }
2663 }
2664 }
2665
2666 return Status::ok();
2667}
2668
2669Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002670 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2671 ATRACE_CALL();
2672 if (!concurrentCameraIds) {
2673 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2674 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2675 }
2676
2677 if (!mInitialized) {
2678 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002679 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002680 return STATUS_ERROR(ERROR_DISCONNECTED,
2681 "Camera subsystem is not available");
2682 }
2683 // First call into the provider and get the set of concurrent camera
2684 // combinations
2685 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002686 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002687 for (auto &combination : concurrentCameraCombinations) {
2688 std::vector<std::string> validCombination;
2689 for (auto &cameraId : combination) {
2690 // if the camera state is not present, skip
2691 String8 cameraIdStr(cameraId.c_str());
2692 auto state = getCameraState(cameraIdStr);
2693 if (state == nullptr) {
2694 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2695 continue;
2696 }
2697 StatusInternal status = state->getStatus();
2698 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2699 continue;
2700 }
2701 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2702 continue;
2703 }
2704 validCombination.push_back(cameraId);
2705 }
2706 if (validCombination.size() != 0) {
2707 concurrentCameraIds->push_back(std::move(validCombination));
2708 }
2709 }
2710 return Status::ok();
2711}
2712
2713Status CameraService::isConcurrentSessionConfigurationSupported(
2714 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002715 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002716 if (!isSupported) {
2717 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2718 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2719 }
2720
2721 if (!mInitialized) {
2722 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2723 return STATUS_ERROR(ERROR_DISCONNECTED,
2724 "Camera subsystem is not available");
2725 }
2726
2727 // Check for camera permissions
2728 int callingPid = CameraThreadState::getCallingPid();
2729 int callingUid = CameraThreadState::getCallingUid();
Joanne Chung02c13d02023-01-16 12:58:05 +00002730 permission::PermissionChecker permissionChecker;
2731 AttributionSourceState attributionSource{};
2732 attributionSource.pid = callingPid;
2733 attributionSource.uid = callingUid;
2734 bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
2735 sCameraPermission, attributionSource, String16(), AppOpsManager::OP_NONE)
2736 != permission::PermissionChecker::PERMISSION_HARD_DENIED;
2737 if ((callingPid != getpid()) && !checkPermissionForCamera) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002738 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2739 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2740 "android.permission.CAMERA needed to call"
2741 "isConcurrentSessionConfigurationSupported");
2742 }
2743
2744 status_t res =
2745 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002746 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
2747 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002748 if (res != OK) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07002749 logServiceError(String8::format("Unable to query session configuration support"),
2750 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002751 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2752 "support %s (%d)", strerror(-res), res);
2753 }
2754 return Status::ok();
2755}
2756
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002757Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2758 /*out*/
2759 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002760 return addListenerHelper(listener, cameraStatuses);
2761}
2762
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002763binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2764 std::vector<hardware::CameraStatus>* cameraStatuses) {
2765 return addListenerHelper(listener, cameraStatuses, false, true);
2766}
2767
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002768Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2769 /*out*/
2770 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002771 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002772
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002773 ATRACE_CALL();
2774
Igor Murashkinbfc99152013-02-27 12:55:20 -08002775 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002776
Ruben Brunk3450ba72015-06-16 11:00:37 -07002777 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002778 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002779 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002780 }
2781
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002782 auto clientUid = CameraThreadState::getCallingUid();
2783 auto clientPid = CameraThreadState::getCallingPid();
Joanne Chung02c13d02023-01-16 12:58:05 +00002784 permission::PermissionChecker permissionChecker;
2785 AttributionSourceState attributionSource{};
2786 attributionSource.uid = clientUid;
2787 attributionSource.pid = clientPid;
2788 bool openCloseCallbackAllowed = permissionChecker.checkPermissionForPreflight(
2789 sCameraOpenCloseListenerPermission, attributionSource, String16(),
2790 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002791
Igor Murashkinbfc99152013-02-27 12:55:20 -08002792 Mutex::Autolock lock(mServiceLock);
2793
Ruben Brunkcc776712015-02-17 20:18:47 -08002794 {
2795 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002796 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002797 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002798 ALOGW("%s: Tried to add listener %p which was already subscribed",
2799 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002800 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002801 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002802 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002803
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002804 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002805 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2806 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002807 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08002808 if (ret != NO_ERROR) {
2809 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2810 strerror(-ret), ret);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002811 logServiceError(msg,ERROR_ILLEGAL_ARGUMENT);
Emilian Peev53722fa2019-02-22 17:47:20 -08002812 ALOGE("%s: %s", __FUNCTION__, msg.string());
2813 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2814 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002815 // The listener still needs to be added to the list of listeners, regardless of what
2816 // permissions the listener process has / whether it is a vendor listener. Since it might be
2817 // eligible to listen to other camera ids.
2818 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002819 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002820 }
2821
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002822 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002823 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002824 Mutex::Autolock lock(mCameraStatesLock);
2825 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002826 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07002827 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
2828 openCloseCallbackAllowed ? i.second->getClientPackage() : String8::empty());
Igor Murashkincba2c162013-03-20 15:56:31 -07002829 }
2830 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002831 // Remove the camera statuses that should be hidden from the client, we do
2832 // this after collecting the states in order to avoid holding
2833 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2834 // the same time.
2835 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2836 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2837 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2838 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2839 ALOGE("%s: Invalid camera id %s, skipping status update",
2840 __FUNCTION__, s.cameraId.c_str());
2841 return true;
2842 }
2843 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2844 clientUid);}), cameraStatuses->end());
2845
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002846 //cameraStatuses will have non-eligible camera ids removed.
2847 std::set<String16> idsChosenForCallback;
2848 for (const auto &s : *cameraStatuses) {
2849 idsChosenForCallback.insert(String16(s.cameraId));
2850 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002851
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002852 /*
2853 * Immediately signal current torch status to this listener only
2854 * This may be a subset of all the devices, so don't include it in the response directly
2855 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002856 {
2857 Mutex::Autolock al(mTorchStatusMutex);
2858 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002859 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002860 // The camera id is visible to the client. Fine to send torch
2861 // callback.
2862 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2863 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2864 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002865 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002866 }
2867
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002868 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002869}
Ruben Brunkcc776712015-02-17 20:18:47 -08002870
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002871Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002872 ATRACE_CALL();
2873
Igor Murashkinbfc99152013-02-27 12:55:20 -08002874 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2875
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002876 if (listener == 0) {
2877 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002878 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002879 }
2880
Igor Murashkinbfc99152013-02-27 12:55:20 -08002881 Mutex::Autolock lock(mServiceLock);
2882
Ruben Brunkcc776712015-02-17 20:18:47 -08002883 {
2884 Mutex::Autolock lock(mStatusListenerLock);
2885 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002886 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2887 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2888 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002889 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002890 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002891 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002892 }
2893 }
2894
2895 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2896 __FUNCTION__, listener.get());
2897
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002898 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002899}
2900
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002901Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002902
2903 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002904 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2905
2906 if (parameters == NULL) {
2907 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002908 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002909 }
2910
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002911 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002912
2913 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002914 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002915 // Error logged by caller
2916 return ret;
2917 }
2918
2919 String8 shimParamsString8 = shimParams.flatten();
2920 String16 shimParamsString16 = String16(shimParamsString8);
2921
2922 *parameters = shimParamsString16;
2923
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002924 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002925}
2926
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002927Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2928 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002929 ATRACE_CALL();
2930
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002931 const String8 id = String8(cameraId);
2932
2933 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002934
2935 switch (apiVersion) {
2936 case API_VERSION_1:
2937 case API_VERSION_2:
2938 break;
2939 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002940 String8 msg = String8::format("Unknown API version %d", apiVersion);
2941 ALOGE("%s: %s", __FUNCTION__, msg.string());
2942 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002943 }
2944
Austin Borger18b30a72022-10-27 12:20:29 -07002945 int portraitRotation;
2946 auto deviceVersionAndTransport = getDeviceVersion(id, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002947 if (deviceVersionAndTransport.first == -1) {
2948 String8 msg = String8::format("Unknown camera ID %s", id.string());
2949 ALOGE("%s: %s", __FUNCTION__, msg.string());
2950 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2951 }
2952 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
2953 int deviceVersion = deviceVersionAndTransport.first;
2954 switch (deviceVersion) {
2955 case CAMERA_DEVICE_API_VERSION_1_0:
2956 case CAMERA_DEVICE_API_VERSION_3_0:
2957 case CAMERA_DEVICE_API_VERSION_3_1:
2958 if (apiVersion == API_VERSION_2) {
2959 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
2960 "shim", __FUNCTION__, id.string(), deviceVersion);
2961 *isSupported = false;
2962 } else { // if (apiVersion == API_VERSION_1) {
2963 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
2964 "supported", __FUNCTION__, id.string());
2965 *isSupported = true;
2966 }
2967 break;
2968 case CAMERA_DEVICE_API_VERSION_3_2:
2969 case CAMERA_DEVICE_API_VERSION_3_3:
2970 case CAMERA_DEVICE_API_VERSION_3_4:
2971 case CAMERA_DEVICE_API_VERSION_3_5:
2972 case CAMERA_DEVICE_API_VERSION_3_6:
2973 case CAMERA_DEVICE_API_VERSION_3_7:
2974 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002975 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002976 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002977 break;
2978 default: {
2979 String8 msg = String8::format("Unknown device version %x for device %s",
2980 deviceVersion, id.string());
2981 ALOGE("%s: %s", __FUNCTION__, msg.string());
2982 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002983 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002984 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002985 } else {
2986 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002987 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002988 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002989}
2990
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002991Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2992 /*out*/ bool *isSupported) {
2993 ATRACE_CALL();
2994
2995 const String8 id = String8(cameraId);
2996
2997 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2998 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2999
3000 return Status::ok();
3001}
3002
Cliff Wud8cae102021-03-11 01:37:42 +08003003Status CameraService::injectCamera(
3004 const String16& packageName, const String16& internalCamId,
3005 const String16& externalCamId,
3006 const sp<ICameraInjectionCallback>& callback,
3007 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003008 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003009 ATRACE_CALL();
3010
3011 if (!checkCallingPermission(sCameraInjectExternalCameraPermission)) {
3012 const int pid = CameraThreadState::getCallingPid();
3013 const int uid = CameraThreadState::getCallingUid();
3014 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3015 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3016 "Permission Denial: no permission to inject camera");
3017 }
3018
3019 ALOGV(
3020 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3021 "%s",
3022 __FUNCTION__, String8(packageName).string(),
3023 String8(internalCamId).string(), String8(externalCamId).string());
3024
Cliff Wud3a05312021-04-26 23:07:31 +08003025 {
3026 Mutex::Autolock lock(mInjectionParametersLock);
3027 mInjectionInternalCamId = String8(internalCamId);
3028 mInjectionExternalCamId = String8(externalCamId);
Cliff Wu646bd612021-11-23 23:21:29 +08003029 mInjectionStatusListener->addListener(callback);
3030 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003031 status_t res = NO_ERROR;
3032 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3033 // If the client already exists, we can directly connect to the camera device through the
3034 // client's injectCamera(), otherwise we need to wait until the client is established
3035 // (execute connectHelper()) before injecting the camera to the camera device.
3036 if (clientDescriptor != nullptr) {
3037 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003038 sp<BasicClient> clientSp = clientDescriptor->getValue();
3039 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3040 if(res != OK) {
3041 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3042 "No camera device with ID \"%s\" currently available",
3043 mInjectionExternalCamId.string());
3044 }
3045 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08003046 if(res != OK) {
3047 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3048 }
3049 } else {
3050 mInjectionInitPending = true;
3051 }
3052 }
Cliff Wud8cae102021-03-11 01:37:42 +08003053
Cliff Wud3a05312021-04-26 23:07:31 +08003054 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003055}
3056
Ruben Brunkcc776712015-02-17 20:18:47 -08003057void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003058 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003059 for (auto& i : mActiveClientManager.getAll()) {
3060 auto clientSp = i->getValue();
3061 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003062 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003063 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003064 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003065 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003066 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003067}
3068
Ruben Brunkcc776712015-02-17 20:18:47 -08003069bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003070 bool ret = false;
3071 {
3072 // Acquire mServiceLock and prevent other clients from connecting
3073 std::unique_ptr<AutoConditionLock> lock =
3074 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003075
Igor Murashkin634a5152013-02-20 17:15:11 -08003076
Ruben Brunkcc776712015-02-17 20:18:47 -08003077 std::vector<sp<BasicClient>> evicted;
3078 for (auto& i : mActiveClientManager.getAll()) {
3079 auto clientSp = i->getValue();
3080 if (clientSp.get() == nullptr) {
3081 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3082 mActiveClientManager.remove(i);
3083 continue;
3084 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003085 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003086 mActiveClientManager.remove(i);
3087 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003088
Ruben Brunkcc776712015-02-17 20:18:47 -08003089 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003090 clientSp->notifyError(
3091 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003092 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003093 }
3094 }
3095
Ruben Brunkcc776712015-02-17 20:18:47 -08003096 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3097 // other clients from connecting in mServiceLockWrapper if held
3098 mServiceLock.unlock();
3099
Ruben Brunk36597b22015-03-20 22:15:57 -07003100 // Do not clear caller identity, remote caller should be client proccess
3101
Ruben Brunkcc776712015-02-17 20:18:47 -08003102 for (auto& i : evicted) {
3103 if (i.get() != nullptr) {
3104 i->disconnect();
3105 ret = true;
3106 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003107 }
3108
Ruben Brunkcc776712015-02-17 20:18:47 -08003109 // Reacquire mServiceLock
3110 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003111
Ruben Brunkcc776712015-02-17 20:18:47 -08003112 } // lock is destroyed, allow further connect calls
3113
3114 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003115}
3116
Ruben Brunkcc776712015-02-17 20:18:47 -08003117std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
3118 const String8& cameraId) const {
3119 std::shared_ptr<CameraState> state;
3120 {
3121 Mutex::Autolock lock(mCameraStatesLock);
3122 auto iter = mCameraStates.find(cameraId);
3123 if (iter != mCameraStates.end()) {
3124 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003125 }
3126 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003127 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003128}
3129
Ruben Brunkcc776712015-02-17 20:18:47 -08003130sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
3131 // Remove from active clients list
3132 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3133 if (clientDescriptorPtr == nullptr) {
3134 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
3135 cameraId.string());
3136 return sp<BasicClient>{nullptr};
3137 }
3138
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003139 sp<BasicClient> client = clientDescriptorPtr->getValue();
3140 if (client.get() != nullptr) {
3141 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3142 }
3143 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003144}
3145
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003146void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003147 // Acquire mServiceLock and prevent other clients from connecting
3148 std::unique_ptr<AutoConditionLock> lock =
3149 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3150
Ruben Brunk6267b532015-04-30 17:44:07 -07003151 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003152 for (size_t i = 0; i < newUserIds.size(); i++) {
3153 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003154 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003155 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003156 return;
3157 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003158 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003159 }
3160
Ruben Brunka8ca9152015-04-07 14:23:40 -07003161
Ruben Brunk6267b532015-04-30 17:44:07 -07003162 if (newAllowedUsers == mAllowedUsers) {
3163 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3164 return;
3165 }
3166
3167 logUserSwitch(mAllowedUsers, newAllowedUsers);
3168
3169 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003170
3171 // Current user has switched, evict all current clients.
3172 std::vector<sp<BasicClient>> evicted;
3173 for (auto& i : mActiveClientManager.getAll()) {
3174 auto clientSp = i->getValue();
3175
3176 if (clientSp.get() == nullptr) {
3177 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3178 continue;
3179 }
3180
Ruben Brunk6267b532015-04-30 17:44:07 -07003181 // Don't evict clients that are still allowed.
3182 uid_t clientUid = clientSp->getClientUid();
3183 userid_t clientUserId = multiuser_get_user_id(clientUid);
3184 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3185 continue;
3186 }
3187
Ruben Brunk36597b22015-03-20 22:15:57 -07003188 evicted.push_back(clientSp);
3189
3190 String8 curTime = getFormattedCurrentTime();
3191
3192 ALOGE("Evicting conflicting client for camera ID %s due to user change",
3193 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003194
Ruben Brunk36597b22015-03-20 22:15:57 -07003195 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07003196 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003197 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
3198 " to user switch.", i->getKey().string(),
3199 String8{clientSp->getPackageName()}.string(),
3200 i->getOwnerId(), i->getPriority().getScore(),
3201 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003202
3203 }
3204
3205 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3206 // blocking other clients from connecting in mServiceLockWrapper if held.
3207 mServiceLock.unlock();
3208
3209 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07003210 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003211
3212 for (auto& i : evicted) {
3213 i->disconnect();
3214 }
3215
Jayant Chowdhary12361932018-08-27 14:46:13 -07003216 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003217
3218 // Reacquire mServiceLock
3219 mServiceLock.lock();
3220}
Ruben Brunkcc776712015-02-17 20:18:47 -08003221
Ruben Brunka8ca9152015-04-07 14:23:40 -07003222void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003223 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003224 Mutex::Autolock l(mLogLock);
Rucha Katakward9ea6452021-05-06 11:57:16 -07003225 String8 msg = String8::format("%s : %s", curTime.string(), event);
3226 // For service error events, print the msg only once.
3227 if(!msg.contains("SERVICE ERROR")) {
3228 mEventLog.add(msg);
3229 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3230 // Error event not added to the dumpsys log before
3231 mEventLog.add(msg);
3232 sServiceErrorEventSet.insert(msg);
3233 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003234}
3235
Ruben Brunka8ca9152015-04-07 14:23:40 -07003236void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003237 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003238 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07003239 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003240 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003241}
3242
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003243void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
3244 const char* clientPackage) {
3245 // Log the clients evicted
3246 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
3247 cameraId, clientPackage, clientPid));
3248}
3249
Ruben Brunka8ca9152015-04-07 14:23:40 -07003250void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003251 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003252 // Log the clients evicted
3253 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003254 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003255}
3256
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003257void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
3258 const char* clientPackage) {
3259 // Log the clients evicted
3260 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
3261 clientPackage, clientPid));
3262}
3263
Ruben Brunka8ca9152015-04-07 14:23:40 -07003264void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003265 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003266 // Log the client rejected
3267 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003268 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003269}
3270
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003271void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
3272 // Log torch event
3273 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
3274 torchState, clientPid));
3275}
3276
Ruben Brunk6267b532015-04-30 17:44:07 -07003277void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3278 const std::set<userid_t>& newUserIds) {
3279 String8 newUsers = toString(newUserIds);
3280 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003281 if (oldUsers.size() == 0) {
3282 oldUsers = "<None>";
3283 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003284 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003285 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07003286 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003287}
3288
3289void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
3290 // Log the device removal
3291 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
3292}
3293
3294void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
3295 // Log the device removal
3296 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
3297}
3298
3299void CameraService::logClientDied(int clientPid, const char* reason) {
3300 // Log the device removal
3301 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003302}
3303
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003304void CameraService::logServiceError(const char* msg, int errorCode) {
3305 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003306 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003307}
3308
Ruben Brunk36597b22015-03-20 22:15:57 -07003309status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3310 uint32_t flags) {
3311
Mathias Agopian65ab4712010-07-14 17:59:35 -07003312 // Permission checks
3313 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003314 case SHELL_COMMAND_TRANSACTION: {
3315 int in = data.readFileDescriptor();
3316 int out = data.readFileDescriptor();
3317 int err = data.readFileDescriptor();
3318 int argc = data.readInt32();
3319 Vector<String16> args;
3320 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3321 args.add(data.readString16());
3322 }
3323 sp<IBinder> unusedCallback;
3324 sp<IResultReceiver> resultReceiver;
3325 status_t status;
3326 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3327 return status;
3328 }
3329 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3330 return status;
3331 }
3332 status = shellCommand(in, out, err, args);
3333 if (resultReceiver != nullptr) {
3334 resultReceiver->send(status);
3335 }
3336 return NO_ERROR;
3337 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003338 }
3339
3340 return BnCameraService::onTransact(code, data, reply, flags);
3341}
3342
Mathias Agopian65ab4712010-07-14 17:59:35 -07003343// We share the media players for shutter and recording sound for all clients.
3344// A reference count is kept to determine when we will actually release the
3345// media players.
3346
Jaekyun Seokef498052018-03-23 13:09:44 +09003347sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3348 sp<MediaPlayer> mp = new MediaPlayer();
3349 status_t error;
3350 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003351 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003352 error = mp->prepare();
3353 }
3354 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003355 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003356 mp->disconnect();
3357 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003358 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003359 }
3360 return mp;
3361}
3362
username5755fea2018-12-27 09:48:08 +08003363void CameraService::increaseSoundRef() {
3364 Mutex::Autolock lock(mSoundLock);
3365 mSoundRef++;
3366}
3367
3368void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003369 ATRACE_CALL();
3370
username5755fea2018-12-27 09:48:08 +08003371 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3372 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3373 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3374 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3375 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3376 }
3377 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3378 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3379 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3380 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003381 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003382 }
3383 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3384 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3385 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3386 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3387 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003388 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003389}
3390
username5755fea2018-12-27 09:48:08 +08003391void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003392 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003393 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003394 if (--mSoundRef) return;
3395
3396 for (int i = 0; i < NUM_SOUNDS; i++) {
3397 if (mSoundPlayer[i] != 0) {
3398 mSoundPlayer[i]->disconnect();
3399 mSoundPlayer[i].clear();
3400 }
3401 }
3402}
3403
3404void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003405 ATRACE_CALL();
3406
Mathias Agopian65ab4712010-07-14 17:59:35 -07003407 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07003408 if (kind < 0 || kind >= NUM_SOUNDS) {
3409 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
3410 return;
3411 }
3412
Mathias Agopian65ab4712010-07-14 17:59:35 -07003413 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003414 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003415 sp<MediaPlayer> player = mSoundPlayer[kind];
3416 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08003417 player->seekTo(0);
3418 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003419 }
3420}
3421
3422// ----------------------------------------------------------------------------
3423
3424CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07003425 const sp<ICameraClient>& cameraClient,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003426 const String16& clientPackageName, bool systemNativeClient,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003427 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003428 const String8& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003429 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003430 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003431 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003432 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003433 IInterface::asBinder(cameraClient),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003434 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003435 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003436 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003437 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003438 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003439{
Jayant Chowdhary12361932018-08-27 14:46:13 -07003440 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003441 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003442
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003443 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003444
username5755fea2018-12-27 09:48:08 +08003445 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003446
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003447 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003448}
3449
Mathias Agopian65ab4712010-07-14 17:59:35 -07003450// tear down the client
3451CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003452 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08003453 mDestructionStarted = true;
3454
username5755fea2018-12-27 09:48:08 +08003455 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003456 // unconditionally disconnect. function is idempotent
3457 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003458}
3459
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003460sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
3461
Igor Murashkin634a5152013-02-20 17:15:11 -08003462CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003463 const sp<IBinder>& remoteCallback,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003464 const String16& clientPackageName, bool nativeClient,
3465 const std::optional<String16>& clientFeatureId, const String8& cameraIdStr,
3466 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003467 int servicePid, bool overrideToPortrait):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003468 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07003469 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003470 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
3471 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003472 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003473 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07003474 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07003475 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003476 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003477 mRemoteBinder(remoteCallback),
3478 mOpsActive(false),
3479 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08003480{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003481 if (sCameraService == nullptr) {
3482 sCameraService = cameraService;
3483 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08003484
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003485 // There are 2 scenarios in which a client won't have AppOps operations
3486 // (both scenarios : native clients)
3487 // 1) It's an system native client*, the package name will be empty
3488 // and it will return from this function in the previous if condition
3489 // (This is the same as the previously existing behavior).
3490 // 2) It is a system native client, but its package name has been
3491 // modified for debugging, however it still must not use AppOps since
3492 // the package name is not a real one.
3493 //
3494 // * system native client - native client with UID < AID_APP_START. It
3495 // doesn't exclude clients not on the system partition.
3496 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003497 mAppOpsManager = std::make_unique<AppOpsManager>();
3498 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07003499
3500 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08003501}
3502
3503CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003504 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08003505 mDestructionStarted = true;
3506}
3507
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003508binder::Status CameraService::BasicClient::disconnect() {
3509 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003510 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003511 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07003512 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07003513 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08003514
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003515 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003516 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07003517 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
3518 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003519
3520 sp<IBinder> remote = getRemote();
3521 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003522 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08003523 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003524
3525 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07003526 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003527 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
3528 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
3529 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003530
Igor Murashkincba2c162013-03-20 15:56:31 -07003531 // client shouldn't be able to call into us anymore
3532 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003533
Kunal Malhotrabfc96052023-02-28 23:25:34 +00003534 const auto& mActivityManager = getActivityManager();
3535 if (mActivityManager) {
3536 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
3537 CameraThreadState::getCallingUid(),
3538 CameraThreadState::getCallingPid());
3539 }
3540
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003541 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08003542}
3543
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003544status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
3545 // No dumping of clients directly over Binder,
3546 // must go through CameraService::dump
3547 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003548 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003549 return OK;
3550}
3551
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07003552status_t CameraService::BasicClient::startWatchingTags(const String8&, int) {
3553 // Can't watch tags directly, must go through CameraService::startWatchingTags
3554 return OK;
3555}
3556
3557status_t CameraService::BasicClient::stopWatchingTags(int) {
3558 // Can't watch tags directly, must go through CameraService::stopWatchingTags
3559 return OK;
3560}
3561
3562status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
3563 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
3564 return OK;
3565}
3566
Ruben Brunkcc776712015-02-17 20:18:47 -08003567String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003568 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08003569}
3570
Emilian Peev8b64f282021-03-25 16:49:57 -07003571int CameraService::BasicClient::getCameraFacing() const {
3572 return mCameraFacing;
3573}
3574
3575int CameraService::BasicClient::getCameraOrientation() const {
3576 return mOrientation;
3577}
Ruben Brunkcc776712015-02-17 20:18:47 -08003578
3579int CameraService::BasicClient::getClientPid() const {
3580 return mClientPid;
3581}
3582
Ruben Brunk6267b532015-04-30 17:44:07 -07003583uid_t CameraService::BasicClient::getClientUid() const {
3584 return mClientUid;
3585}
3586
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003587bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
3588 // Defaults to API2.
3589 return level == API_2;
3590}
3591
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003592status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003593 {
3594 Mutex::Autolock l(mAudioRestrictionLock);
3595 mAudioRestriction = mode;
3596 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003597 sCameraService->updateAudioRestriction();
3598 return OK;
3599}
3600
3601int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003602 return sCameraService->updateAudioRestriction();
3603}
3604
3605int32_t CameraService::BasicClient::getAudioRestriction() const {
3606 Mutex::Autolock l(mAudioRestrictionLock);
3607 return mAudioRestriction;
3608}
3609
3610bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
3611 switch (mode) {
3612 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
3613 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
3614 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
3615 return true;
3616 default:
3617 return false;
3618 }
3619}
3620
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003621status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
3622 if (mode == AppOpsManager::MODE_ERRORED) {
3623 ALOGI("Camera %s: Access for \"%s\" has been revoked",
3624 mCameraIdStr.string(), String8(mClientPackageName).string());
3625 return PERMISSION_DENIED;
3626 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
3627 // If the calling Uid is trusted (a native service), the AppOpsManager could
3628 // return MODE_IGNORED. Do not treat such case as error.
3629 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
3630 mClientPackageName);
3631 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08003632 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayana8143e572023-01-09 08:46:49 -08003633 // We don't want to return EACCESS if the CameraPrivacy is enabled.
3634 // We prefer to successfully open the camera and perform camera muting
3635 // or blocking in connectHelper as handleAppOpMode can be called before the
3636 // connection has been fully established and at that time camera muting
3637 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003638 if (!isUidActive || !isCameraPrivacyEnabled) {
3639 ALOGI("Camera %s: Access for \"%s\" has been restricted",
3640 mCameraIdStr.string(), String8(mClientPackageName).string());
3641 // Return the same error as for device policy manager rejection
3642 return -EACCES;
3643 }
3644 }
3645 return OK;
3646}
3647
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003648status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003649 ATRACE_CALL();
3650
Igor Murashkine6800ce2013-03-04 17:25:57 -08003651 {
3652 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003653 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003654 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003655 if (mAppOpsManager != nullptr) {
3656 // Notify app ops that the camera is not available
3657 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003658 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
3659 mClientPackageName, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003660
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003661 // Just check for camera acccess here on open - delay startOp until
3662 // camera frames start streaming in startCameraStreamingOps
3663 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
3664 mClientPackageName);
3665 status_t res = handleAppOpMode(mode);
3666 if (res != OK) {
3667 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003668 }
Svetoslav28e8ef72015-05-11 19:21:31 -07003669 }
3670
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003671 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003672
3673 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003674 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003675
Emilian Peev53722fa2019-02-22 17:47:20 -08003676 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
3677
Shuzhen Wang695044d2020-03-06 09:02:23 -08003678 // Notify listeners of camera open/close status
3679 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
3680
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003681 return OK;
3682}
3683
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003684status_t CameraService::BasicClient::startCameraStreamingOps() {
3685 ATRACE_CALL();
3686
3687 if (!mOpsActive) {
3688 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3689 return INVALID_OPERATION;
3690 }
3691 if (mOpsStreaming) {
3692 ALOGV("%s: Streaming already active!", __FUNCTION__);
3693 return OK;
3694 }
3695
3696 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
3697 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3698
3699 if (mAppOpsManager != nullptr) {
3700 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
3701 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
3702 String16("start camera ") + String16(mCameraIdStr));
3703 status_t res = handleAppOpMode(mode);
3704 if (res != OK) {
3705 return res;
3706 }
3707 }
3708
3709 mOpsStreaming = true;
3710
3711 return OK;
3712}
3713
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003714status_t CameraService::BasicClient::noteAppOp() {
3715 ATRACE_CALL();
3716
3717 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
3718 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3719
3720 // noteAppOp is only used for when camera mute is not supported, in order
3721 // to trigger the sensor privacy "Unblock" dialog
3722 if (mAppOpsManager != nullptr) {
3723 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
3724 mClientPackageName, mClientFeatureId,
3725 String16("start camera ") + String16(mCameraIdStr));
3726 status_t res = handleAppOpMode(mode);
3727 if (res != OK) {
3728 return res;
3729 }
3730 }
3731
3732 return OK;
3733}
3734
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003735status_t CameraService::BasicClient::finishCameraStreamingOps() {
3736 ATRACE_CALL();
3737
3738 if (!mOpsActive) {
3739 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3740 return INVALID_OPERATION;
3741 }
3742 if (!mOpsStreaming) {
3743 ALOGV("%s: Streaming not active!", __FUNCTION__);
3744 return OK;
3745 }
3746
3747 if (mAppOpsManager != nullptr) {
3748 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
3749 mClientPackageName, mClientFeatureId);
3750 mOpsStreaming = false;
3751 }
3752
3753 return OK;
3754}
3755
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003756status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003757 ATRACE_CALL();
3758
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003759 if (mOpsStreaming) {
3760 // Make sure we've notified everyone about camera stopping
3761 finishCameraStreamingOps();
3762 }
3763
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003764 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003765 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003766 mOpsActive = false;
3767
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003768 // This function is called when a client disconnects. This should
3769 // release the camera, but actually only if it was in a proper
3770 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003771 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003772 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003773
Ruben Brunkcc776712015-02-17 20:18:47 -08003774 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003775 sCameraService->updateStatus(StatusInternal::PRESENT,
3776 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003777 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003778 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003779 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3780 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003781 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003782 mOpsCallback.clear();
3783
Emilian Peev53722fa2019-02-22 17:47:20 -08003784 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3785
Shuzhen Wang695044d2020-03-06 09:02:23 -08003786 // Notify listeners of camera open/close status
3787 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3788
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003789 return OK;
3790}
3791
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003792void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003793 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003794 if (mAppOpsManager == nullptr) {
3795 return;
3796 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003797 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003798 if (op != AppOpsManager::OP_CAMERA) {
3799 ALOGW("Unexpected app ops notification received: %d", op);
3800 return;
3801 }
3802
3803 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003804 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003805 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003806 ALOGV("checkOp returns: %d, %s ", res,
3807 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3808 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3809 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3810 "UNKNOWN");
3811
Shuzhen Wang64900852021-02-05 09:03:29 -08003812 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003813 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003814 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003815 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003816 } else if (res == AppOpsManager::MODE_IGNORED) {
3817 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08003818 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08003819 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Shuzhen Wang64900852021-02-05 09:03:29 -08003820 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3821 mCameraIdStr.string(), String8(mClientPackageName).string(),
3822 mUidIsTrusted, isUidActive);
3823 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3824 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3825 // error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003826 if (!mUidIsTrusted) {
3827 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
3828 setCameraMute(true);
3829 } else if (!isUidActive
3830 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
3831 block();
3832 }
Shuzhen Wang64900852021-02-05 09:03:29 -08003833 }
Evan Severson09ab4002021-02-10 14:15:19 -08003834 } else if (res == AppOpsManager::MODE_ALLOWED) {
3835 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003836 }
3837}
3838
Svet Ganova453d0d2018-01-11 15:37:58 -08003839void CameraService::BasicClient::block() {
3840 ATRACE_CALL();
3841
3842 // Reset the client PID to allow server-initiated disconnect,
3843 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003844 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003845 CaptureResultExtras resultExtras; // a dummy result (invalid)
3846 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3847 disconnect();
3848}
3849
Mathias Agopian65ab4712010-07-14 17:59:35 -07003850// ----------------------------------------------------------------------------
3851
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003852void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08003853 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003854 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003855 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3856 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3857 api1ErrorCode = CAMERA_ERROR_DISABLED;
3858 }
3859 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003860 } else {
3861 ALOGE("mRemoteCallback is NULL!!");
3862 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003863}
3864
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003865// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003866binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003867 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003868 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003869}
3870
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003871bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3872 return level == API_1;
3873}
3874
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003875CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3876 mClient(client) {
3877}
3878
3879void CameraService::Client::OpsCallback::opChanged(int32_t op,
3880 const String16& packageName) {
3881 sp<BasicClient> client = mClient.promote();
3882 if (client != NULL) {
3883 client->opChanged(op, packageName);
3884 }
3885}
3886
Mathias Agopian65ab4712010-07-14 17:59:35 -07003887// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003888// UidPolicy
3889// ----------------------------------------------------------------------------
3890
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08003891void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003892 Mutex::Autolock _l(mUidLock);
3893
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003894 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003895 status_t res = mAm.linkToDeath(this);
3896 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003897 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00003898 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
3899 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08003900 ActivityManager::PROCESS_STATE_UNKNOWN,
3901 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003902 if (res == OK) {
3903 mRegistered = true;
3904 ALOGV("UidPolicy: Registered with ActivityManager");
3905 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003906}
3907
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08003908void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
3909 if (name != String16(kActivityServiceName)) {
3910 return;
3911 }
3912
3913 registerWithActivityManager();
3914}
3915
3916void CameraService::UidPolicy::registerSelf() {
3917 // Use check service to see if the activity service is available
3918 // If not available then register for notifications, instead of blocking
3919 // till the service is ready
3920 sp<IServiceManager> sm = defaultServiceManager();
3921 sp<IBinder> binder = sm->checkService(String16(kActivityServiceName));
3922 if (!binder) {
3923 sm->registerForNotifications(String16(kActivityServiceName), this);
3924 } else {
3925 registerWithActivityManager();
3926 }
3927}
3928
Svet Ganova453d0d2018-01-11 15:37:58 -08003929void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003930 Mutex::Autolock _l(mUidLock);
3931
Steven Moreland2f348142019-07-02 15:59:07 -07003932 mAm.unregisterUidObserver(this);
3933 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003934 mRegistered = false;
3935 mActiveUids.clear();
3936 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003937}
3938
3939void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3940 onUidIdle(uid, disabled);
3941}
3942
3943void CameraService::UidPolicy::onUidActive(uid_t uid) {
3944 Mutex::Autolock _l(mUidLock);
3945 mActiveUids.insert(uid);
3946}
3947
3948void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3949 bool deleted = false;
3950 {
3951 Mutex::Autolock _l(mUidLock);
3952 if (mActiveUids.erase(uid) > 0) {
3953 deleted = true;
3954 }
3955 }
3956 if (deleted) {
3957 sp<CameraService> service = mService.promote();
3958 if (service != nullptr) {
3959 service->blockClientsForUid(uid);
3960 }
3961 }
3962}
3963
Emilian Peev53722fa2019-02-22 17:47:20 -08003964void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003965 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00003966 bool procStateChange = false;
3967 {
3968 Mutex::Autolock _l(mUidLock);
3969 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
3970 mMonitoredUids[uid].procState != procState) {
3971 mMonitoredUids[uid].procState = procState;
3972 procStateChange = true;
3973 }
3974 }
3975
3976 if (procStateChange) {
3977 sp<CameraService> service = mService.promote();
3978 if (service != nullptr) {
3979 service->notifyMonitoredUids();
3980 }
Emilian Peev53722fa2019-02-22 17:47:20 -08003981 }
3982}
3983
Austin Borger65577682022-02-17 00:25:43 +00003984void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid) {
3985 bool procAdjChange = false;
3986 {
3987 Mutex::Autolock _l(mUidLock);
3988 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3989 procAdjChange = true;
3990 }
3991 }
3992
3993 if (procAdjChange) {
3994 sp<CameraService> service = mService.promote();
3995 if (service != nullptr) {
3996 service->notifyMonitoredUids();
3997 }
3998 }
3999}
4000
Emilian Peev53722fa2019-02-22 17:47:20 -08004001void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
4002 Mutex::Autolock _l(mUidLock);
4003 auto it = mMonitoredUids.find(uid);
4004 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004005 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004006 } else {
Austin Borger65577682022-02-17 00:25:43 +00004007 MonitoredUid monitoredUid;
4008 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
4009 monitoredUid.refCount = 1;
4010 mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid));
Emilian Peev53722fa2019-02-22 17:47:20 -08004011 }
4012}
4013
4014void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
4015 Mutex::Autolock _l(mUidLock);
4016 auto it = mMonitoredUids.find(uid);
4017 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004018 it->second.refCount--;
4019 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004020 mMonitoredUids.erase(it);
4021 }
4022 } else {
4023 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4024 }
4025}
4026
Svet Ganov7b4ab782018-03-25 12:48:10 -07004027bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004028 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004029 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004030}
4031
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004032static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4033static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004034
Svet Ganov7b4ab782018-03-25 12:48:10 -07004035bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004036 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004037 // If activity manager is unreachable, assume everything is active
4038 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004039 return true;
4040 }
4041 auto it = mOverrideUids.find(uid);
4042 if (it != mOverrideUids.end()) {
4043 return it->second;
4044 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004045 bool active = mActiveUids.find(uid) != mActiveUids.end();
4046 if (!active) {
4047 // We want active UIDs to always access camera with their first attempt since
4048 // there is no guarantee the app is robustly written and would retry getting
4049 // the camera on failure. The inverse case is not a problem as we would take
4050 // camera away soon once we get the callback that the uid is no longer active.
4051 ActivityManager am;
4052 // Okay to access with a lock held as UID changes are dispatched without
4053 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004054 int64_t startTimeMillis = 0;
4055 do {
4056 // TODO: Fix this b/109950150!
4057 // Okay this is a hack. There is a race between the UID turning active and
4058 // activity being resumed. The proper fix is very risky, so we temporary add
4059 // some polling which should happen pretty rarely anyway as the race is hard
4060 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004061 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00004062 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07004063 if (active) {
4064 break;
4065 }
4066 if (startTimeMillis <= 0) {
4067 startTimeMillis = uptimeMillis();
4068 }
4069 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004070 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004071 if (remainingTimeMillis <= 0) {
4072 break;
4073 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004074 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4075
4076 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004077 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004078 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004079 } while (true);
4080
Svet Ganov7b4ab782018-03-25 12:48:10 -07004081 if (active) {
4082 // Now that we found out the UID is actually active, cache that
4083 mActiveUids.insert(uid);
4084 }
4085 }
4086 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004087}
4088
Varun Shahb42f1eb2019-04-16 14:45:13 -07004089int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4090 Mutex::Autolock _l(mUidLock);
4091 return getProcStateLocked(uid);
4092}
4093
4094int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4095 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4096 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004097 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004098 }
4099 return procState;
4100}
4101
Svet Ganov7b4ab782018-03-25 12:48:10 -07004102void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
4103 String16 callingPackage, bool active) {
4104 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004105}
4106
Svet Ganov7b4ab782018-03-25 12:48:10 -07004107void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
4108 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004109}
4110
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004111void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4112 Mutex::Autolock _l(mUidLock);
4113 ALOGV("UidPolicy: ActivityManager has died");
4114 mRegistered = false;
4115 mActiveUids.clear();
4116}
4117
Svet Ganov7b4ab782018-03-25 12:48:10 -07004118void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
4119 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004120 bool wasActive = false;
4121 bool isActive = false;
4122 {
4123 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004124 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004125 mOverrideUids.erase(uid);
4126 if (insert) {
4127 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4128 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004129 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004130 }
4131 if (wasActive != isActive && !isActive) {
4132 sp<CameraService> service = mService.promote();
4133 if (service != nullptr) {
4134 service->blockClientsForUid(uid);
4135 }
4136 }
4137}
4138
4139// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004140// SensorPrivacyPolicy
4141// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004142
4143void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4144{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004145 Mutex::Autolock _l(mSensorPrivacyLock);
4146 if (mRegistered) {
4147 return;
4148 }
Evan Severson09ab4002021-02-10 14:15:19 -08004149 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004150 mSpm.addSensorPrivacyListener(this);
4151 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
4152 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004153 if (res == OK) {
4154 mRegistered = true;
4155 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4156 }
4157}
4158
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004159void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4160 const sp<IBinder>&) {
4161 if (name != String16(kSensorPrivacyServiceName)) {
4162 return;
4163 }
4164
4165 registerWithSensorPrivacyManager();
4166}
4167
4168void CameraService::SensorPrivacyPolicy::registerSelf() {
4169 // Use checkservice to see if the sensor_privacy service is available
4170 // If service is not available then register for notification
4171 sp<IServiceManager> sm = defaultServiceManager();
4172 sp<IBinder> binder = sm->checkService(String16(kSensorPrivacyServiceName));
4173 if (!binder) {
4174 sm->registerForNotifications(String16(kSensorPrivacyServiceName),this);
4175 } else {
4176 registerWithSensorPrivacyManager();
4177 }
4178}
4179
Michael Grooverd1d435a2018-12-18 17:39:42 -08004180void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4181 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004182 mSpm.removeSensorPrivacyListener(this);
4183 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004184 mRegistered = false;
4185 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4186}
4187
4188bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004189 if (!mRegistered) {
4190 registerWithSensorPrivacyManager();
4191 }
4192
Michael Grooverd1d435a2018-12-18 17:39:42 -08004193 Mutex::Autolock _l(mSensorPrivacyLock);
4194 return mSensorPrivacyEnabled;
4195}
4196
Evan Seversond0b69922022-01-27 10:47:34 -08004197bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004198 if (!hasCameraPrivacyFeature()) {
4199 return false;
4200 }
Evan Seversond0b69922022-01-27 10:47:34 -08004201 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004202}
4203
Evan Seversond0b69922022-01-27 10:47:34 -08004204binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
4205 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08004206 {
4207 Mutex::Autolock _l(mSensorPrivacyLock);
Kwangkyu Parke3af2992022-11-05 02:46:52 +09004208 mSensorPrivacyEnabled = enabled;
Michael Grooverd1d435a2018-12-18 17:39:42 -08004209 }
4210 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08004211 if (enabled) {
4212 sp<CameraService> service = mService.promote();
4213 if (service != nullptr) {
4214 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004215 }
4216 }
4217 return binder::Status::ok();
4218}
4219
4220void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4221 Mutex::Autolock _l(mSensorPrivacyLock);
4222 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
4223 mRegistered = false;
4224}
4225
Evan Severson09ab4002021-02-10 14:15:19 -08004226bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08004227 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
4228 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4229 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
4230 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4231 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08004232}
4233
Michael Grooverd1d435a2018-12-18 17:39:42 -08004234// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004235// CameraState
4236// ----------------------------------------------------------------------------
4237
4238CameraService::CameraState::CameraState(const String8& id, int cost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004239 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind,
4240 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004241 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004242 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08004243
4244CameraService::CameraState::~CameraState() {}
4245
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004246CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004247 Mutex::Autolock lock(mStatusLock);
4248 return mStatus;
4249}
4250
Shuzhen Wang43858162020-01-10 13:42:15 -08004251std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
4252 Mutex::Autolock lock(mStatusLock);
4253 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
4254 return res;
4255}
4256
Ruben Brunkcc776712015-02-17 20:18:47 -08004257CameraParameters CameraService::CameraState::getShimParams() const {
4258 return mShimParams;
4259}
4260
4261void CameraService::CameraState::setShimParams(const CameraParameters& params) {
4262 mShimParams = params;
4263}
4264
4265int CameraService::CameraState::getCost() const {
4266 return mCost;
4267}
4268
4269std::set<String8> CameraService::CameraState::getConflicting() const {
4270 return mConflicting;
4271}
4272
4273String8 CameraService::CameraState::getId() const {
4274 return mId;
4275}
4276
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004277SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
4278 return mSystemCameraKind;
4279}
4280
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004281bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
4282 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
4283 != mPhysicalCameras.end();
4284}
4285
Shuzhen Wang43858162020-01-10 13:42:15 -08004286bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
4287 Mutex::Autolock lock(mStatusLock);
4288 auto result = mUnavailablePhysicalIds.insert(physicalId);
4289 return result.second;
4290}
4291
4292bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
4293 Mutex::Autolock lock(mStatusLock);
4294 auto count = mUnavailablePhysicalIds.erase(physicalId);
4295 return count > 0;
4296}
4297
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004298void CameraService::CameraState::setClientPackage(const String8& clientPackage) {
4299 Mutex::Autolock lock(mStatusLock);
4300 mClientPackage = clientPackage;
4301}
4302
4303String8 CameraService::CameraState::getClientPackage() const {
4304 Mutex::Autolock lock(mStatusLock);
4305 return mClientPackage;
4306}
4307
Ruben Brunkcc776712015-02-17 20:18:47 -08004308// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07004309// ClientEventListener
4310// ----------------------------------------------------------------------------
4311
4312void CameraService::ClientEventListener::onClientAdded(
4313 const resource_policy::ClientDescriptor<String8,
4314 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004315 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004316 if (basicClient.get() != nullptr) {
4317 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4318 notifier.noteStartCamera(descriptor.getKey(),
4319 static_cast<int>(basicClient->getClientUid()));
4320 }
4321}
4322
4323void CameraService::ClientEventListener::onClientRemoved(
4324 const resource_policy::ClientDescriptor<String8,
4325 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004326 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004327 if (basicClient.get() != nullptr) {
4328 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4329 notifier.noteStopCamera(descriptor.getKey(),
4330 static_cast<int>(basicClient->getClientUid()));
4331 }
4332}
4333
4334
4335// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004336// CameraClientManager
4337// ----------------------------------------------------------------------------
4338
Ruben Brunk99e69712015-05-26 17:25:07 -07004339CameraService::CameraClientManager::CameraClientManager() {
4340 setListener(std::make_shared<ClientEventListener>());
4341}
4342
Ruben Brunkcc776712015-02-17 20:18:47 -08004343CameraService::CameraClientManager::~CameraClientManager() {}
4344
4345sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
4346 const String8& id) const {
4347 auto descriptor = get(id);
4348 if (descriptor == nullptr) {
4349 return sp<BasicClient>{nullptr};
4350 }
4351 return descriptor->getValue();
4352}
4353
4354String8 CameraService::CameraClientManager::toString() const {
4355 auto all = getAll();
4356 String8 ret("[");
4357 bool hasAny = false;
4358 for (auto& i : all) {
4359 hasAny = true;
4360 String8 key = i->getKey();
4361 int32_t cost = i->getCost();
4362 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00004363 int32_t score = i->getPriority().getScore();
4364 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08004365 auto conflicting = i->getConflicting();
4366 auto clientSp = i->getValue();
4367 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07004368 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08004369 if (clientSp.get() != nullptr) {
4370 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07004371 uid_t clientUid = clientSp->getClientUid();
4372 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004373 }
Emilian Peev8131a262017-02-01 12:33:43 +00004374 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
4375 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08004376
Ruben Brunk6267b532015-04-30 17:44:07 -07004377 if (clientSp.get() != nullptr) {
4378 ret.appendFormat("User Id: %d, ", clientUserId);
4379 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004380 if (packageName.size() != 0) {
4381 ret.appendFormat("Client Package Name: %s", packageName.string());
4382 }
4383
4384 ret.append(", Conflicting Client Devices: {");
4385 for (auto& j : conflicting) {
4386 ret.appendFormat("%s, ", j.string());
4387 }
4388 ret.append("})");
4389 }
4390 if (hasAny) ret.append("\n");
4391 ret.append("]\n");
4392 return ret;
4393}
4394
4395CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
4396 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00004397 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004398 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004399
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004400 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
4401 int32_t state_adj = systemNativeClient ? kSystemNativeClientState: state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07004402
Ruben Brunkcc776712015-02-17 20:18:47 -08004403 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004404 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
4405 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08004406}
4407
4408CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004409 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004410 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004411 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00004412 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004413 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
4414 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08004415}
4416
4417// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08004418// InjectionStatusListener
4419// ----------------------------------------------------------------------------
4420
4421void CameraService::InjectionStatusListener::addListener(
4422 const sp<ICameraInjectionCallback>& callback) {
4423 Mutex::Autolock lock(mListenerLock);
4424 if (mCameraInjectionCallback) return;
4425 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
4426 if (res == OK) {
4427 mCameraInjectionCallback = callback;
4428 }
4429}
4430
4431void CameraService::InjectionStatusListener::removeListener() {
4432 Mutex::Autolock lock(mListenerLock);
4433 if (mCameraInjectionCallback == nullptr) {
4434 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4435 return;
4436 }
4437 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
4438 mCameraInjectionCallback = nullptr;
4439}
4440
4441void CameraService::InjectionStatusListener::notifyInjectionError(
Cliff Wud3a05312021-04-26 23:07:31 +08004442 String8 injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08004443 if (mCameraInjectionCallback == nullptr) {
4444 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4445 return;
4446 }
Cliff Wud3a05312021-04-26 23:07:31 +08004447
4448 switch (err) {
4449 case -ENODEV:
4450 mCameraInjectionCallback->onInjectionError(
4451 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4452 ALOGE("No camera device with ID \"%s\" currently available!",
4453 injectedCamId.string());
4454 break;
4455 case -EBUSY:
4456 mCameraInjectionCallback->onInjectionError(
4457 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4458 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
4459 injectedCamId.string());
4460 break;
4461 case DEAD_OBJECT:
4462 mCameraInjectionCallback->onInjectionError(
4463 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4464 ALOGE("Camera ID \"%s\" object is dead!",
4465 injectedCamId.string());
4466 break;
4467 case INVALID_OPERATION:
4468 mCameraInjectionCallback->onInjectionError(
4469 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4470 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
4471 injectedCamId.string());
4472 break;
4473 case UNKNOWN_TRANSACTION:
4474 mCameraInjectionCallback->onInjectionError(
4475 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
4476 ALOGE("Camera ID \"%s\" method doesn't support!",
4477 injectedCamId.string());
4478 break;
4479 default:
4480 mCameraInjectionCallback->onInjectionError(
4481 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
4482 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
4483 strerror(-err), err, injectedCamId.string());
4484 }
Cliff Wud8cae102021-03-11 01:37:42 +08004485}
4486
4487void CameraService::InjectionStatusListener::binderDied(
4488 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08004489 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
4490 auto parent = mParent.promote();
4491 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08004492 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4493 if (clientDescriptor != nullptr) {
4494 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4495 baseClientPtr->stopInjection();
4496 }
Cliff Wu3b268182021-07-06 15:44:43 +08004497 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004498 }
4499}
4500
4501// ----------------------------------------------------------------------------
4502// CameraInjectionSession
4503// ----------------------------------------------------------------------------
4504
4505binder::Status CameraService::CameraInjectionSession::stopInjection() {
4506 Mutex::Autolock lock(mInjectionSessionLock);
4507 auto parent = mParent.promote();
4508 if (parent == nullptr) {
4509 ALOGE("CameraInjectionSession: Parent is gone");
4510 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
4511 "Camera service encountered error");
4512 }
Cliff Wud3a05312021-04-26 23:07:31 +08004513
4514 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08004515 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4516 if (clientDescriptor != nullptr) {
4517 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4518 res = baseClientPtr->stopInjection();
4519 if (res != OK) {
4520 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
4521 " ret != NO_ERROR: %d", res);
4522 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
4523 "Camera session encountered error");
4524 }
4525 }
Cliff Wu3b268182021-07-06 15:44:43 +08004526 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004527 return binder::Status::ok();
4528}
4529
4530// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07004531
4532static const int kDumpLockRetries = 50;
4533static const int kDumpLockSleep = 60000;
4534
4535static bool tryLock(Mutex& mutex)
4536{
4537 bool locked = false;
4538 for (int i = 0; i < kDumpLockRetries; ++i) {
4539 if (mutex.tryLock() == NO_ERROR) {
4540 locked = true;
4541 break;
4542 }
4543 usleep(kDumpLockSleep);
4544 }
4545 return locked;
4546}
4547
Rucha Katakwardf223072021-06-15 10:21:00 -07004548void CameraService::cacheDump() {
4549 if (mMemFd != -1) {
4550 const Vector<String16> args;
4551 ATRACE_CALL();
4552 // Acquiring service lock here will avoid the deadlock since
4553 // cacheDump will not be called during the second disconnect.
4554 Mutex::Autolock lock(mServiceLock);
4555
4556 Mutex::Autolock l(mCameraStatesLock);
4557 // Start collecting the info for open sessions and store it in temp file.
4558 for (const auto& state : mCameraStates) {
4559 String8 cameraId = state.first;
4560 auto clientDescriptor = mActiveClientManager.get(cameraId);
4561 if (clientDescriptor != nullptr) {
4562 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.string());
4563 // Log the current open session info before device is disconnected.
4564 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
4565 }
4566 }
4567 }
4568}
4569
Mathias Agopian65ab4712010-07-14 17:59:35 -07004570status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004571 ATRACE_CALL();
4572
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004573 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004574 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004575 CameraThreadState::getCallingPid(),
4576 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004577 return NO_ERROR;
4578 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004579 bool locked = tryLock(mServiceLock);
4580 // failed to lock - CameraService is probably deadlocked
4581 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004582 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004583 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004584
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004585 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004586 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07004587
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004588 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004589 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08004590
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004591 if (locked) mServiceLock.unlock();
4592 return NO_ERROR;
4593 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004594 dprintf(fd, "\n== Service global info: ==\n\n");
4595 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004596 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07004597 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
4598 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004599 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
4600 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
4601 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004602 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004603 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
4604 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Shuzhen Wang16610a62022-12-15 22:38:07 -08004605 if (mStreamUseCaseOverrides.size() > 0) {
4606 dprintf(fd, "Active stream use case overrides:");
4607 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
4608 dprintf(fd, " %" PRId64, useCaseOverride);
4609 }
4610 dprintf(fd, "\n");
4611 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004612
4613 dumpEventLog(fd);
4614
4615 bool stateLocked = tryLock(mCameraStatesLock);
4616 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004617 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004618 }
4619
Emilian Peevbd8c5032018-02-14 23:05:40 +00004620 int argSize = args.size();
4621 for (int i = 0; i < argSize; i++) {
4622 if (args[i] == TagMonitor::kMonitorOption) {
4623 if (i + 1 < argSize) {
4624 mMonitorTags = String8(args[i + 1]);
4625 }
4626 break;
4627 }
4628 }
4629
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004630 for (auto& state : mCameraStates) {
4631 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004632
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004633 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004634
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004635 CameraParameters p = state.second->getShimParams();
4636 if (!p.isEmpty()) {
4637 dprintf(fd, " Camera1 API shim is using parameters:\n ");
4638 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004639 }
4640
4641 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004642 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004643 // log the current open session info
4644 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004645 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07004646 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004647 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004648
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004649 }
4650
4651 if (stateLocked) mCameraStatesLock.unlock();
4652
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004653 if (locked) mServiceLock.unlock();
4654
Emilian Peevf53f66e2017-04-11 14:29:43 +01004655 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004656
4657 dprintf(fd, "\n== Vendor tags: ==\n\n");
4658
4659 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
4660 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00004661 sp<VendorTagDescriptorCache> cache =
4662 VendorTagDescriptorCache::getGlobalVendorTagCache();
4663 if (cache == NULL) {
4664 dprintf(fd, "No vendor tags.\n");
4665 } else {
4666 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
4667 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004668 } else {
4669 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
4670 }
4671
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004672 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004673 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004674 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004675
4676 // Process dump arguments, if any
4677 int n = args.size();
4678 String16 verboseOption("-v");
4679 String16 unreachableOption("--unreachable");
4680 for (int i = 0; i < n; i++) {
4681 if (args[i] == verboseOption) {
4682 // change logging level
4683 if (i + 1 >= n) continue;
4684 String8 levelStr(args[i+1]);
4685 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004686 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004687 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004688 } else if (args[i] == unreachableOption) {
4689 // Dump memory analysis
4690 // TODO - should limit be an argument parameter?
4691 UnreachableMemoryInfo info;
4692 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
4693 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004694 dprintf(fd, "\n== Unable to dump unreachable memory. "
4695 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004696 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004697 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004698 std::string s = info.ToString(/*log_contents*/ true);
4699 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004700 }
4701 }
4702 }
Rucha Katakwardf223072021-06-15 10:21:00 -07004703
4704 bool serviceLocked = tryLock(mServiceLock);
4705
4706 // Dump info from previous open sessions.
4707 // Reposition the offset to beginning of the file before reading
4708
4709 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
4710 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
4711 ssize_t size_read;
4712 char buf[4096];
4713 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
4714 // Read data from file to a small buffer and write it to fd.
4715 write(fd, buf, size_read);
4716 if (size_read == -1) {
4717 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4718 break;
4719 }
4720 }
4721 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
4722 } else {
4723 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4724 }
4725
4726 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004727 return NO_ERROR;
4728}
4729
Rucha Katakwardf223072021-06-15 10:21:00 -07004730void CameraService::dumpOpenSessionClientLogs(int fd,
4731 const Vector<String16>& args, const String8& cameraId) {
4732 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07004733 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
4734 getFormattedCurrentTime().string(),
4735 cameraId.string());
Rucha Katakwardf223072021-06-15 10:21:00 -07004736 dprintf(fd, " Client priority score: %d state: %d\n",
4737 clientDescriptor->getPriority().getScore(),
4738 clientDescriptor->getPriority().getState());
4739 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
4740
4741 auto client = clientDescriptor->getValue();
4742 dprintf(fd, " Client package: %s\n",
4743 String8(client->getPackageName()).string());
4744
4745 client->dumpClient(fd, args);
4746}
4747
4748void CameraService::dumpClosedSessionClientLogs(int fd, const String8& cameraId) {
4749 dprintf(fd, " Device %s is closed, no client instance\n",
4750 cameraId.string());
4751}
4752
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004753void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004754 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004755
4756 Mutex::Autolock l(mLogLock);
4757 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004758 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004759 }
4760
4761 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004762 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004763 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004764 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004765 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004766 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004767}
4768
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004769void CameraService::cacheClientTagDumpIfNeeded(const char *cameraId, BasicClient* client) {
4770 Mutex::Autolock lock(mLogLock);
4771 if (!isClientWatchedLocked(client)) { return; }
4772
4773 std::vector<std::string> dumpVector;
4774 client->dumpWatchedEventsToVector(dumpVector);
4775
4776 if (dumpVector.empty()) { return; }
4777
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004778 std::string dumpString;
4779
4780 String8 currentTime = getFormattedCurrentTime();
4781 dumpString += "Cached @ ";
4782 dumpString += currentTime.string();
4783 dumpString += "\n"; // First line is the timestamp of when client is cached.
4784
4785
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004786 const String16 &packageName = client->getPackageName();
4787
4788 String8 packageName8 = String8(packageName);
4789 const char *printablePackageName = packageName8.lockBuffer(packageName.size());
4790
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004791
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004792 size_t i = dumpVector.size();
4793
4794 // Store the string in reverse order (latest last)
4795 while (i > 0) {
4796 i--;
4797 dumpString += cameraId;
4798 dumpString += ":";
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004799 dumpString += printablePackageName;
4800 dumpString += " ";
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004801 dumpString += dumpVector[i]; // implicitly ends with '\n'
4802 }
4803
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004804 packageName8.unlockBuffer();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004805 mWatchedClientsDumpCache[packageName] = dumpString;
4806}
4807
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004808void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004809 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004810 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
4811 if (mTorchClientMap[i] == who) {
4812 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004813 String8 cameraId = mTorchClientMap.keyAt(i);
4814 status_t res = mFlashlight->setTorchMode(cameraId, false);
4815 if (res) {
4816 ALOGE("%s: torch client died but couldn't turn off torch: "
4817 "%s (%d)", __FUNCTION__, strerror(-res), res);
4818 return;
4819 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004820 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004821 break;
4822 }
4823 }
4824}
4825
Ruben Brunkcc776712015-02-17 20:18:47 -08004826/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07004827
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004828 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07004829 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
4830 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004831 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08004832 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004833 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004834
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004835 // check torch client
4836 handleTorchClientBinderDied(who);
4837
4838 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08004839 if(!evictClientIdByRemote(who)) {
4840 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004841 return;
4842 }
4843
Ruben Brunkcc776712015-02-17 20:18:47 -08004844 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
4845 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004846}
4847
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004848void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004849 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08004850}
4851
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004852void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
4853 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004854 // Do not lock mServiceLock here or can get into a deadlock from
4855 // connect() -> disconnect -> updateStatus
4856
4857 auto state = getCameraState(cameraId);
4858
4859 if (state == nullptr) {
4860 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4861 cameraId.string());
4862 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07004863 }
4864
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004865 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
4866 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
4867 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
4868 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
4869 return;
4870 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004871
4872 // Collect the logical cameras without holding mStatusLock in updateStatus
4873 // as that can lead to a deadlock(b/162192331).
4874 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08004875 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08004876 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07004877 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004878 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004879 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004880
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004881 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004882 // Update torch status if it has a flash unit.
4883 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004884 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004885 if (getTorchStatusLocked(cameraId, &torchStatus) !=
4886 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004887 TorchModeStatus newTorchStatus =
4888 status == StatusInternal::PRESENT ?
4889 TorchModeStatus::AVAILABLE_OFF :
4890 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004891 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07004892 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004893 }
4894 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004895 }
4896
4897 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004898 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
4899 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08004900
Ruben Brunkcc776712015-02-17 20:18:47 -08004901 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07004902 bool isVendorListener = listener->isVendorListener();
4903 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
4904 listener->getListenerPid(), listener->getListenerUid()) ||
Shuzhen Wangb8259792021-05-27 09:27:06 -07004905 isVendorListener) {
4906 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004907 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08004908 continue;
4909 }
Austin Borgere8e2c422022-05-12 13:45:24 -07004910 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08004911 String16(cameraId));
Austin Borgere8e2c422022-05-12 13:45:24 -07004912 listener->handleBinderStatus(ret,
4913 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
4914 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
4915 ret.exceptionCode());
Ruben Brunkcc776712015-02-17 20:18:47 -08004916 }
4917 });
Igor Murashkincba2c162013-03-20 15:56:31 -07004918}
4919
Shuzhen Wang695044d2020-03-06 09:02:23 -08004920void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
4921 const String16& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004922 auto state = getCameraState(cameraId);
4923 if (state == nullptr) {
4924 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4925 cameraId.string());
4926 return;
4927 }
4928 if (open) {
4929 state->setClientPackage(String8(clientPackageName));
4930 } else {
4931 state->setClientPackage(String8::empty());
4932 }
4933
Shuzhen Wang695044d2020-03-06 09:02:23 -08004934 Mutex::Autolock lock(mStatusListenerLock);
4935
4936 for (const auto& it : mListenerList) {
4937 if (!it->isOpenCloseCallbackAllowed()) {
4938 continue;
4939 }
4940
4941 binder::Status ret;
4942 String16 cameraId64(cameraId);
4943 if (open) {
4944 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
4945 } else {
4946 ret = it->getListener()->onCameraClosed(cameraId64);
4947 }
Austin Borgere8e2c422022-05-12 13:45:24 -07004948
4949 it->handleBinderStatus(ret,
4950 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
4951 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08004952 }
4953}
4954
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004955template<class Func>
4956void CameraService::CameraState::updateStatus(StatusInternal status,
4957 const String8& cameraId,
4958 std::initializer_list<StatusInternal> rejectSourceStates,
4959 Func onStatusUpdatedLocked) {
4960 Mutex::Autolock lock(mStatusLock);
4961 StatusInternal oldStatus = mStatus;
4962 mStatus = status;
4963
4964 if (oldStatus == status) {
4965 return;
4966 }
4967
4968 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
4969 cameraId.string(), oldStatus, status);
4970
4971 if (oldStatus == StatusInternal::NOT_PRESENT &&
4972 (status != StatusInternal::PRESENT &&
4973 status != StatusInternal::ENUMERATING)) {
4974
4975 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
4976 __FUNCTION__);
4977 mStatus = oldStatus;
4978 return;
4979 }
4980
4981 /**
4982 * Sometimes we want to conditionally do a transition.
4983 * For example if a client disconnects, we want to go to PRESENT
4984 * only if we weren't already in NOT_PRESENT or ENUMERATING.
4985 */
4986 for (auto& rejectStatus : rejectSourceStates) {
4987 if (oldStatus == rejectStatus) {
4988 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
4989 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
4990 mStatus = oldStatus;
4991 return;
4992 }
4993 }
4994
4995 onStatusUpdatedLocked(cameraId, status);
4996}
4997
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004998status_t CameraService::getTorchStatusLocked(
4999 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005000 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005001 if (!status) {
5002 return BAD_VALUE;
5003 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005004 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5005 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005006 // invalid camera ID or the camera doesn't have a flash unit
5007 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005008 }
5009
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005010 *status = mTorchStatusMap.valueAt(index);
5011 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005012}
5013
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005014status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005015 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005016 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5017 if (index == NAME_NOT_FOUND) {
5018 return BAD_VALUE;
5019 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005020 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005021
5022 return OK;
5023}
5024
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005025std::list<String16> CameraService::getLogicalCameras(
5026 const String8& physicalCameraId) {
5027 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005028 Mutex::Autolock lock(mCameraStatesLock);
5029 for (const auto& state : mCameraStates) {
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005030 if (state.second->containsPhysicalCamera(physicalCameraId.c_str())) {
5031 retList.emplace_back(String16(state.first));
Shuzhen Wang43858162020-01-10 13:42:15 -08005032 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005033 }
5034 return retList;
5035}
5036
5037void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
5038 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
5039 SystemCameraKind deviceKind) {
5040 // mStatusListenerLock is expected to be locked
5041 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005042 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005043 // Note: we check only the deviceKind of the physical camera id
5044 // since, logical camera ids and their physical camera ids are
5045 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005046 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5047 listener->getListenerPid(), listener->getListenerUid())) {
5048 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005049 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005050 continue;
5051 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005052 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005053 logicalCameraId, physicalCameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005054 listener->handleBinderStatus(ret,
5055 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5056 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5057 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005058 }
5059 }
5060}
5061
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005062
Svet Ganova453d0d2018-01-11 15:37:58 -08005063void CameraService::blockClientsForUid(uid_t uid) {
5064 const auto clients = mActiveClientManager.getAll();
5065 for (auto& current : clients) {
5066 if (current != nullptr) {
5067 const auto basicClient = current->getValue();
5068 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5069 basicClient->block();
5070 }
5071 }
5072 }
5073}
5074
Michael Grooverd1d435a2018-12-18 17:39:42 -08005075void CameraService::blockAllClients() {
5076 const auto clients = mActiveClientManager.getAll();
5077 for (auto& current : clients) {
5078 if (current != nullptr) {
5079 const auto basicClient = current->getValue();
5080 if (basicClient.get() != nullptr) {
5081 basicClient->block();
5082 }
5083 }
5084 }
5085}
5086
Svet Ganova453d0d2018-01-11 15:37:58 -08005087// NOTE: This is a remote API - make sure all args are validated
5088status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
5089 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
5090 return PERMISSION_DENIED;
5091 }
5092 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5093 return BAD_VALUE;
5094 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005095 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005096 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07005097 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005098 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07005099 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005100 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005101 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
5102 return handleSetRotateAndCrop(args);
5103 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
5104 return handleGetRotateAndCrop(out);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005105 } else if (args.size() >= 2 && args[0] == String16("set-autoframing")) {
5106 return handleSetAutoframing(args);
5107 } else if (args.size() >= 1 && args[0] == String16("get-autoframing")) {
5108 return handleGetAutoframing(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005109 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
5110 return handleSetImageDumpMask(args);
5111 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
5112 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005113 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
5114 return handleSetCameraMute(args);
Shuzhen Wang16610a62022-12-15 22:38:07 -08005115 } else if (args.size() >= 2 && args[0] == String16("set-stream-use-case-override")) {
5116 return handleSetStreamUseCaseOverrides(args);
5117 } else if (args.size() >= 1 && args[0] == String16("clear-stream-use-case-override")) {
5118 handleClearStreamUseCaseOverrides();
5119 return OK;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005120 } else if (args.size() >= 2 && args[0] == String16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005121 return handleWatchCommand(args, in, out);
Ravneetaeb20dc2022-03-30 05:33:03 +00005122 } else if (args.size() >= 2 && args[0] == String16("set-watchdog")) {
5123 return handleSetCameraServiceWatchdog(args);
Svet Ganova453d0d2018-01-11 15:37:58 -08005124 } else if (args.size() == 1 && args[0] == String16("help")) {
5125 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005126 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005127 }
5128 printHelp(err);
5129 return BAD_VALUE;
5130}
5131
5132status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07005133 String16 packageName = args[1];
5134
Svet Ganova453d0d2018-01-11 15:37:58 -08005135 bool active = false;
5136 if (args[2] == String16("active")) {
5137 active = true;
5138 } else if ((args[2] != String16("idle"))) {
5139 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
5140 return BAD_VALUE;
5141 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005142
5143 int userId = 0;
5144 if (args.size() >= 5 && args[3] == String16("--user")) {
5145 userId = atoi(String8(args[4]));
5146 }
5147
5148 uid_t uid;
5149 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5150 return BAD_VALUE;
5151 }
5152
5153 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005154 return NO_ERROR;
5155}
5156
5157status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07005158 String16 packageName = args[1];
5159
5160 int userId = 0;
5161 if (args.size() >= 4 && args[2] == String16("--user")) {
5162 userId = atoi(String8(args[3]));
5163 }
5164
5165 uid_t uid;
5166 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005167 return BAD_VALUE;
5168 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005169
5170 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005171 return NO_ERROR;
5172}
5173
5174status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07005175 String16 packageName = args[1];
5176
5177 int userId = 0;
5178 if (args.size() >= 4 && args[2] == String16("--user")) {
5179 userId = atoi(String8(args[3]));
5180 }
5181
5182 uid_t uid;
5183 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005184 return BAD_VALUE;
5185 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005186
5187 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005188 return dprintf(out, "active\n");
5189 } else {
5190 return dprintf(out, "idle\n");
5191 }
5192}
5193
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005194status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
5195 int rotateValue = atoi(String8(args[1]));
5196 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
5197 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
5198 Mutex::Autolock lock(mServiceLock);
5199
5200 mOverrideRotateAndCropMode = rotateValue;
5201
5202 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
5203
5204 const auto clients = mActiveClientManager.getAll();
5205 for (auto& current : clients) {
5206 if (current != nullptr) {
5207 const auto basicClient = current->getValue();
5208 if (basicClient.get() != nullptr) {
5209 basicClient->setRotateAndCropOverride(rotateValue);
5210 }
5211 }
5212 }
5213
5214 return OK;
5215}
5216
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005217status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
5218 char* end;
5219 int autoframingValue = (int) strtol(String8(args[1]), &end, /*base=*/10);
5220 if ((*end != '\0') ||
5221 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
5222 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
5223 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
5224 return BAD_VALUE;
5225 }
5226
5227 Mutex::Autolock lock(mServiceLock);
5228 mOverrideAutoframingMode = autoframingValue;
5229
5230 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
5231
5232 const auto clients = mActiveClientManager.getAll();
5233 for (auto& current : clients) {
5234 if (current != nullptr) {
5235 const auto basicClient = current->getValue();
5236 if (basicClient.get() != nullptr) {
5237 basicClient->setAutoframingOverride(autoframingValue);
5238 }
5239 }
5240 }
5241
5242 return OK;
5243}
5244
Ravneetaeb20dc2022-03-30 05:33:03 +00005245status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
5246 int enableWatchdog = atoi(String8(args[1]));
5247
5248 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
5249
5250 Mutex::Autolock lock(mServiceLock);
5251
5252 mCameraServiceWatchdogEnabled = enableWatchdog;
5253
5254 const auto clients = mActiveClientManager.getAll();
5255 for (auto& current : clients) {
5256 if (current != nullptr) {
5257 const auto basicClient = current->getValue();
5258 if (basicClient.get() != nullptr) {
5259 basicClient->setCameraServiceWatchdog(enableWatchdog);
5260 }
5261 }
5262 }
5263
5264 return OK;
5265}
5266
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005267status_t CameraService::handleGetRotateAndCrop(int out) {
5268 Mutex::Autolock lock(mServiceLock);
5269
5270 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
5271}
5272
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005273status_t CameraService::handleGetAutoframing(int out) {
5274 Mutex::Autolock lock(mServiceLock);
5275
5276 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
5277}
5278
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005279status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
5280 char *endPtr;
5281 errno = 0;
5282 String8 maskString8 = String8(args[1]);
5283 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
5284
5285 if (errno != 0) return BAD_VALUE;
5286 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
5287 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
5288
5289 Mutex::Autolock lock(mServiceLock);
5290
5291 mImageDumpMask = maskValue;
5292
5293 return OK;
5294}
5295
5296status_t CameraService::handleGetImageDumpMask(int out) {
5297 Mutex::Autolock lock(mServiceLock);
5298
5299 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
5300}
5301
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005302status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
5303 int muteValue = strtol(String8(args[1]), nullptr, 10);
5304 if (errno != 0) return BAD_VALUE;
5305
5306 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
5307 Mutex::Autolock lock(mServiceLock);
5308
5309 mOverrideCameraMuteMode = (muteValue == 1);
5310
5311 const auto clients = mActiveClientManager.getAll();
5312 for (auto& current : clients) {
5313 if (current != nullptr) {
5314 const auto basicClient = current->getValue();
5315 if (basicClient.get() != nullptr) {
5316 if (basicClient->supportsCameraMute()) {
5317 basicClient->setCameraMute(mOverrideCameraMuteMode);
5318 }
5319 }
5320 }
5321 }
5322
5323 return OK;
5324}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005325
Shuzhen Wang16610a62022-12-15 22:38:07 -08005326status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
5327 std::vector<int64_t> useCasesOverride;
5328 for (size_t i = 1; i < args.size(); i++) {
5329 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
5330 String8 arg8 = String8(args[i]);
5331 if (arg8 == "DEFAULT") {
5332 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
5333 } else if (arg8 == "PREVIEW") {
5334 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
5335 } else if (arg8 == "STILL_CAPTURE") {
5336 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
5337 } else if (arg8 == "VIDEO_RECORD") {
5338 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
5339 } else if (arg8 == "PREVIEW_VIDEO_STILL") {
5340 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
5341 } else if (arg8 == "VIDEO_CALL") {
5342 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
5343 } else if (arg8 == "CROPPED_RAW") {
5344 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
5345 } else {
5346 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg8.c_str());
5347 return BAD_VALUE;
5348 }
5349 useCasesOverride.push_back(useCase);
5350 }
5351
5352 Mutex::Autolock lock(mServiceLock);
5353 mStreamUseCaseOverrides = std::move(useCasesOverride);
5354
5355 return OK;
5356}
5357
5358void CameraService::handleClearStreamUseCaseOverrides() {
5359 Mutex::Autolock lock(mServiceLock);
5360 mStreamUseCaseOverrides.clear();
5361}
5362
Avichal Rakesh84147132021-11-11 17:47:11 -08005363status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005364 if (args.size() >= 3 && args[1] == String16("start")) {
5365 return startWatchingTags(args, outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005366 } else if (args.size() == 2 && args[1] == String16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005367 return stopWatchingTags(outFd);
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005368 } else if (args.size() == 2 && args[1] == String16("dump")) {
5369 return printWatchedTags(outFd);
5370 } else if (args.size() >= 2 && args[1] == String16("live")) {
5371 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005372 } else if (args.size() == 2 && args[1] == String16("clear")) {
5373 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005374 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005375 dprintf(outFd, "Camera service watch commands:\n"
5376 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
5377 " starts watching the provided tags for clients with provided package\n"
5378 " recognizes tag shorthands like '3a'\n"
5379 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005380 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005381 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005382 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005383 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08005384 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005385 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005386 return BAD_VALUE;
5387}
5388
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005389status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
5390 Mutex::Autolock lock(mLogLock);
5391 size_t tagsIdx; // index of '-m'
5392 String16 tags("");
5393 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != String16("-m"); tagsIdx++);
5394 if (tagsIdx < args.size() - 1) {
5395 tags = args[tagsIdx + 1];
5396 } else {
5397 dprintf(outFd, "No tags provided.\n");
5398 return BAD_VALUE;
5399 }
5400
5401 size_t clientsIdx; // index of '-c'
5402 String16 clients = kWatchAllClientsFlag; // watch all clients if no clients are provided
5403 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != String16("-c");
5404 clientsIdx++);
5405 if (clientsIdx < args.size() - 1) {
5406 clients = args[clientsIdx + 1];
5407 }
5408 parseClientsToWatchLocked(String8(clients));
5409
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005410 // track tags to initialize future clients with the monitoring information
5411 mMonitorTags = String8(tags);
5412
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005413 bool serviceLock = tryLock(mServiceLock);
5414 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005415 auto cameraClients = mActiveClientManager.getAll();
5416 for (const auto &clientDescriptor: cameraClients) {
5417 if (clientDescriptor == nullptr) { continue; }
5418 sp<BasicClient> client = clientDescriptor->getValue();
5419 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005420
5421 if (isClientWatchedLocked(client.get())) {
5422 client->startWatchingTags(mMonitorTags, outFd);
5423 numWatchedClients++;
5424 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005425 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005426 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
5427
5428 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005429 return OK;
5430}
5431
5432status_t CameraService::stopWatchingTags(int outFd) {
5433 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005434 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005435 mMonitorTags = String8::empty();
5436
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005437 mWatchedClientPackages.clear();
5438 mWatchedClientsDumpCache.clear();
5439
5440 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005441 auto cameraClients = mActiveClientManager.getAll();
5442 for (const auto &clientDescriptor : cameraClients) {
5443 if (clientDescriptor == nullptr) { continue; }
5444 sp<BasicClient> client = clientDescriptor->getValue();
5445 if (client.get() == nullptr) { continue; }
5446 client->stopWatchingTags(outFd);
5447 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005448 dprintf(outFd, "Stopped watching all clients.\n");
5449 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005450 return OK;
5451}
5452
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005453status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
5454 Mutex::Autolock lock(mLogLock);
5455 size_t clearedSize = mWatchedClientsDumpCache.size();
5456 mWatchedClientsDumpCache.clear();
5457 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
5458 return OK;
5459}
5460
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005461status_t CameraService::printWatchedTags(int outFd) {
5462 Mutex::Autolock logLock(mLogLock);
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08005463 std::set<String16> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005464
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005465 bool printedSomething = false; // tracks if any monitoring information was printed
5466 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005467
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005468 bool serviceLock = tryLock(mServiceLock);
5469 // get all watched clients that are currently connected
5470 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
5471 if (clientDescriptor == nullptr) { continue; }
5472
5473 sp<BasicClient> client = clientDescriptor->getValue();
5474 if (client.get() == nullptr) { continue; }
5475 if (!isClientWatchedLocked(client.get())) { continue; }
5476
5477 std::vector<std::string> dumpVector;
5478 client->dumpWatchedEventsToVector(dumpVector);
5479
5480 size_t printIdx = dumpVector.size();
5481 if (printIdx == 0) {
5482 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005483 }
5484
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005485 // Print tag dumps for active client
5486 const String8 &cameraId = clientDescriptor->getKey();
5487 String8 packageName8 = String8(client->getPackageName());
5488 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
5489 dprintf(outFd, "Client: %s (active)\n", printablePackageName);
5490 while(printIdx > 0) {
5491 printIdx--;
5492 dprintf(outFd, "%s:%s %s", cameraId.string(), printablePackageName,
5493 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005494 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005495 dprintf(outFd, "\n");
5496 packageName8.unlockBuffer();
5497 printedSomething = true;
5498
5499 connectedMonitoredClients.emplace(client->getPackageName());
5500 }
5501 if (serviceLock) { mServiceLock.unlock(); }
5502
5503 // Print entries in mWatchedClientsDumpCache for clients that are not connected
5504 for (const auto &kv: mWatchedClientsDumpCache) {
5505 const String16 &package = kv.first;
5506 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
5507 continue;
5508 }
5509
5510 dprintf(outFd, "Client: %s (cached)\n", String8(package).string());
5511 dprintf(outFd, "%s\n", kv.second.c_str());
5512 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005513 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005514
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005515 if (!printedSomething) {
5516 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005517 }
5518
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005519 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005520}
5521
Avichal Rakesh84147132021-11-11 17:47:11 -08005522// Print all events in vector `events' that came after lastPrintedEvent
5523void printNewWatchedEvents(int outFd,
5524 const char *cameraId,
5525 const String16 &packageName,
5526 const std::vector<std::string> &events,
5527 const std::string &lastPrintedEvent) {
5528 if (events.empty()) { return; }
5529
5530 // index of lastPrintedEvent in events.
5531 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
5532 size_t lastPrintedIdx;
5533 for (lastPrintedIdx = 0;
5534 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
5535 lastPrintedIdx++);
5536
5537 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
5538
5539 String8 packageName8(packageName);
5540 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
5541
5542 // print events in chronological order (latest event last)
5543 size_t idxToPrint = lastPrintedIdx;
5544 do {
5545 idxToPrint--;
5546 dprintf(outFd, "%s:%s %s", cameraId, printablePackageName, events[idxToPrint].c_str());
5547 } while (idxToPrint != 0);
5548
5549 packageName8.unlockBuffer();
5550}
5551
5552// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
5553// command should be interrupted if the user presses the return key, or if user loses any way to
5554// signal interrupt.
5555// If timeoutMs == 0, this function will always return false
5556bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
5557 struct timeval startTime;
5558 int startTimeError = gettimeofday(&startTime, nullptr);
5559 if (startTimeError) {
5560 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5561 return true;
5562 }
5563
5564 const nfds_t numFds = 1;
5565 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
5566
5567 struct timeval currTime;
5568 char buffer[2];
5569 while(true) {
5570 int currTimeError = gettimeofday(&currTime, nullptr);
5571 if (currTimeError) {
5572 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5573 return true;
5574 }
5575
5576 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
5577 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
5578 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
5579
5580 if (remainingTimeMs <= 0) {
5581 // No user interrupt within timeoutMs, don't interrupt watch command
5582 return false;
5583 }
5584
5585 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
5586 if (numFdsUpdated < 0) {
5587 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5588 return true;
5589 }
5590
5591 if (numFdsUpdated == 0) {
5592 // No user input within timeoutMs, don't interrupt watch command
5593 return false;
5594 }
5595
5596 if (!(pollFd.revents & POLLIN)) {
5597 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5598 return true;
5599 }
5600
5601 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
5602 if (sizeRead < 0) {
5603 dprintf(outFd, "Error reading user input. Exiting.\n");
5604 return true;
5605 }
5606
5607 if (sizeRead == 0) {
5608 // Reached end of input fd (can happen if input is piped)
5609 // User has no way to signal an interrupt, so interrupt here
5610 return true;
5611 }
5612
5613 if (buffer[0] == '\n') {
5614 // User pressed return, interrupt watch command.
5615 return true;
5616 }
5617 }
5618}
5619
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005620status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
5621 int inFd, int outFd) {
5622 // Figure out refresh interval, if present in args
5623 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005624 if (args.size() > 2) {
5625 size_t intervalIdx; // index of '-n'
5626 for (intervalIdx = 2; intervalIdx < args.size() && String16("-n") != args[intervalIdx];
5627 intervalIdx++);
5628
5629 size_t intervalValIdx = intervalIdx + 1;
5630 if (intervalValIdx < args.size()) {
5631 refreshTimeoutMs = strtol(String8(args[intervalValIdx].string()), nullptr, 10);
5632 if (errno) { return BAD_VALUE; }
5633 }
5634 }
5635
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005636 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
5637 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005638
Avichal Rakesh84147132021-11-11 17:47:11 -08005639 dprintf(outFd, "Press return to exit...\n\n");
Avichal Rakesha14d9832021-11-11 01:41:55 -08005640 std::map<String16, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005641
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005642 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005643 bool serviceLock = tryLock(mServiceLock);
5644 auto cameraClients = mActiveClientManager.getAll();
5645 if (serviceLock) { mServiceLock.unlock(); }
5646
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005647 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005648 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005649 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005650
5651 sp<BasicClient> client = clientDescriptor->getValue();
5652 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005653 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005654
Avichal Rakesha14d9832021-11-11 01:41:55 -08005655 const String16 &packageName = client->getPackageName();
5656 // This also initializes the map entries with an empty string
5657 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
5658
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005659 std::vector<std::string> latestEvents;
5660 client->dumpWatchedEventsToVector(latestEvents);
5661
5662 if (!latestEvents.empty()) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005663 String8 cameraId = clientDescriptor->getKey();
5664 const char *printableCameraId = cameraId.lockBuffer(cameraId.size());
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005665 printNewWatchedEvents(outFd,
Avichal Rakesha14d9832021-11-11 01:41:55 -08005666 printableCameraId,
5667 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005668 latestEvents,
5669 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08005670 packageNameToLastEvent[packageName] = latestEvents[0];
5671 cameraId.unlockBuffer();
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005672 }
5673 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005674 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005675 break;
5676 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005677 }
5678 return OK;
5679}
5680
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005681void CameraService::parseClientsToWatchLocked(String8 clients) {
5682 mWatchedClientPackages.clear();
5683
5684 const char *allSentinel = String8(kWatchAllClientsFlag).string();
5685
5686 char *tokenized = clients.lockBuffer(clients.size());
5687 char *savePtr;
5688 char *nextClient = strtok_r(tokenized, ",", &savePtr);
5689
5690 while (nextClient != nullptr) {
5691 if (strcmp(nextClient, allSentinel) == 0) {
5692 // Don't need to track any other package if 'all' is present
5693 mWatchedClientPackages.clear();
5694 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
5695 break;
5696 }
5697
5698 // track package names
5699 mWatchedClientPackages.emplace(nextClient);
5700 nextClient = strtok_r(nullptr, ",", &savePtr);
5701 }
5702 clients.unlockBuffer();
5703}
5704
Svet Ganova453d0d2018-01-11 15:37:58 -08005705status_t CameraService::printHelp(int out) {
5706 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07005707 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
5708 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
5709 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005710 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
5711 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
5712 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005713 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
5714 " Valid values 0=false, 1=true, 2=auto\n"
5715 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005716 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
5717 " Valid values 0=OFF, 1=ON for JPEG\n"
5718 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005719 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08005720 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
5721 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
5722 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
5723 " on. In case the number of usecases is smaller than the number of streams, the\n"
5724 " last use case is assigned to all the remaining streams. In case of multiple\n"
5725 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
5726 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
5727 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
5728 " clear-stream-use-case-override clear the stream use case override\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005729 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08005730 " help print this message\n");
5731}
5732
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005733bool CameraService::isClientWatched(const BasicClient *client) {
5734 Mutex::Autolock lock(mLogLock);
5735 return isClientWatchedLocked(client);
5736}
5737
5738bool CameraService::isClientWatchedLocked(const BasicClient *client) {
5739 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
5740 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
5741}
5742
Yin-Chia Yehdba03232019-08-19 15:54:28 -07005743int32_t CameraService::updateAudioRestriction() {
5744 Mutex::Autolock lock(mServiceLock);
5745 return updateAudioRestrictionLocked();
5746}
5747
5748int32_t CameraService::updateAudioRestrictionLocked() {
5749 int32_t mode = 0;
5750 // iterate through all active client
5751 for (const auto& i : mActiveClientManager.getAll()) {
5752 const auto clientSp = i->getValue();
5753 mode |= clientSp->getAudioRestriction();
5754 }
5755
5756 bool modeChanged = (mAudioRestriction != mode);
5757 mAudioRestriction = mode;
5758 if (modeChanged) {
5759 mAppOps.setCameraAudioRestriction(mode);
5760 }
5761 return mode;
5762}
5763
Cliff Wu646bd612021-11-23 23:21:29 +08005764status_t CameraService::checkIfInjectionCameraIsPresent(const String8& externalCamId,
5765 sp<BasicClient> clientSp) {
5766 std::unique_ptr<AutoConditionLock> lock =
5767 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
5768 status_t res = NO_ERROR;
5769 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
5770 ALOGW("Device %s is not usable!", externalCamId.string());
5771 mInjectionStatusListener->notifyInjectionError(
5772 externalCamId, UNKNOWN_TRANSACTION);
5773 clientSp->notifyError(
5774 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
5775 CaptureResultExtras());
5776
5777 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
5778 // other clients from connecting in mServiceLockWrapper if held
5779 mServiceLock.unlock();
5780
5781 // Clear caller identity temporarily so client disconnect PID checks work correctly
5782 int64_t token = CameraThreadState::clearCallingIdentity();
5783 clientSp->disconnect();
5784 CameraThreadState::restoreCallingIdentity(token);
5785
5786 // Reacquire mServiceLock
5787 mServiceLock.lock();
5788 }
5789
5790 return res;
5791}
5792
Cliff Wud3a05312021-04-26 23:07:31 +08005793void CameraService::clearInjectionParameters() {
5794 {
5795 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08005796 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08005797 mInjectionInternalCamId = "";
5798 }
5799 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08005800 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08005801}
5802
Mathias Agopian65ab4712010-07-14 17:59:35 -07005803}; // namespace android