blob: b4f1ace7b773f9189810197e7c999dae75947eaf [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>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080072
Ruben Brunkb2119af2014-05-09 19:57:56 -070073#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070074
75#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070076#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070077#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070078#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000079#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070080#include "utils/CameraThreadState.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070081#include "utils/CameraServiceProxyWrapper.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070082
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080083namespace {
84 const char* kPermissionServiceName = "permission";
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080085 const char* kActivityServiceName = "activity";
86 const char* kSensorPrivacyServiceName = "sensor_privacy";
87 const char* kAppopsServiceName = "appops";
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080088}; // namespace anonymous
89
Mathias Agopian65ab4712010-07-14 17:59:35 -070090namespace android {
91
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070092using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080093using binder::Status;
Austin Borgerea931242021-12-13 23:10:41 +000094using namespace camera3;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070095using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -070096using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080097using hardware::ICamera;
98using hardware::ICameraClient;
99using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800100using hardware::camera2::ICameraInjectionCallback;
101using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800102using hardware::camera2::utils::CameraIdAndSessionConfiguration;
103using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800104
Mathias Agopian65ab4712010-07-14 17:59:35 -0700105// ----------------------------------------------------------------------------
106// Logging support -- this is for debugging only
107// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700108volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109
Steve Blockb8a80522011-12-20 16:23:08 +0000110#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
111#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700112
113static void setLogLevel(int level) {
114 android_atomic_write(level, &gLogLevel);
115}
116
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800117// Convenience methods for constructing binder::Status objects for error returns
118
119#define STATUS_ERROR(errorCode, errorString) \
120 binder::Status::fromServiceSpecificError(errorCode, \
121 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
122
123#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
124 binder::Status::fromServiceSpecificError(errorCode, \
125 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
126 __VA_ARGS__))
127
Mathias Agopian65ab4712010-07-14 17:59:35 -0700128// ----------------------------------------------------------------------------
129
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700130static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800131static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700132static const String16 sCameraPermission("android.permission.CAMERA");
133static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
134static const String16
135 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Shuzhen Wang695044d2020-03-06 09:02:23 -0800136static const String16 sCameraOpenCloseListenerPermission(
137 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Cliff Wud8cae102021-03-11 01:37:42 +0800138static const String16
139 sCameraInjectExternalCameraPermission("android.permission.CAMERA_INJECT_EXTERNAL_CAMERA");
Rucha Katakwardf223072021-06-15 10:21:00 -0700140const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800141static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
142static constexpr int32_t kSystemNativeClientState =
143 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700144
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800145const String8 CameraService::kOfflineDevice("offline-");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -0700146const String16 CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700147
Rucha Katakward9ea6452021-05-06 11:57:16 -0700148// Set to keep track of logged service error events.
149static std::set<String8> sServiceErrorEventSet;
150
Austin Borger74fca042022-05-23 12:41:21 -0700151CameraService::CameraService(
152 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper) :
153 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
154 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800155 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800156 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700157 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700158 mSoundRef(0), mInitialized(false),
159 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000160 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800161 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700162 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
163 if (mMemFd == -1) {
164 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
165 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700166}
167
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800168// The word 'System' here does not refer to clients only on the system
169// partition. They just need to have a android system uid.
170static bool doesClientHaveSystemUid() {
171 return (CameraThreadState::getCallingUid() < AID_APP_START);
172}
173
Charles Chena7b613c2023-01-24 21:57:33 +0000174// Enable processes with isolated AID to request the binder
175void CameraService::instantiate() {
176 CameraService::publish(true);
177}
178
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800179void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
180 if (name != String16(kAppopsServiceName)) {
181 return;
182 }
183
184 ALOGV("appops service registered. setting camera audio restriction");
185 mAppOps.setCameraAudioRestriction(mAudioRestriction);
186}
187
Iliyan Malchev8951a972011-04-14 16:55:59 -0700188void CameraService::onFirstRef()
189{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700190
Ruben Brunkcc776712015-02-17 20:18:47 -0800191 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800192
Iliyan Malchev8951a972011-04-14 16:55:59 -0700193 BnCameraService::onFirstRef();
194
Ruben Brunk99e69712015-05-26 17:25:07 -0700195 // Update battery life tracking if service is restarting
196 BatteryNotifier& notifier(BatteryNotifier::getInstance());
197 notifier.noteResetCamera();
198 notifier.noteResetFlashlight();
199
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800200 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800201
Emilian Peevf53f66e2017-04-11 14:29:43 +0100202 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800203 if (res == OK) {
204 mInitialized = true;
205 }
206
Svet Ganova453d0d2018-01-11 15:37:58 -0800207 mUidPolicy = new UidPolicy(this);
208 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800209 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
210 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800211 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800212
213 // appops function setCamerAudioRestriction uses getService which
214 // is blocking till the appops service is ready. To enable early
215 // boot availability for cameraservice, use checkService which is
216 // non blocking and register for notifications
217 sp<IServiceManager> sm = defaultServiceManager();
218 sp<IBinder> binder = sm->checkService(String16(kAppopsServiceName));
219 if (!binder) {
220 sm->registerForNotifications(String16(kAppopsServiceName), this);
221 } else {
222 mAppOps.setCameraAudioRestriction(mAudioRestriction);
223 }
224
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700225 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
226 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000227 // Deprecated, so it will fail to register on newer devices
228 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700229 __FUNCTION__);
230 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700231
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700232 if (!AidlCameraService::registerService(this)) {
233 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
234 }
235
Shuzhen Wang24b44152019-09-20 10:38:11 -0700236 // This needs to be last call in this function, so that it's as close to
237 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700238 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700239 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800240}
241
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800242status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800243 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100244
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800245 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000246 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800247 {
248 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800249
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800250 if (nullptr == mCameraProviderManager.get()) {
251 mCameraProviderManager = new CameraProviderManager();
252 res = mCameraProviderManager->initialize(this);
253 if (res != OK) {
254 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
255 __FUNCTION__, strerror(-res), res);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700256 logServiceError(String8::format("Unable to initialize camera provider manager"),
257 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800258 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100259 }
260 }
261
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800262
263 // Setup vendor tags before we call get_camera_info the first time
264 // because HAL might need to setup static vendor keys in get_camera_info
265 // TODO: maybe put this into CameraProviderManager::initialize()?
266 mCameraProviderManager->setUpVendorTags();
267
268 if (nullptr == mFlashlight.get()) {
269 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700270 }
271
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800272 res = mFlashlight->findFlashUnits();
273 if (res != OK) {
274 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
275 }
276
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000277 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800278 }
279
280
281 for (auto& cameraId : deviceIds) {
282 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800283 if (getCameraState(id8) == nullptr) {
284 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
285 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000286 if (unavailPhysicalIds.count(cameraId) > 0) {
287 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
288 String8 physicalId8 = String8(physicalId.c_str());
289 onDeviceStatusChanged(id8, physicalId8, CameraDeviceStatus::NOT_PRESENT);
290 }
291 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800292 }
293
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700294 // Derive primary rear/front cameras, and filter their charactierstics.
295 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700296 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700297 // Assume internal cameras are advertised from the same
298 // provider. If multiple providers are registered at different time,
299 // and each provider contains multiple internal color cameras, the current
300 // logic may filter the characteristics of more than one front/rear color
301 // cameras.
302 Mutex::Autolock l(mServiceLock);
303 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700304 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700305
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800306 return OK;
307}
308
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700309void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status,
310 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800311 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800312 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700313 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
314 i->getListenerUid())) {
315 ALOGV("Skipping torch callback for system-only camera device %s",
316 cameraId.c_str());
317 continue;
318 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700319 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
320 String16{cameraId});
321 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
322 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800323 }
324}
325
Mathias Agopian65ab4712010-07-14 17:59:35 -0700326CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800327 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800328 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800329 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800330 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700331}
332
Emilian Peevaee727d2017-05-04 16:35:48 +0100333void CameraService::onNewProviderRegistered() {
334 enumerateProviders();
335}
336
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700337void CameraService::filterAPI1SystemCameraLocked(
338 const std::vector<std::string> &normalDeviceIds) {
339 mNormalDeviceIdsWithoutSystemCamera.clear();
340 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700341 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
342 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
343 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
344 continue;
345 }
346 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700347 // All system camera ids will necessarily come after public camera
348 // device ids as per the HAL interface contract.
349 break;
350 }
351 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
352 }
353 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
354 mNormalDeviceIdsWithoutSystemCamera.size());
355}
356
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700357status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
358 auto state = getCameraState(cameraId);
359 if (state != nullptr) {
360 *kind = state->getSystemCameraKind();
361 return OK;
362 }
363 // Hidden physical camera ids won't have CameraState
364 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
365}
366
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800367void CameraService::updateCameraNumAndIds() {
368 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700369 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
370 // Excludes hidden secure cameras
371 mNumberOfCameras =
372 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
373 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800374 mNormalDeviceIds =
375 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700376 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800377}
378
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700379void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700380 // To claim to be S Performance primary cameras, the cameras must be
381 // backward compatible. So performance class primary camera Ids must be API1
382 // compatible.
383 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
384 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
385 int facing = -1;
386 int orientation = 0;
387 String8 cameraId8(cameraId.c_str());
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800388 int portraitRotation;
389 getDeviceVersion(cameraId8, /*overrideToPortrait*/false, /*out*/&portraitRotation,
390 /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700391 if (facing == -1) {
392 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
393 return;
394 }
395
396 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
397 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700398 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
399 if (res == OK) {
400 mPerfClassPrimaryCameraIds.insert(cameraId);
401 } else {
402 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
403 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
404 break;
405 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700406
407 if (facing == hardware::CAMERA_FACING_BACK) {
408 firstRearCameraSeen = true;
409 }
410 if (facing == hardware::CAMERA_FACING_FRONT) {
411 firstFrontCameraSeen = true;
412 }
413 }
414
415 if (firstRearCameraSeen && firstFrontCameraSeen) {
416 break;
417 }
418 }
419}
420
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100421void CameraService::addStates(const String8 id) {
422 std::string cameraId(id.c_str());
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700423 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100424 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
425 if (res != OK) {
426 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
427 return;
428 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000429 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700430 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
431 if (res != OK) {
432 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
433 return;
434 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000435 std::vector<std::string> physicalCameraIds;
436 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100437 std::set<String8> conflicting;
438 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
439 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
440 }
441
442 {
443 Mutex::Autolock lock(mCameraStatesLock);
444 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000445 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100446 }
447
448 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100449 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100450 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800451
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700452 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100453 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800454
455 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100456 logDeviceAdded(id, "Device added");
457}
458
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100459void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800460 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100461 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100462 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100463 mTorchStatusMap.removeItem(id);
464 }
465
466 {
467 Mutex::Autolock lock(mCameraStatesLock);
468 mCameraStates.erase(id);
469 }
470}
471
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800472void CameraService::onDeviceStatusChanged(const String8& id,
473 CameraDeviceStatus newHalStatus) {
474 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
475 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700476
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800477 StatusInternal newStatus = mapToInternal(newHalStatus);
478
Ruben Brunkcc776712015-02-17 20:18:47 -0800479 std::shared_ptr<CameraState> state = getCameraState(id);
480
481 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700482 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100483 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700484 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100485
486 // First add as absent to make sure clients are notified below
487 addStates(id);
488
489 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700490 } else {
491 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
492 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700493 return;
494 }
495
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800496 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800497
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800498 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800499 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700500 return;
501 }
502
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800503 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700504 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
505 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800506
507 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
508 // to this device until the status changes
509 updateStatus(StatusInternal::NOT_PRESENT, id);
510
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800511 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700512 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800513 // Don't do this in updateStatus to avoid deadlock over mServiceLock
514 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700515
Ruben Brunkcc776712015-02-17 20:18:47 -0800516 // Remove cached shim parameters
517 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700518
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800519 // Remove online as well as offline client from the list of active clients,
520 // if they are present
521 clientToDisconnectOnline = removeClientLocked(id);
522 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700523 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800524
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800525 disconnectClient(id, clientToDisconnectOnline);
526 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700527
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100528 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800529 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800530 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700531 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
532 newStatus));
533 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800534 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700535 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800536}
Igor Murashkincba2c162013-03-20 15:56:31 -0700537
Shuzhen Wang43858162020-01-10 13:42:15 -0800538void CameraService::onDeviceStatusChanged(const String8& id,
539 const String8& physicalId,
540 CameraDeviceStatus newHalStatus) {
541 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
542 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
543
544 StatusInternal newStatus = mapToInternal(newHalStatus);
545
546 std::shared_ptr<CameraState> state = getCameraState(id);
547
548 if (state == nullptr) {
549 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000550 __FUNCTION__, physicalId.string(), id.string());
Shuzhen Wang43858162020-01-10 13:42:15 -0800551 return;
552 }
553
554 StatusInternal logicalCameraStatus = state->getStatus();
555 if (logicalCameraStatus != StatusInternal::PRESENT &&
556 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
557 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
558 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
559 return;
560 }
561
562 bool updated = false;
563 if (newStatus == StatusInternal::PRESENT) {
564 updated = state->removeUnavailablePhysicalId(physicalId);
565 } else {
566 updated = state->addUnavailablePhysicalId(physicalId);
567 }
568
569 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800570 String8 idCombo = id + " : " + physicalId;
571 if (newStatus == StatusInternal::PRESENT) {
572 logDeviceAdded(idCombo,
573 String8::format("Device status changed to %d", newStatus));
574 } else {
575 logDeviceRemoved(idCombo,
576 String8::format("Device status changed to %d", newStatus));
577 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700578 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
579 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
580 if (getSystemCameraKind(id, &deviceKind) != OK) {
581 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
582 return;
583 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800584 String16 id16(id), physicalId16(physicalId);
585 Mutex::Autolock lock(mStatusListenerLock);
586 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700587 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
588 listener->getListenerPid(), listener->getListenerUid())) {
589 ALOGV("Skipping discovery callback for system-only camera device %s",
590 id.c_str());
591 continue;
592 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700593 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
594 mapToInterface(newStatus), id16, physicalId16);
595 listener->handleBinderStatus(ret,
596 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
597 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
598 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800599 }
600 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700601}
602
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800603void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
604 if (clientToDisconnect.get() != nullptr) {
605 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
606 __FUNCTION__, id.string());
607 // Notify the client of disconnection
608 clientToDisconnect->notifyError(
609 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
610 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800611 clientToDisconnect->disconnect();
612 }
613}
614
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800615void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800616 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700617 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
618 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
619 if (res != OK) {
620 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
621 cameraId.string());
622 return;
623 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800624 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700625 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800626}
627
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700628
629void CameraService::onTorchStatusChanged(const String8& cameraId,
630 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
631 Mutex::Autolock al(mTorchStatusMutex);
632 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
633}
634
Rucha Katakwar38284522021-11-10 11:25:21 -0800635void CameraService::broadcastTorchStrengthLevel(const String8& cameraId,
636 int32_t newStrengthLevel) {
637 Mutex::Autolock lock(mStatusListenerLock);
638 for (auto& i : mListenerList) {
Austin Borgere8e2c422022-05-12 13:45:24 -0700639 auto ret = i->getListener()->onTorchStrengthLevelChanged(String16{cameraId},
Rucha Katakwar38284522021-11-10 11:25:21 -0800640 newStrengthLevel);
Austin Borgere8e2c422022-05-12 13:45:24 -0700641 i->handleBinderStatus(ret,
642 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
643 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800644 }
645}
646
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800647void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700648 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800649 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
650 __FUNCTION__, cameraId.string(), newStatus);
651
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800652 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800653 status_t res = getTorchStatusLocked(cameraId, &status);
654 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700655 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
656 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800657 return;
658 }
659 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800660 return;
661 }
662
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800663 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800664 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800665 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
666 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800667 return;
668 }
669
Ruben Brunkcc776712015-02-17 20:18:47 -0800670 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700671 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700672 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700673 auto iter = mTorchUidMap.find(cameraId);
674 if (iter != mTorchUidMap.end()) {
675 int oldUid = iter->second.second;
676 int newUid = iter->second.first;
677 BatteryNotifier& notifier(BatteryNotifier::getInstance());
678 if (oldUid != newUid) {
679 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800680 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700681 notifier.noteFlashlightOff(cameraId, oldUid);
682 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800683 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700684 notifier.noteFlashlightOn(cameraId, newUid);
685 }
686 iter->second.second = newUid;
687 } else {
688 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800689 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700690 notifier.noteFlashlightOn(cameraId, oldUid);
691 } else {
692 notifier.noteFlashlightOff(cameraId, oldUid);
693 }
694 }
695 }
696 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700697 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800698}
699
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700700static bool isAutomotiveDevice() {
701 // Checks the property ro.hardware.type and returns true if it is
702 // automotive.
703 char value[PROPERTY_VALUE_MAX] = {0};
704 property_get("ro.hardware.type", value, "");
705 return strncmp(value, "automotive", PROPERTY_VALUE_MAX) == 0;
706}
707
708static bool isAutomotivePrivilegedClient(int32_t uid) {
709 // Returns false if this is not an automotive device type.
710 if (!isAutomotiveDevice())
711 return false;
712
713 // Returns true if the uid is AID_AUTOMOTIVE_EVS which is a
714 // privileged client uid used for safety critical use cases such as
715 // rear view and surround view.
716 return uid == AID_AUTOMOTIVE_EVS;
717}
718
719bool CameraService::isAutomotiveExteriorSystemCamera(const String8& cam_id) const{
720 // Returns false if this is not an automotive device type.
721 if (!isAutomotiveDevice())
722 return false;
723
724 // Returns false if no camera id is provided.
725 if (cam_id.isEmpty())
726 return false;
727
728 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
729 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
730 // This isn't a known camera ID, so it's not a system camera.
731 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
732 return false;
733 }
734
735 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
736 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
737 return false;
738 }
739
740 CameraMetadata cameraInfo;
741 status_t res = mCameraProviderManager->getCameraCharacteristics(
742 cam_id.string(), false, &cameraInfo, false);
743 if (res != OK){
744 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
745 cam_id.c_str());
746 return false;
747 }
748
749 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
750 if (auto_location.count != 1)
751 return false;
752
753 uint8_t location = auto_location.data.u8[0];
754 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
755 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
756 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
757 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
758 return false;
759 }
760
761 return true;
762}
763
764bool CameraService::checkPermission(const String8& cam_id, const String16& permission,
765 const AttributionSourceState& attributionSource,const String16& message,
766 int32_t attributedOpCode) const{
767 if (isAutomotivePrivilegedClient(attributionSource.uid)) {
768 // If cam_id is empty, then it means that this check is not used for the
769 // purpose of accessing a specific camera, hence grant permission just
770 // based on uid to the automotive privileged client.
771 if (cam_id.isEmpty())
772 return true;
773 // If this call is used for accessing a specific camera then cam_id must be provided.
774 // In that case, only pre-grants the permission for accessing the exterior system only
775 // camera.
776 return isAutomotiveExteriorSystemCamera(cam_id);
777
778 }
779
Joanne Chung02c13d02023-01-16 12:58:05 +0000780 permission::PermissionChecker permissionChecker;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700781 return permissionChecker.checkPermissionForPreflight(permission, attributionSource,
782 message, attributedOpCode) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
783}
784
785bool CameraService::hasPermissionsForSystemCamera(const String8& cam_id, int callingPid,
786 int callingUid) const{
Joanne Chung02c13d02023-01-16 12:58:05 +0000787 AttributionSourceState attributionSource{};
788 attributionSource.pid = callingPid;
789 attributionSource.uid = callingUid;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700790 bool checkPermissionForSystemCamera = checkPermission(cam_id,
791 sSystemCameraPermission, attributionSource, String16(), AppOpsManager::OP_NONE);
792 bool checkPermissionForCamera = checkPermission(cam_id,
793 sCameraPermission, attributionSource, String16(), AppOpsManager::OP_NONE);
Joanne Chung02c13d02023-01-16 12:58:05 +0000794 return checkPermissionForSystemCamera && checkPermissionForCamera;
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700795}
796
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800797Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700798 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100799 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700800 bool hasSystemCameraPermissions =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700801 hasPermissionsForSystemCamera(String8(), CameraThreadState::getCallingPid(),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700802 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700803 switch (type) {
804 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700805 if (hasSystemCameraPermissions) {
806 *numCameras = static_cast<int>(mNormalDeviceIds.size());
807 } else {
808 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
809 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800810 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700811 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700812 if (hasSystemCameraPermissions) {
813 *numCameras = mNumberOfCameras;
814 } else {
815 *numCameras = mNumberOfCamerasWithoutSystemCamera;
816 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800817 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700818 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800819 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700820 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800821 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
822 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700823 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800824 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825}
826
Austin Borger18b30a72022-10-27 12:20:29 -0700827Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800828 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700829 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100830 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700831 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
832 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
833 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
834 "characteristics for system only device %s: ", cameraIdStr.c_str());
835 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100836
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800837 if (!mInitialized) {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700838 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800839 return STATUS_ERROR(ERROR_DISCONNECTED,
840 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700841 }
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700842 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(String8::format("%d", cameraId),
843 CameraThreadState::getCallingPid(), CameraThreadState::getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700844 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
845 if (hasSystemCameraPermissions) {
846 cameraIdBound = mNumberOfCameras;
847 }
848 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800849 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
850 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700851 }
852
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800853 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -0700854 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800855 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borger18b30a72022-10-27 12:20:29 -0700856 cameraIdStr.c_str(), overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100857 if (err != OK) {
858 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
859 "Error retrieving camera info from device %d: %s (%d)", cameraId,
860 strerror(-err), err);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700861 logServiceError(String8::format("Error retrieving camera info from device %d",cameraId),
862 ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -0800863 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100864
Ruben Brunkcc776712015-02-17 20:18:47 -0800865 return ret;
866}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700867
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800868std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700869 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
870 auto callingPid = CameraThreadState::getCallingPid();
871 auto callingUid = CameraThreadState::getCallingUid();
Joanne Chung02c13d02023-01-16 12:58:05 +0000872 AttributionSourceState attributionSource{};
873 attributionSource.pid = callingPid;
874 attributionSource.uid = callingUid;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700875 bool checkPermissionForSystemCamera = checkPermission(String8::format("%d", cameraIdInt),
876 sSystemCameraPermission, attributionSource, String16(), AppOpsManager::OP_NONE);
Joanne Chung02c13d02023-01-16 12:58:05 +0000877 if (checkPermissionForSystemCamera || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700878 deviceIds = &mNormalDeviceIds;
879 }
880 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800881 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700882 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800883 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800884 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800885
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700886 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800887}
888
889String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
890 Mutex::Autolock lock(mServiceLock);
891 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800892}
893
894Status CameraService::getCameraCharacteristics(const String16& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -0700895 int targetSdkVersion, bool overrideToPortrait, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700896 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700897 if (!cameraInfo) {
898 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800899 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700900 }
901
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800902 if (!mInitialized) {
903 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700904 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800905 return STATUS_ERROR(ERROR_DISCONNECTED,
906 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700907 }
908
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700909 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
910 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
911 "characteristics for system only device %s: ", String8(cameraId).string());
912 }
913
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800914 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800915
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700916
917 std::string cameraIdStr = String8(cameraId).string();
918 bool overrideForPerfClass =
919 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
920 cameraIdStr, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100921 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borger18b30a72022-10-27 12:20:29 -0700922 cameraIdStr, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100923 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700924 if (res == NAME_NOT_FOUND) {
925 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
926 "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
927 strerror(-res), res);
928 } else {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700929 logServiceError(String8::format("Unable to retrieve camera characteristics for "
930 "device %s.", String8(cameraId).string()),ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700931 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
932 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
933 strerror(-res), res);
934 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700935 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700936 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
937 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
938 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
939 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
940 "for device %s", String8(cameraId).string());
941 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700942 int callingPid = CameraThreadState::getCallingPid();
943 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100944 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700945 // If it's not calling from cameraserver, check the permission only if
946 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
947 // it would've already been checked in shouldRejectSystemCameraConnection.
Joanne Chung02c13d02023-01-16 12:58:05 +0000948 AttributionSourceState attributionSource{};
949 attributionSource.pid = callingPid;
950 attributionSource.uid = callingUid;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700951 bool checkPermissionForCamera = checkPermission(String8(cameraId), sCameraPermission,
952 attributionSource, String16(), AppOpsManager::OP_NONE);
Emilian Peeve20c6372018-08-14 18:45:53 +0100953 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700954 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Joanne Chung02c13d02023-01-16 12:58:05 +0000955 !checkPermissionForCamera) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100956 res = cameraInfo->removePermissionEntries(
957 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
958 &tagsRemoved);
959 if (res != OK) {
960 cameraInfo->clear();
961 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
962 " characteristics needing camera permission for device %s: %s (%d)",
963 String8(cameraId).string(), strerror(-res), res);
964 }
965 }
966
967 if (!tagsRemoved.empty()) {
968 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
969 tagsRemoved.data(), tagsRemoved.size());
970 if (res != OK) {
971 cameraInfo->clear();
972 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
973 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
974 strerror(-res), res);
975 }
976 }
977
Zhijun He2b59be82013-09-25 10:14:30 -0700978 return ret;
979}
980
Rucha Katakwar38284522021-11-10 11:25:21 -0800981Status CameraService::getTorchStrengthLevel(const String16& cameraId,
982 int32_t* torchStrength) {
983 ATRACE_CALL();
984 Mutex::Autolock l(mServiceLock);
985 if (!mInitialized) {
986 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
987 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
988 }
989
990 if(torchStrength == NULL) {
991 ALOGE("%s: strength level must not be null.", __FUNCTION__);
992 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
993 }
994
995 status_t res = mCameraProviderManager->getTorchStrengthLevel(String8(cameraId).string(),
996 torchStrength);
997 if (res != OK) {
998 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
999 "strength level for device %s: %s (%d)", String8(cameraId).string(),
1000 strerror(-res), res);
1001 }
1002 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1003 return Status::ok();
1004}
1005
Ruben Brunkcc776712015-02-17 20:18:47 -08001006String8 CameraService::getFormattedCurrentTime() {
1007 time_t now = time(nullptr);
1008 char formattedTime[64];
1009 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
1010 return String8(formattedTime);
1011}
1012
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001013Status CameraService::getCameraVendorTagDescriptor(
1014 /*out*/
1015 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001016 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001017 if (!mInitialized) {
1018 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001019 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001020 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001021 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1022 if (globalDescriptor != nullptr) {
1023 *desc = *(globalDescriptor.get());
1024 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001025 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001026}
1027
Emilian Peev71c73a22017-03-21 16:35:51 +00001028Status CameraService::getCameraVendorTagCache(
1029 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1030 ATRACE_CALL();
1031 if (!mInitialized) {
1032 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1033 return STATUS_ERROR(ERROR_DISCONNECTED,
1034 "Camera subsystem not available");
1035 }
1036 sp<VendorTagDescriptorCache> globalCache =
1037 VendorTagDescriptorCache::getGlobalVendorTagCache();
1038 if (globalCache != nullptr) {
1039 *cache = *(globalCache.get());
1040 }
1041 return Status::ok();
1042}
1043
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001044void CameraService::clearCachedVariables() {
1045 BasicClient::BasicClient::sCameraService = nullptr;
1046}
1047
Austin Borger18b30a72022-10-27 12:20:29 -07001048std::pair<int, IPCTransport> CameraService::getDeviceVersion(const String8& cameraId,
1049 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001050 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001051
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001052 int deviceVersion = 0;
1053
Emilian Peevf53f66e2017-04-11 14:29:43 +01001054 status_t res;
1055 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001056 IPCTransport transport = IPCTransport::INVALID;
Emilian Peevf53f66e2017-04-11 14:29:43 +01001057 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001058 &maxVersion, &transport);
1059 if (res != OK || transport == IPCTransport::INVALID) {
1060 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
1061 cameraId.string());
1062 return std::make_pair(-1, IPCTransport::INVALID) ;
1063 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001064 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001065
Emilian Peevf53f66e2017-04-11 14:29:43 +01001066 hardware::CameraInfo info;
1067 if (facing) {
Austin Borger18b30a72022-10-27 12:20:29 -07001068 res = mCameraProviderManager->getCameraInfo(cameraId.string(), overrideToPortrait,
1069 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001070 if (res != OK) {
1071 return std::make_pair(-1, IPCTransport::INVALID);
1072 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001073 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001074 if (orientation) {
1075 *orientation = info.orientation;
1076 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001077 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001078
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001079 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001080}
1081
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001082Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001083 switch(err) {
1084 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001085 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001086 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001087 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1088 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001089 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001090 return STATUS_ERROR(ERROR_DISCONNECTED,
1091 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001092 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001093 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1094 "Camera HAL encountered error %d: %s",
1095 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001096 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001097}
1098
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001099Status CameraService::makeClient(const sp<CameraService>& cameraService,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001100 const sp<IInterface>& cameraCb, const String16& packageName, bool systemNativeClient,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001101 const std::optional<String16>& featureId, const String8& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001102 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001103 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001104 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
1105 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001106 // For HIDL devices
1107 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1108 // Create CameraClient based on device version reported by the HAL.
1109 int deviceVersion = deviceVersionAndTransport.first;
1110 switch(deviceVersion) {
1111 case CAMERA_DEVICE_API_VERSION_1_0:
1112 ALOGE("Camera using old HAL version: %d", deviceVersion);
1113 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1114 "Camera device \"%s\" HAL version %d no longer supported",
1115 cameraId.string(), deviceVersion);
1116 break;
1117 case CAMERA_DEVICE_API_VERSION_3_0:
1118 case CAMERA_DEVICE_API_VERSION_3_1:
1119 case CAMERA_DEVICE_API_VERSION_3_2:
1120 case CAMERA_DEVICE_API_VERSION_3_3:
1121 case CAMERA_DEVICE_API_VERSION_3_4:
1122 case CAMERA_DEVICE_API_VERSION_3_5:
1123 case CAMERA_DEVICE_API_VERSION_3_6:
1124 case CAMERA_DEVICE_API_VERSION_3_7:
1125 break;
1126 default:
1127 // Should not be reachable
1128 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1129 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1130 "Camera device \"%s\" has unknown HAL version %d",
1131 cameraId.string(), deviceVersion);
1132 }
1133 }
1134 if (effectiveApiLevel == API_1) { // Camera1 API route
1135 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001136 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
1137 packageName, featureId, cameraId, api1CameraId, facing, sensorOrientation,
Austin Borger18b30a72022-10-27 12:20:29 -07001138 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait);
1139 ALOGI("%s: Camera1 API (legacy), override to portrait %d", __FUNCTION__,
1140 overrideToPortrait);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001141 } else { // Camera2 API route
1142 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1143 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001144 *client = new CameraDeviceClient(cameraService, tmp,
1145 cameraService->mCameraServiceProxyWrapper, packageName, systemNativeClient,
1146 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
Austin Borger18b30a72022-10-27 12:20:29 -07001147 overrideForPerfClass, overrideToPortrait);
1148 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001149 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001150 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001151}
1152
Ruben Brunk6267b532015-04-30 17:44:07 -07001153String8 CameraService::toString(std::set<userid_t> intSet) {
1154 String8 s("");
1155 bool first = true;
1156 for (userid_t i : intSet) {
1157 if (first) {
1158 s.appendFormat("%d", i);
1159 first = false;
1160 } else {
1161 s.appendFormat(", %d", i);
1162 }
1163 }
1164 return s;
1165}
1166
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001167int32_t CameraService::mapToInterface(TorchModeStatus status) {
1168 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1169 switch (status) {
1170 case TorchModeStatus::NOT_AVAILABLE:
1171 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1172 break;
1173 case TorchModeStatus::AVAILABLE_OFF:
1174 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1175 break;
1176 case TorchModeStatus::AVAILABLE_ON:
1177 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1178 break;
1179 default:
1180 ALOGW("Unknown new flash status: %d", status);
1181 }
1182 return serviceStatus;
1183}
1184
1185CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1186 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1187 switch (status) {
1188 case CameraDeviceStatus::NOT_PRESENT:
1189 serviceStatus = StatusInternal::NOT_PRESENT;
1190 break;
1191 case CameraDeviceStatus::PRESENT:
1192 serviceStatus = StatusInternal::PRESENT;
1193 break;
1194 case CameraDeviceStatus::ENUMERATING:
1195 serviceStatus = StatusInternal::ENUMERATING;
1196 break;
1197 default:
1198 ALOGW("Unknown new HAL device status: %d", status);
1199 }
1200 return serviceStatus;
1201}
1202
1203int32_t CameraService::mapToInterface(StatusInternal status) {
1204 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1205 switch (status) {
1206 case StatusInternal::NOT_PRESENT:
1207 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1208 break;
1209 case StatusInternal::PRESENT:
1210 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1211 break;
1212 case StatusInternal::ENUMERATING:
1213 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1214 break;
1215 case StatusInternal::NOT_AVAILABLE:
1216 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1217 break;
1218 case StatusInternal::UNKNOWN:
1219 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1220 break;
1221 default:
1222 ALOGW("Unknown new internal device status: %d", status);
1223 }
1224 return serviceStatus;
1225}
1226
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001227Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001228 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001229
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001230 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -08001231 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001232 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001233 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001234 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001235 sp<ICameraClient>{nullptr}, id, cameraId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001236 internalPackageName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001237 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Austin Borger18b30a72022-10-27 12:20:29 -07001238 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001239 ).isOk()) {
1240 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001241 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001242 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001243}
1244
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001245Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001246 /*out*/
1247 CameraParameters* parameters) {
1248
1249 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1250
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001251 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001252
1253 if (parameters == NULL) {
1254 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001255 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001256 }
1257
Ruben Brunkcc776712015-02-17 20:18:47 -08001258 String8 id = String8::format("%d", cameraId);
1259
1260 // Check if we already have parameters
1261 {
1262 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001263 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001264 auto cameraState = getCameraState(id);
1265 if (cameraState == nullptr) {
1266 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001267 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1268 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001269 }
1270 CameraParameters p = cameraState->getShimParams();
1271 if (!p.isEmpty()) {
1272 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001273 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001274 }
1275 }
1276
Jayant Chowdhary12361932018-08-27 14:46:13 -07001277 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001278 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001279 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001280 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001281 // Error already logged by callee
1282 return ret;
1283 }
1284
1285 // Check for parameters again
1286 {
1287 // Scope for service lock
1288 Mutex::Autolock lock(mServiceLock);
1289 auto cameraState = getCameraState(id);
1290 if (cameraState == nullptr) {
1291 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001292 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1293 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001294 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001295 CameraParameters p = cameraState->getShimParams();
1296 if (!p.isEmpty()) {
1297 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001298 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001299 }
1300 }
1301
Ruben Brunkcc776712015-02-17 20:18:47 -08001302 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1303 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001304 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001305}
1306
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001307// Can camera service trust the caller based on the calling UID?
1308static bool isTrustedCallingUid(uid_t uid) {
1309 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001310 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001311 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001312 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001313 return true;
1314 default:
1315 return false;
1316 }
1317}
1318
Nicholas Sauera3620332019-04-03 14:05:17 -07001319static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1320 PermissionController pc;
1321 uid = pc.getPackageUid(packageName, 0);
1322 if (uid <= 0) {
1323 ALOGE("Unknown package: '%s'", String8(packageName).string());
1324 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1325 return BAD_VALUE;
1326 }
1327
1328 if (userId < 0) {
1329 ALOGE("Invalid user: %d", userId);
1330 dprintf(err, "Invalid user: %d\n", userId);
1331 return BAD_VALUE;
1332 }
1333
1334 uid = multiuser_get_uid(userId, uid);
1335 return NO_ERROR;
1336}
1337
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001338Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001339 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1340 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001341
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001342#ifdef __BRILLO__
1343 UNUSED(clientName8);
1344 UNUSED(clientUid);
1345 UNUSED(clientPid);
1346 UNUSED(originalClientPid);
1347#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001348 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1349 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001350 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001351 return allowed;
1352 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001353#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001354
Jayant Chowdhary12361932018-08-27 14:46:13 -07001355 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001356
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001357 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001358 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1359 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001360 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1361 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001362 }
1363
Ruben Brunkcc776712015-02-17 20:18:47 -08001364 if (getCameraState(cameraId) == nullptr) {
1365 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1366 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001367 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1368 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001369 }
1370
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001371 status_t err = checkIfDeviceIsUsable(cameraId);
1372 if (err != NO_ERROR) {
1373 switch(err) {
1374 case -ENODEV:
1375 case -EBUSY:
1376 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1377 "No camera device with ID \"%s\" currently available", cameraId.string());
1378 default:
1379 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1380 "Unknown error connecting to ID \"%s\"", cameraId.string());
1381 }
1382 }
1383 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001384}
1385
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001386Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001387 const String8& clientName8, int& clientUid, int& clientPid,
1388 /*out*/int& originalClientPid) const {
Joanne Chung02c13d02023-01-16 12:58:05 +00001389 AttributionSourceState attributionSource{};
1390
Jayant Chowdhary12361932018-08-27 14:46:13 -07001391 int callingPid = CameraThreadState::getCallingPid();
1392 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001393
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001394 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001395 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001396 clientUid = callingUid;
1397 } else if (!isTrustedCallingUid(callingUid)) {
1398 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1399 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001400 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1401 "Untrusted caller (calling PID %d, UID %d) trying to "
1402 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1403 callingPid, callingUid, cameraId.string(),
1404 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001405 }
1406
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001407 // Check if we can trust clientPid
1408 if (clientPid == USE_CALLING_PID) {
1409 clientPid = callingPid;
1410 } else if (!isTrustedCallingUid(callingUid)) {
1411 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1412 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001413 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1414 "Untrusted caller (calling PID %d, UID %d) trying to "
1415 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1416 callingPid, callingUid, cameraId.string(),
1417 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001418 }
1419
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001420 if (shouldRejectSystemCameraConnection(cameraId)) {
1421 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1422 cameraId.c_str());
1423 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1424 "available", cameraId.string());
1425 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001426 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1427 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1428 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1429 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1430 "found while trying to query device kind", cameraId.string());
1431
1432 }
1433
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001434 // If it's not calling from cameraserver, check the permission if the
1435 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1436 // android.permission.SYSTEM_CAMERA for system only camera devices).
Joanne Chung02c13d02023-01-16 12:58:05 +00001437 attributionSource.pid = clientPid;
1438 attributionSource.uid = clientUid;
1439 attributionSource.packageName = clientName8;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001440 bool checkPermissionForCamera = checkPermission(cameraId, sCameraPermission, attributionSource,
1441 String16(), AppOpsManager::OP_NONE);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001442 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001443 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001444 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001445 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1446 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1447 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001448 }
1449
Svet Ganova453d0d2018-01-11 15:37:58 -08001450 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001451 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001452 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001453 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1454 clientPid, clientUid);
1455 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001456 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1457 "calling UID %d proc state %" PRId32 ")",
1458 clientName8.string(), clientUid, clientPid, cameraId.string(),
1459 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001460 }
1461
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001462
1463 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1464 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1465 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1466 if ((!isAutomotivePrivilegedClient(callingUid) ||
1467 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1468 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001469 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1470 return STATUS_ERROR_FMT(ERROR_DISABLED,
1471 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1472 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1473 }
1474
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001475 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1476 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001477 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001478 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001479
Ruben Brunk6267b532015-04-30 17:44:07 -07001480 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001481
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001482 // For non-system clients : Only allow clients who are being used by the current foreground
1483 // device user, unless calling from our own process.
1484 if (!doesClientHaveSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001485 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001486 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1487 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1488 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001489 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1490 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1491 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001492 }
1493
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001494 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001495}
1496
1497status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1498 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001499 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001500 if (cameraState == nullptr) {
1501 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1502 cameraId.string());
1503 return -ENODEV;
1504 }
1505
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001506 StatusInternal currentStatus = cameraState->getStatus();
1507 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001508 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1509 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001510 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001511 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001512 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1513 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001514 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001515 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001516
Ruben Brunkcc776712015-02-17 20:18:47 -08001517 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001518}
1519
Ruben Brunkcc776712015-02-17 20:18:47 -08001520void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001521 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001522
Ruben Brunkcc776712015-02-17 20:18:47 -08001523 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001524 auto clientDescriptor =
1525 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001526 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001527 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1528
1529 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1530 String8(client->getPackageName()));
1531
1532 if (evicted.size() > 0) {
1533 // This should never happen - clients should already have been removed in disconnect
1534 for (auto& i : evicted) {
1535 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1536 __FUNCTION__, i->getKey().string());
1537 }
1538
1539 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1540 __FUNCTION__);
1541 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001542
1543 // And register a death notification for the client callback. Do
1544 // this last to avoid Binder policy where a nested Binder
1545 // transaction might be pre-empted to service the client death
1546 // notification if the client process dies before linkToDeath is
1547 // invoked.
1548 sp<IBinder> remoteCallback = client->getRemote();
1549 if (remoteCallback != nullptr) {
1550 remoteCallback->linkToDeath(this);
1551 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001552}
1553
1554status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1555 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001556 int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001557 /*out*/
1558 sp<BasicClient>* client,
1559 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001560 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001561 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001562 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001563 DescriptorPtr clientDescriptor;
1564 {
1565 if (effectiveApiLevel == API_1) {
1566 // If we are using API1, any existing client for this camera ID with the same remote
1567 // should be returned rather than evicted to allow MediaRecorder to work properly.
1568
1569 auto current = mActiveClientManager.get(cameraId);
1570 if (current != nullptr) {
1571 auto clientSp = current->getValue();
1572 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001573 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001574 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001575 " API level, evicting prior client...");
1576 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001577 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001578 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001579 *client = clientSp;
1580 return NO_ERROR;
1581 }
1582 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001583 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001584 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001585
Ruben Brunkcc776712015-02-17 20:18:47 -08001586 // Get current active client PIDs
1587 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1588 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001589
Emilian Peev8131a262017-02-01 12:33:43 +00001590 std::vector<int> priorityScores(ownerPids.size());
1591 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001592
Emilian Peev8131a262017-02-01 12:33:43 +00001593 // Get priority scores of all active PIDs
1594 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1595 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1596 /*out*/&priorityScores[0]);
1597 if (err != OK) {
1598 ALOGE("%s: Priority score query failed: %d",
1599 __FUNCTION__, err);
1600 return err;
1601 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001602
Ruben Brunkcc776712015-02-17 20:18:47 -08001603 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001604 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001605 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001606 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001607 resource_policy::ClientPriority(priorityScores[i], states[i],
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001608 /* isVendorClient won't get copied over*/ false,
1609 /* oomScoreOffset won't get copied over*/ 0));
Ruben Brunkcc776712015-02-17 20:18:47 -08001610 }
1611 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001612
Ruben Brunkcc776712015-02-17 20:18:47 -08001613 // Get state for the given cameraId
1614 auto state = getCameraState(cameraId);
1615 if (state == nullptr) {
1616 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1617 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001618 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001619 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001620 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001621
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001622 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1623 int32_t actualState = states[states.size() - 1];
1624
1625 // Make descriptor for incoming client. We store the oomScoreOffset
1626 // since we might need it later on new handleEvictionsLocked and
1627 // ProcessInfoService would not take that into account.
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001628 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001629 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001630 state->getConflicting(), actualScore, clientPid, actualState,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001631 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001632
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001633 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1634
Ruben Brunkcc776712015-02-17 20:18:47 -08001635 // Find clients that would be evicted
1636 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1637
1638 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1639 // background, so we cannot do evictions
1640 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1641 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1642 " priority).", clientPid);
1643
1644 sp<BasicClient> clientSp = clientDescriptor->getValue();
1645 String8 curTime = getFormattedCurrentTime();
1646 auto incompatibleClients =
1647 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1648
1649 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001650 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001651 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001652 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001653
1654 for (auto& i : incompatibleClients) {
1655 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001656 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1657 i->getKey().string(),
1658 String8{i->getValue()->getPackageName()}.string(),
1659 i->getOwnerId(), i->getPriority().getScore(),
1660 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001661 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001662 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001663 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001664 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001665 }
1666
1667 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001668 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001669 mEventLog.add(msg);
1670
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001671 auto current = mActiveClientManager.get(cameraId);
1672 if (current != nullptr) {
1673 return -EBUSY; // CAMERA_IN_USE
1674 } else {
1675 return -EUSERS; // MAX_CAMERAS_IN_USE
1676 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001677 }
1678
1679 for (auto& i : evicted) {
1680 sp<BasicClient> clientSp = i->getValue();
1681 if (clientSp.get() == nullptr) {
1682 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1683
1684 // TODO: Remove this
1685 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1686 __FUNCTION__);
1687 mActiveClientManager.remove(i);
1688 continue;
1689 }
1690
1691 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1692 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001693 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001694
Ruben Brunkcc776712015-02-17 20:18:47 -08001695 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001696 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001697 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1698 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001699 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001700 i->getOwnerId(), i->getPriority().getScore(),
1701 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001702 packageName.string(), clientPid, clientPriority.getScore(),
1703 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001704
1705 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001706 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001707 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001708 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001709 }
1710
Ruben Brunkcc776712015-02-17 20:18:47 -08001711 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1712 // other clients from connecting in mServiceLockWrapper if held
1713 mServiceLock.unlock();
1714
1715 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001716 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001717
1718 // Destroy evicted clients
1719 for (auto& i : evictedClients) {
1720 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001721 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001722 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001723
Jayant Chowdhary12361932018-08-27 14:46:13 -07001724 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001725
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001726 for (const auto& i : evictedClients) {
1727 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1728 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1729 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1730 if (ret == TIMED_OUT) {
1731 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1732 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1733 mActiveClientManager.toString().string());
1734 return -EBUSY;
1735 }
1736 if (ret != NO_ERROR) {
1737 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1738 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1739 ret, mActiveClientManager.toString().string());
1740 return ret;
1741 }
1742 }
1743
1744 evictedClients.clear();
1745
Ruben Brunkcc776712015-02-17 20:18:47 -08001746 // Once clients have been disconnected, relock
1747 mServiceLock.lock();
1748
1749 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1750 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1751 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001752 }
1753
Ruben Brunkcc776712015-02-17 20:18:47 -08001754 *partial = clientDescriptor;
1755 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001756}
1757
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001758Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001759 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001760 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001761 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001762 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001763 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001764 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001765 bool overrideToPortrait,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001766 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001767 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001768
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001769 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001770 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001771
1772 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001773 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001774 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001775 clientPackageName,/*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07001776 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
1777 overrideToPortrait, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001778
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001779 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001780 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001781 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001782 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001783 }
1784
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001785 *device = client;
1786 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001787}
1788
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001789bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1790 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001791 // If the client is not a vendor client, don't add listener if
1792 // a) the camera is a publicly hidden secure camera OR
1793 // b) the camera is a system only camera and the client doesn't
1794 // have android.permission.SYSTEM_CAMERA permissions.
1795 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1796 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001797 !hasPermissionsForSystemCamera(String8(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001798 return true;
1799 }
1800 return false;
1801}
1802
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001803bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1804 // Rules for rejection:
1805 // 1) If cameraserver tries to access this camera device, accept the
1806 // connection.
1807 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001808 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001809 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1810 // and the serving thread is a non hwbinder thread, the client must have
1811 // android.permission.SYSTEM_CAMERA permissions to connect.
1812
1813 int cPid = CameraThreadState::getCallingPid();
1814 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001815 bool systemClient = doesClientHaveSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001816 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1817 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001818 // This isn't a known camera ID, so it's not a system camera
1819 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1820 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001821 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001822
1823 // (1) Cameraserver trying to connect, accept.
1824 if (CameraThreadState::getCallingPid() == getpid()) {
1825 return false;
1826 }
1827 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001828 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001829 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1830 return true;
1831 }
1832 // (3) Here we only check for permissions if it is a system only camera device. This is since
1833 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1834 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1835 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001836 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001837 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001838 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1839 cameraId.c_str());
1840 return true;
1841 }
1842
1843 return false;
1844}
1845
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001846Status CameraService::connectDevice(
1847 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001848 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001849 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001850 const std::optional<String16>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001851 int clientUid, int oomScoreOffset, int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001852 bool overrideToPortrait,
Ruben Brunkcc776712015-02-17 20:18:47 -08001853 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001854 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001855
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001856 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001857 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001858 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001859 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001860 String16 clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001861 int callingPid = CameraThreadState::getCallingPid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001862 bool systemNativeClient = false;
1863 if (doesClientHaveSystemUid() && (clientPackageNameAdj.size() == 0)) {
1864 std::string systemClient =
1865 StringPrintf("client.pid<%d>", CameraThreadState::getCallingPid());
1866 clientPackageNameAdj = String16(systemClient.c_str());
1867 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001868 }
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001869
1870 if (oomScoreOffset < 0) {
1871 String8 msg =
1872 String8::format("Cannot increase the priority of a client %s pid %d for "
1873 "camera id %s", String8(clientPackageNameAdj).string(), callingPid,
1874 id.string());
1875 ALOGE("%s: %s", __FUNCTION__, msg.string());
1876 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1877 }
1878
Austin Borger9bfa0a72022-08-03 17:50:40 -07001879 userid_t clientUserId = multiuser_get_user_id(clientUid);
1880 int callingUid = CameraThreadState::getCallingUid();
1881 if (clientUid == USE_CALLING_UID) {
1882 clientUserId = multiuser_get_user_id(callingUid);
1883 }
1884
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001885 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1886 // such as rear view and surround view cannot be disabled.
1887 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(id)) &&
1888 mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borger5f7abe22022-04-26 15:55:10 -07001889 String8 msg =
1890 String8::format("Camera disabled by device policy");
1891 ALOGE("%s: %s", __FUNCTION__, msg.string());
1892 return STATUS_ERROR(ERROR_DISABLED, msg.string());
1893 }
1894
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001895 // enforce system camera permissions
1896 if (oomScoreOffset > 0 &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001897 !hasPermissionsForSystemCamera(id, callingPid, CameraThreadState::getCallingUid()) &&
Austin Borger86a588e2022-05-23 12:41:58 -07001898 !isTrustedCallingUid(CameraThreadState::getCallingUid())) {
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001899 String8 msg =
1900 String8::format("Cannot change the priority of a client %s pid %d for "
1901 "camera id %s without SYSTEM_CAMERA permissions",
1902 String8(clientPackageNameAdj).string(), callingPid, id.string());
1903 ALOGE("%s: %s", __FUNCTION__, msg.string());
1904 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.string());
1905 }
1906
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001907 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001908 /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient,clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001909 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
Austin Borger18b30a72022-10-27 12:20:29 -07001910 targetSdkVersion, overrideToPortrait, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001911
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001912 if(!ret.isOk()) {
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001913 logRejected(id, callingPid, String8(clientPackageNameAdj), ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001914 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001915 }
1916
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001917 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07001918 Mutex::Autolock lock(mServiceLock);
1919
1920 // Clear the previous cached logs and reposition the
1921 // file offset to beginning of the file to log new data.
1922 // If either truncate or lseek fails, close the previous file and create a new one.
1923 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
1924 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
1925 // Close the previous memfd.
1926 close(mMemFd);
1927 // If failure to wipe the data, then create a new file and
1928 // assign the new value to mMemFd.
1929 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
1930 if (mMemFd == -1) {
1931 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
1932 }
1933 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001934 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001935}
1936
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001937String16 CameraService::getPackageNameFromUid(int clientUid) {
1938 String16 packageName("");
1939
1940 sp<IServiceManager> sm = defaultServiceManager();
1941 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
1942 if (binder == 0) {
1943 ALOGE("Cannot get permission service");
1944 // Return empty package name and the further interaction
1945 // with camera will likely fail
1946 return packageName;
1947 }
1948
1949 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
1950 Vector<String16> packages;
1951
1952 permCtrl->getPackagesForUid(clientUid, packages);
1953
1954 if (packages.isEmpty()) {
1955 ALOGE("No packages for calling UID %d", clientUid);
1956 // Return empty package name and the further interaction
1957 // with camera will likely fail
1958 return packageName;
1959 }
1960
1961 // Arbitrarily pick the first name in the list
1962 packageName = packages[0];
1963
1964 return packageName;
1965}
1966
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001967template<class CALLBACK, class CLIENT>
1968Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001969 int api1CameraId, const String16& clientPackageNameMaybe, bool systemNativeClient,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001970 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001971 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001972 bool overrideToPortrait, /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001973 binder::Status ret = binder::Status::ok();
1974
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001975 bool isNonSystemNdk = false;
1976 String16 clientPackageName;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001977 int packageUid = (clientUid == USE_CALLING_UID) ?
1978 CameraThreadState::getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001979 if (clientPackageNameMaybe.size() <= 0) {
1980 // NDK calls don't come with package names, but we need one for various cases.
1981 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
1982 // do exist. For all authentication cases, all packages under the same UID get the
1983 // same permissions, so picking any associated package name is sufficient. For some
1984 // other cases, this may give inaccurate names for clients in logs.
1985 isNonSystemNdk = true;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001986 clientPackageName = getPackageNameFromUid(packageUid);
1987 } else {
1988 clientPackageName = clientPackageNameMaybe;
1989 }
1990
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001991 String8 clientName8(clientPackageName);
1992
1993 int originalClientPid = 0;
1994
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001995 int packagePid = (clientPid == USE_CALLING_PID) ?
1996 CameraThreadState::getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001997 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001998 "Camera API version %d", packagePid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001999 static_cast<int>(effectiveApiLevel));
2000
Shuzhen Wang316781a2020-08-18 18:11:01 -07002001 nsecs_t openTimeNs = systemTime();
2002
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002003 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002004 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002005 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002006
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002007 {
2008 // Acquire mServiceLock and prevent other clients from connecting
2009 std::unique_ptr<AutoConditionLock> lock =
2010 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2011
2012 if (lock == nullptr) {
2013 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2014 , clientPid);
2015 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2016 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
2017 cameraId.string(), clientName8.string(), clientPid);
2018 }
2019
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002020 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002021 if(!(ret = validateConnectLocked(cameraId, clientName8,
2022 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2023 return ret;
2024 }
2025
2026 // Check the shim parameters after acquiring lock, if they have already been updated and
2027 // we were doing a shim update, return immediately
2028 if (shimUpdateOnly) {
2029 auto cameraState = getCameraState(cameraId);
2030 if (cameraState != nullptr) {
2031 if (!cameraState->getShimParams().isEmpty()) return ret;
2032 }
2033 }
2034
2035 status_t err;
2036
2037 sp<BasicClient> clientTmp = nullptr;
2038 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
2039 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002040 IInterface::asBinder(cameraCb), clientName8, oomScoreOffset, systemNativeClient,
2041 /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002042 switch (err) {
2043 case -ENODEV:
2044 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2045 "No camera device with ID \"%s\" currently available",
2046 cameraId.string());
2047 case -EBUSY:
2048 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2049 "Higher-priority client using camera, ID \"%s\" currently unavailable",
2050 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002051 case -EUSERS:
2052 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2053 "Too many cameras already open, cannot open camera \"%s\"",
2054 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002055 default:
2056 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2057 "Unexpected error %s (%d) opening camera \"%s\"",
2058 strerror(-err), err, cameraId.string());
2059 }
2060 }
2061
2062 if (clientTmp.get() != nullptr) {
2063 // Handle special case for API1 MediaRecorder where the existing client is returned
2064 device = static_cast<CLIENT*>(clientTmp.get());
2065 return ret;
2066 }
2067
2068 // give flashlight a chance to close devices if necessary.
2069 mFlashlight->prepareDeviceOpen(cameraId);
2070
Austin Borger18b30a72022-10-27 12:20:29 -07002071 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002072 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07002073 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
2074 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002075 if (facing == -1) {
2076 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
2077 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2078 "Unable to get camera device \"%s\" facing", cameraId.string());
2079 }
2080
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002081 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002082 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
2083 mPerfClassPrimaryCameraIds, cameraId.string(), targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002084 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
2085 clientFeatureId, cameraId, api1CameraId, facing, orientation,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07002086 clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002087 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
Austin Borger18b30a72022-10-27 12:20:29 -07002088 overrideToPortrait, /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002089 return ret;
2090 }
2091 client = static_cast<CLIENT*>(tmp.get());
2092
2093 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2094 __FUNCTION__);
2095
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002096 String8 monitorTags = isClientWatched(client.get()) ? mMonitorTags : String8("");
2097 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002098 if (err != OK) {
2099 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002100 // Errors could be from the HAL module open call or from AppOpsManager
2101 switch(err) {
2102 case BAD_VALUE:
2103 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2104 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
2105 case -EBUSY:
2106 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2107 "Camera \"%s\" is already open", cameraId.string());
2108 case -EUSERS:
2109 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2110 "Too many cameras already open, cannot open camera \"%s\"",
2111 cameraId.string());
2112 case PERMISSION_DENIED:
2113 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2114 "No permission to open camera \"%s\"", cameraId.string());
2115 case -EACCES:
2116 return STATUS_ERROR_FMT(ERROR_DISABLED,
2117 "Camera \"%s\" disabled by policy", cameraId.string());
2118 case -ENODEV:
2119 default:
2120 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2121 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
2122 strerror(-err), err);
2123 }
2124 }
2125
2126 // Update shim paremeters for legacy clients
2127 if (effectiveApiLevel == API_1) {
2128 // Assume we have always received a Client subclass for API1
2129 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2130 String8 rawParams = shimClient->getParameters();
2131 CameraParameters params(rawParams);
2132
2133 auto cameraState = getCameraState(cameraId);
2134 if (cameraState != nullptr) {
2135 cameraState->setShimParams(params);
2136 } else {
2137 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
2138 __FUNCTION__, cameraId.string());
2139 }
2140 }
2141
Ravneetaeb20dc2022-03-30 05:33:03 +00002142 // Enable/disable camera service watchdog
2143 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2144
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002145 // Set rotate-and-crop override behavior
2146 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2147 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Austin Borger18b30a72022-10-27 12:20:29 -07002148 } else if (overrideToPortrait && portraitRotation != 0) {
2149 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2150 switch (portraitRotation) {
2151 case 90:
2152 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2153 break;
2154 case 180:
2155 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2156 break;
2157 case 270:
2158 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2159 break;
2160 default:
2161 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2162 break;
2163 }
2164 client->setRotateAndCropOverride(rotateAndCropMode);
Emilian Peev13f35ad2022-04-27 11:28:48 -07002165 } else {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002166 client->setRotateAndCropOverride(
2167 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2168 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2169 }
2170
2171 // Set autoframing override behaviour
2172 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2173 client->setAutoframingOverride(mOverrideAutoframingMode);
2174 } else {
2175 client->setAutoframingOverride(
2176 mCameraServiceProxyWrapper->getAutoframingOverride(
2177 clientPackageName));
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002178 }
2179
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002180 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use
2181 // cases such as rear view and surround view cannot be disabled and are exempt from camera
2182 // privacy policy.
2183 if ((!isAutomotivePrivilegedClient(packageUid) ||
2184 !isAutomotiveExteriorSystemCamera(cameraId))) {
2185 // Set camera muting behavior.
2186 bool isCameraPrivacyEnabled =
2187 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2188 if (client->supportsCameraMute()) {
2189 client->setCameraMute(
2190 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2191 } else if (isCameraPrivacyEnabled) {
2192 // no camera mute supported, but privacy is on! => disconnect
2193 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2194 String8(client->getPackageName()).string(), cameraId.string());
2195 // Do not hold mServiceLock while disconnecting clients, but
2196 // retain the condition blocking other clients from connecting
2197 // in mServiceLockWrapper if held.
2198 mServiceLock.unlock();
2199 // Clear caller identity temporarily so client disconnect PID
2200 // checks work correctly
2201 int64_t token = CameraThreadState::clearCallingIdentity();
2202 // Note AppOp to trigger the "Unblock" dialog
2203 client->noteAppOp();
2204 client->disconnect();
2205 CameraThreadState::restoreCallingIdentity(token);
2206 // Reacquire mServiceLock
2207 mServiceLock.lock();
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002208
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002209 return STATUS_ERROR_FMT(ERROR_DISABLED,
2210 "Camera \"%s\" disabled due to camera mute", cameraId.string());
2211 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002212 }
2213
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002214 if (shimUpdateOnly) {
2215 // If only updating legacy shim parameters, immediately disconnect client
2216 mServiceLock.unlock();
2217 client->disconnect();
2218 mServiceLock.lock();
2219 } else {
2220 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002221 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002222 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002223
2224 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002225 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002226 } // lock is destroyed, allow further connect calls
2227
2228 // Important: release the mutex here so the client can call back into the service from its
2229 // destructor (can be at the end of the call)
2230 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002231
2232 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002233 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002234 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002235
Cliff Wud3a05312021-04-26 23:07:31 +08002236 {
2237 Mutex::Autolock lock(mInjectionParametersLock);
2238 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2239 mInjectionInitPending = false;
2240 status_t res = NO_ERROR;
2241 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2242 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002243 sp<BasicClient> clientSp = clientDescriptor->getValue();
2244 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2245 if(res != OK) {
2246 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2247 "No camera device with ID \"%s\" currently available",
2248 mInjectionExternalCamId.string());
2249 }
2250 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002251 if (res != OK) {
2252 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2253 }
2254 } else {
2255 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
2256 __FUNCTION__, mInjectionInternalCamId.string());
2257 res = NO_INIT;
2258 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2259 }
2260 }
2261 }
2262
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002263 return ret;
2264}
2265
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002266status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
2267 if (offlineClient.get() == nullptr) {
2268 return BAD_VALUE;
2269 }
2270
2271 {
2272 // Acquire mServiceLock and prevent other clients from connecting
2273 std::unique_ptr<AutoConditionLock> lock =
2274 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2275
2276 if (lock == nullptr) {
2277 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2278 , __FUNCTION__, offlineClient->getClientPid());
2279 return TIMED_OUT;
2280 }
2281
2282 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2283 if (onlineClientDesc.get() == nullptr) {
2284 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2285 cameraId.c_str());
2286 return BAD_VALUE;
2287 }
2288
2289 // Offline clients do not evict or conflict with other online devices. Resource sharing
2290 // conflicts are handled by the camera provider which will either succeed or fail before
2291 // reaching this method.
2292 const auto& onlinePriority = onlineClientDesc->getPriority();
2293 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2294 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
2295 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002296 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002297 // native clients don't have offline processing support.
2298 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002299 if (offlineClientDesc == nullptr) {
2300 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2301 return BAD_VALUE;
2302 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002303
2304 // Allow only one offline device per camera
2305 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2306 if (!incompatibleClients.empty()) {
2307 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2308 return BAD_VALUE;
2309 }
2310
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002311 String8 monitorTags = isClientWatched(offlineClient.get()) ? mMonitorTags : String8("");
2312 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002313 if (err != OK) {
2314 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2315 return err;
2316 }
2317
2318 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2319 if (evicted.size() > 0) {
2320 for (auto& i : evicted) {
2321 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
2322 __FUNCTION__, i->getKey().string());
2323 }
2324
2325 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2326 "properly", __FUNCTION__);
2327
2328 return BAD_VALUE;
2329 }
2330
2331 logConnectedOffline(offlineClientDesc->getKey(),
2332 static_cast<int>(offlineClientDesc->getOwnerId()),
2333 String8(offlineClient->getPackageName()));
2334
2335 sp<IBinder> remoteCallback = offlineClient->getRemote();
2336 if (remoteCallback != nullptr) {
2337 remoteCallback->linkToDeath(this);
2338 }
2339 } // lock is destroyed, allow further connect calls
2340
2341 return OK;
2342}
2343
Rucha Katakwar38284522021-11-10 11:25:21 -08002344Status CameraService::turnOnTorchWithStrengthLevel(const String16& cameraId, int32_t torchStrength,
2345 const sp<IBinder>& clientBinder) {
2346 Mutex::Autolock lock(mServiceLock);
2347
2348 ATRACE_CALL();
2349 if (clientBinder == nullptr) {
2350 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2351 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2352 "Torch client binder in null.");
2353 }
2354
2355 String8 id = String8(cameraId.string());
2356 int uid = CameraThreadState::getCallingUid();
2357
2358 if (shouldRejectSystemCameraConnection(id)) {
2359 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
2360 "for system only device %s: ", id.string());
2361 }
2362
2363 // verify id is valid
2364 auto state = getCameraState(id);
2365 if (state == nullptr) {
2366 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
2367 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2368 "Camera ID \"%s\" is a not valid camera ID", id.string());
2369 }
2370
2371 StatusInternal cameraStatus = state->getStatus();
2372 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2373 cameraStatus != StatusInternal::PRESENT) {
2374 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(),
2375 (int)cameraStatus);
2376 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2377 "Camera ID \"%s\" is a not valid camera ID", id.string());
2378 }
2379
2380 {
2381 Mutex::Autolock al(mTorchStatusMutex);
2382 TorchModeStatus status;
2383 status_t err = getTorchStatusLocked(id, &status);
2384 if (err != OK) {
2385 if (err == NAME_NOT_FOUND) {
2386 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2387 "Camera \"%s\" does not have a flash unit", id.string());
2388 }
2389 ALOGE("%s: getting current torch status failed for camera %s",
2390 __FUNCTION__, id.string());
2391 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2392 "Error changing torch strength level for camera \"%s\": %s (%d)",
2393 id.string(), strerror(-err), err);
2394 }
2395
2396 if (status == TorchModeStatus::NOT_AVAILABLE) {
2397 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2398 ALOGE("%s: torch mode of camera %s is not available because "
2399 "camera is in use.", __FUNCTION__, id.string());
2400 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2401 "Torch for camera \"%s\" is not available due to an existing camera user",
2402 id.string());
2403 } else {
2404 ALOGE("%s: torch mode of camera %s is not available due to "
2405 "insufficient resources", __FUNCTION__, id.string());
2406 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2407 "Torch for camera \"%s\" is not available due to insufficient resources",
2408 id.string());
2409 }
2410 }
2411 }
2412
2413 {
2414 Mutex::Autolock al(mTorchUidMapMutex);
2415 updateTorchUidMapLocked(cameraId, uid);
2416 }
2417 // Check if the current torch strength level is same as the new one.
2418 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
2419 id.string(), torchStrength);
2420
2421 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(id, torchStrength);
2422
2423 if (err != OK) {
2424 int32_t errorCode;
2425 String8 msg;
2426 switch (err) {
2427 case -ENOSYS:
2428 msg = String8::format("Camera \"%s\" has no flashlight.",
2429 id.string());
2430 errorCode = ERROR_ILLEGAL_ARGUMENT;
2431 break;
2432 case -EBUSY:
2433 msg = String8::format("Camera \"%s\" is in use",
2434 id.string());
2435 errorCode = ERROR_CAMERA_IN_USE;
2436 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002437 case -EINVAL:
2438 msg = String8::format("Torch strength level %d is not within the "
2439 "valid range.", torchStrength);
2440 errorCode = ERROR_ILLEGAL_ARGUMENT;
2441 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002442 default:
2443 msg = String8::format("Changing torch strength level failed.");
2444 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002445 }
2446 ALOGE("%s: %s", __FUNCTION__, msg.string());
2447 return STATUS_ERROR(errorCode, msg.string());
2448 }
2449
2450 {
2451 // update the link to client's death
2452 // Store the last client that turns on each camera's torch mode.
2453 Mutex::Autolock al(mTorchClientMapMutex);
2454 ssize_t index = mTorchClientMap.indexOfKey(id);
2455 if (index == NAME_NOT_FOUND) {
2456 mTorchClientMap.add(id, clientBinder);
2457 } else {
2458 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2459 mTorchClientMap.replaceValueAt(index, clientBinder);
2460 }
2461 clientBinder->linkToDeath(this);
2462 }
2463
2464 int clientPid = CameraThreadState::getCallingPid();
2465 const char *id_cstr = id.c_str();
2466 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
2467 __FUNCTION__, id_cstr, torchStrength, clientPid);
2468 if (!shouldSkipTorchStrengthUpdates) {
2469 broadcastTorchStrengthLevel(id, torchStrength);
2470 }
2471 return Status::ok();
2472}
2473
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002474Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002475 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002476 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002477
2478 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002479 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002480 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002481 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2482 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002483 }
2484
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002485 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07002486 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002487
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002488 if (shouldRejectSystemCameraConnection(id)) {
2489 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
2490 " for system only device %s: ", id.string());
2491 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002492 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08002493 auto state = getCameraState(id);
2494 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002495 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002496 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2497 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002498 }
2499
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002500 StatusInternal cameraStatus = state->getStatus();
2501 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002502 cameraStatus != StatusInternal::NOT_AVAILABLE) {
2503 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002504 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2505 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002506 }
2507
2508 {
2509 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002510 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002511 status_t err = getTorchStatusLocked(id, &status);
2512 if (err != OK) {
2513 if (err == NAME_NOT_FOUND) {
2514 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2515 "Camera \"%s\" does not have a flash unit", id.string());
2516 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002517 ALOGE("%s: getting current torch status failed for camera %s",
2518 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002519 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2520 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
2521 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002522 }
2523
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002524 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002525 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002526 ALOGE("%s: torch mode of camera %s is not available because "
2527 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002528 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2529 "Torch for camera \"%s\" is not available due to an existing camera user",
2530 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002531 } else {
2532 ALOGE("%s: torch mode of camera %s is not available due to "
2533 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002534 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2535 "Torch for camera \"%s\" is not available due to insufficient resources",
2536 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002537 }
2538 }
2539 }
2540
Ruben Brunk99e69712015-05-26 17:25:07 -07002541 {
2542 // Update UID map - this is used in the torch status changed callbacks, so must be done
2543 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002544 Mutex::Autolock al(mTorchUidMapMutex);
Rucha Katakwar38284522021-11-10 11:25:21 -08002545 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07002546 }
2547
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002548 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002549
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002550 if (err != OK) {
2551 int32_t errorCode;
2552 String8 msg;
2553 switch (err) {
2554 case -ENOSYS:
2555 msg = String8::format("Camera \"%s\" has no flashlight",
2556 id.string());
2557 errorCode = ERROR_ILLEGAL_ARGUMENT;
2558 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08002559 case -EBUSY:
2560 msg = String8::format("Camera \"%s\" is in use",
2561 id.string());
2562 errorCode = ERROR_CAMERA_IN_USE;
2563 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002564 default:
2565 msg = String8::format(
2566 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
2567 id.string(), enabled, strerror(-err), err);
2568 errorCode = ERROR_INVALID_OPERATION;
2569 }
2570 ALOGE("%s: %s", __FUNCTION__, msg.string());
Rucha Katakward9ea6452021-05-06 11:57:16 -07002571 logServiceError(msg,errorCode);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002572 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002573 }
2574
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002575 {
2576 // update the link to client's death
2577 Mutex::Autolock al(mTorchClientMapMutex);
2578 ssize_t index = mTorchClientMap.indexOfKey(id);
2579 if (enabled) {
2580 if (index == NAME_NOT_FOUND) {
2581 mTorchClientMap.add(id, clientBinder);
2582 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07002583 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002584 mTorchClientMap.replaceValueAt(index, clientBinder);
2585 }
2586 clientBinder->linkToDeath(this);
2587 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07002588 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002589 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002590 }
2591
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002592 int clientPid = CameraThreadState::getCallingPid();
2593 const char *id_cstr = id.c_str();
2594 const char *torchState = enabled ? "on" : "off";
2595 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
2596 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002597 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002598}
2599
Rucha Katakwar38284522021-11-10 11:25:21 -08002600void CameraService::updateTorchUidMapLocked(const String16& cameraId, int uid) {
2601 String8 id = String8(cameraId.string());
2602 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
2603 mTorchUidMap[id].first = uid;
2604 mTorchUidMap[id].second = uid;
2605 } else {
2606 // Set the pending UID
2607 mTorchUidMap[id].first = uid;
2608 }
2609}
2610
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002611Status CameraService::notifySystemEvent(int32_t eventId,
2612 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002613 const int pid = CameraThreadState::getCallingPid();
2614 const int selfPid = getpid();
2615
2616 // Permission checks
2617 if (pid != selfPid) {
2618 // Ensure we're being called by system_server, or similar process with
2619 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002620 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002621 const int uid = CameraThreadState::getCallingUid();
2622 ALOGE("Permission Denial: cannot send updates to camera service about system"
2623 " events from pid=%d, uid=%d", pid, uid);
2624 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09002625 "No permission to send updates to camera service about system events"
2626 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002627 }
2628 }
2629
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002630 ATRACE_CALL();
2631
Ruben Brunk36597b22015-03-20 22:15:57 -07002632 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002633 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002634 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002635 // from a system server crash
2636 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002637 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002638 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002639 break;
2640 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02002641 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
2642 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
2643 // Notify CameraProviderManager for lazy HALs
2644 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
2645 std::to_string(args[0]));
2646 break;
2647 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002648 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002649 default: {
2650 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2651 eventId);
2652 break;
2653 }
2654 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002655 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002656}
2657
Emilian Peev53722fa2019-02-22 17:47:20 -08002658void CameraService::notifyMonitoredUids() {
2659 Mutex::Autolock lock(mStatusListenerLock);
2660
2661 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002662 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07002663 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
2664 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08002665 }
2666}
2667
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002668Status CameraService::notifyDeviceStateChange(int64_t newState) {
2669 const int pid = CameraThreadState::getCallingPid();
2670 const int selfPid = getpid();
2671
2672 // Permission checks
2673 if (pid != selfPid) {
2674 // Ensure we're being called by system_server, or similar process with
2675 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002676 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002677 const int uid = CameraThreadState::getCallingUid();
2678 ALOGE("Permission Denial: cannot send updates to camera service about device"
2679 " state changes from pid=%d, uid=%d", pid, uid);
2680 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2681 "No permission to send updates to camera service about device state"
2682 " changes from pid=%d, uid=%d", pid, uid);
2683 }
2684 }
2685
2686 ATRACE_CALL();
2687
Austin Borger18b30a72022-10-27 12:20:29 -07002688 {
2689 Mutex::Autolock lock(mServiceLock);
2690 mDeviceState = newState;
2691 }
2692
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07002693 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002694
2695 return Status::ok();
2696}
2697
Emilian Peev8b64f282021-03-25 16:49:57 -07002698Status CameraService::notifyDisplayConfigurationChange() {
2699 ATRACE_CALL();
2700 const int callingPid = CameraThreadState::getCallingPid();
2701 const int selfPid = getpid();
2702
2703 // Permission checks
2704 if (callingPid != selfPid) {
2705 // Ensure we're being called by system_server, or similar process with
2706 // permissions to notify the camera service about system events
2707 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2708 const int uid = CameraThreadState::getCallingUid();
2709 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2710 " changes from pid=%d, uid=%d", callingPid, uid);
2711 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2712 "No permission to send updates to camera service about orientation"
2713 " changes from pid=%d, uid=%d", callingPid, uid);
2714 }
2715 }
2716
2717 Mutex::Autolock lock(mServiceLock);
2718
2719 // Don't do anything if rotate-and-crop override via cmd is active
2720 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2721
2722 const auto clients = mActiveClientManager.getAll();
2723 for (auto& current : clients) {
2724 if (current != nullptr) {
2725 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07002726 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
2727 basicClient->setRotateAndCropOverride(
2728 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2729 basicClient->getPackageName(),
2730 basicClient->getCameraFacing(),
2731 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07002732 }
2733 }
2734 }
2735
2736 return Status::ok();
2737}
2738
2739Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002740 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2741 ATRACE_CALL();
2742 if (!concurrentCameraIds) {
2743 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2744 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2745 }
2746
2747 if (!mInitialized) {
2748 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002749 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002750 return STATUS_ERROR(ERROR_DISCONNECTED,
2751 "Camera subsystem is not available");
2752 }
2753 // First call into the provider and get the set of concurrent camera
2754 // combinations
2755 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002756 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002757 for (auto &combination : concurrentCameraCombinations) {
2758 std::vector<std::string> validCombination;
2759 for (auto &cameraId : combination) {
2760 // if the camera state is not present, skip
2761 String8 cameraIdStr(cameraId.c_str());
2762 auto state = getCameraState(cameraIdStr);
2763 if (state == nullptr) {
2764 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2765 continue;
2766 }
2767 StatusInternal status = state->getStatus();
2768 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2769 continue;
2770 }
2771 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2772 continue;
2773 }
2774 validCombination.push_back(cameraId);
2775 }
2776 if (validCombination.size() != 0) {
2777 concurrentCameraIds->push_back(std::move(validCombination));
2778 }
2779 }
2780 return Status::ok();
2781}
2782
2783Status CameraService::isConcurrentSessionConfigurationSupported(
2784 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002785 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002786 if (!isSupported) {
2787 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2788 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2789 }
2790
2791 if (!mInitialized) {
2792 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2793 return STATUS_ERROR(ERROR_DISCONNECTED,
2794 "Camera subsystem is not available");
2795 }
2796
2797 // Check for camera permissions
2798 int callingPid = CameraThreadState::getCallingPid();
2799 int callingUid = CameraThreadState::getCallingUid();
Joanne Chung02c13d02023-01-16 12:58:05 +00002800 AttributionSourceState attributionSource{};
2801 attributionSource.pid = callingPid;
2802 attributionSource.uid = callingUid;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002803 bool checkPermissionForCamera = checkPermission(String8(),
2804 sCameraPermission, attributionSource, String16(), AppOpsManager::OP_NONE);
Joanne Chung02c13d02023-01-16 12:58:05 +00002805 if ((callingPid != getpid()) && !checkPermissionForCamera) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002806 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2807 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2808 "android.permission.CAMERA needed to call"
2809 "isConcurrentSessionConfigurationSupported");
2810 }
2811
2812 status_t res =
2813 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002814 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
2815 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002816 if (res != OK) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07002817 logServiceError(String8::format("Unable to query session configuration support"),
2818 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002819 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2820 "support %s (%d)", strerror(-res), res);
2821 }
2822 return Status::ok();
2823}
2824
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002825Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2826 /*out*/
2827 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002828 return addListenerHelper(listener, cameraStatuses);
2829}
2830
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002831binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2832 std::vector<hardware::CameraStatus>* cameraStatuses) {
2833 return addListenerHelper(listener, cameraStatuses, false, true);
2834}
2835
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002836Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2837 /*out*/
2838 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002839 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002840
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002841 ATRACE_CALL();
2842
Igor Murashkinbfc99152013-02-27 12:55:20 -08002843 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002844
Ruben Brunk3450ba72015-06-16 11:00:37 -07002845 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002846 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002847 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002848 }
2849
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002850 auto clientUid = CameraThreadState::getCallingUid();
2851 auto clientPid = CameraThreadState::getCallingPid();
Joanne Chung02c13d02023-01-16 12:58:05 +00002852 AttributionSourceState attributionSource{};
2853 attributionSource.uid = clientUid;
2854 attributionSource.pid = clientPid;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002855
2856 bool openCloseCallbackAllowed = checkPermission(String8(),
Joanne Chung02c13d02023-01-16 12:58:05 +00002857 sCameraOpenCloseListenerPermission, attributionSource, String16(),
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002858 AppOpsManager::OP_NONE);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002859
Igor Murashkinbfc99152013-02-27 12:55:20 -08002860 Mutex::Autolock lock(mServiceLock);
2861
Ruben Brunkcc776712015-02-17 20:18:47 -08002862 {
2863 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002864 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002865 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002866 ALOGW("%s: Tried to add listener %p which was already subscribed",
2867 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002868 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002869 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002870 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002871
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002872 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002873 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2874 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002875 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08002876 if (ret != NO_ERROR) {
2877 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2878 strerror(-ret), ret);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002879 logServiceError(msg,ERROR_ILLEGAL_ARGUMENT);
Emilian Peev53722fa2019-02-22 17:47:20 -08002880 ALOGE("%s: %s", __FUNCTION__, msg.string());
2881 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2882 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002883 // The listener still needs to be added to the list of listeners, regardless of what
2884 // permissions the listener process has / whether it is a vendor listener. Since it might be
2885 // eligible to listen to other camera ids.
2886 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002887 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002888 }
2889
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002890 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002891 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002892 Mutex::Autolock lock(mCameraStatesLock);
2893 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002894 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07002895 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
2896 openCloseCallbackAllowed ? i.second->getClientPackage() : String8::empty());
Igor Murashkincba2c162013-03-20 15:56:31 -07002897 }
2898 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002899 // Remove the camera statuses that should be hidden from the client, we do
2900 // this after collecting the states in order to avoid holding
2901 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2902 // the same time.
2903 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2904 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2905 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2906 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2907 ALOGE("%s: Invalid camera id %s, skipping status update",
2908 __FUNCTION__, s.cameraId.c_str());
2909 return true;
2910 }
2911 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2912 clientUid);}), cameraStatuses->end());
2913
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002914 //cameraStatuses will have non-eligible camera ids removed.
2915 std::set<String16> idsChosenForCallback;
2916 for (const auto &s : *cameraStatuses) {
2917 idsChosenForCallback.insert(String16(s.cameraId));
2918 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002919
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002920 /*
2921 * Immediately signal current torch status to this listener only
2922 * This may be a subset of all the devices, so don't include it in the response directly
2923 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002924 {
2925 Mutex::Autolock al(mTorchStatusMutex);
2926 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002927 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002928 // The camera id is visible to the client. Fine to send torch
2929 // callback.
2930 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2931 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2932 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002933 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002934 }
2935
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002936 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002937}
Ruben Brunkcc776712015-02-17 20:18:47 -08002938
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002939Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002940 ATRACE_CALL();
2941
Igor Murashkinbfc99152013-02-27 12:55:20 -08002942 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2943
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002944 if (listener == 0) {
2945 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002946 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002947 }
2948
Igor Murashkinbfc99152013-02-27 12:55:20 -08002949 Mutex::Autolock lock(mServiceLock);
2950
Ruben Brunkcc776712015-02-17 20:18:47 -08002951 {
2952 Mutex::Autolock lock(mStatusListenerLock);
2953 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002954 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2955 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2956 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002957 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002958 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002959 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002960 }
2961 }
2962
2963 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2964 __FUNCTION__, listener.get());
2965
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002966 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002967}
2968
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002969Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002970
2971 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002972 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2973
2974 if (parameters == NULL) {
2975 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002976 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002977 }
2978
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002979 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002980
2981 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002982 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002983 // Error logged by caller
2984 return ret;
2985 }
2986
2987 String8 shimParamsString8 = shimParams.flatten();
2988 String16 shimParamsString16 = String16(shimParamsString8);
2989
2990 *parameters = shimParamsString16;
2991
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002992 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002993}
2994
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002995Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2996 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002997 ATRACE_CALL();
2998
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002999 const String8 id = String8(cameraId);
3000
3001 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003002
3003 switch (apiVersion) {
3004 case API_VERSION_1:
3005 case API_VERSION_2:
3006 break;
3007 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003008 String8 msg = String8::format("Unknown API version %d", apiVersion);
3009 ALOGE("%s: %s", __FUNCTION__, msg.string());
3010 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003011 }
3012
Austin Borger18b30a72022-10-27 12:20:29 -07003013 int portraitRotation;
3014 auto deviceVersionAndTransport = getDeviceVersion(id, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003015 if (deviceVersionAndTransport.first == -1) {
3016 String8 msg = String8::format("Unknown camera ID %s", id.string());
3017 ALOGE("%s: %s", __FUNCTION__, msg.string());
3018 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
3019 }
3020 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3021 int deviceVersion = deviceVersionAndTransport.first;
3022 switch (deviceVersion) {
3023 case CAMERA_DEVICE_API_VERSION_1_0:
3024 case CAMERA_DEVICE_API_VERSION_3_0:
3025 case CAMERA_DEVICE_API_VERSION_3_1:
3026 if (apiVersion == API_VERSION_2) {
3027 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
3028 "shim", __FUNCTION__, id.string(), deviceVersion);
3029 *isSupported = false;
3030 } else { // if (apiVersion == API_VERSION_1) {
3031 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
3032 "supported", __FUNCTION__, id.string());
3033 *isSupported = true;
3034 }
3035 break;
3036 case CAMERA_DEVICE_API_VERSION_3_2:
3037 case CAMERA_DEVICE_API_VERSION_3_3:
3038 case CAMERA_DEVICE_API_VERSION_3_4:
3039 case CAMERA_DEVICE_API_VERSION_3_5:
3040 case CAMERA_DEVICE_API_VERSION_3_6:
3041 case CAMERA_DEVICE_API_VERSION_3_7:
3042 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003043 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003044 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003045 break;
3046 default: {
3047 String8 msg = String8::format("Unknown device version %x for device %s",
3048 deviceVersion, id.string());
3049 ALOGE("%s: %s", __FUNCTION__, msg.string());
3050 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003051 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003052 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003053 } else {
3054 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003055 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003056 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003057}
3058
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003059Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
3060 /*out*/ bool *isSupported) {
3061 ATRACE_CALL();
3062
3063 const String8 id = String8(cameraId);
3064
3065 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
3066 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
3067
3068 return Status::ok();
3069}
3070
Cliff Wud8cae102021-03-11 01:37:42 +08003071Status CameraService::injectCamera(
3072 const String16& packageName, const String16& internalCamId,
3073 const String16& externalCamId,
3074 const sp<ICameraInjectionCallback>& callback,
3075 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003076 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003077 ATRACE_CALL();
3078
3079 if (!checkCallingPermission(sCameraInjectExternalCameraPermission)) {
3080 const int pid = CameraThreadState::getCallingPid();
3081 const int uid = CameraThreadState::getCallingUid();
3082 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3083 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3084 "Permission Denial: no permission to inject camera");
3085 }
3086
3087 ALOGV(
3088 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3089 "%s",
3090 __FUNCTION__, String8(packageName).string(),
3091 String8(internalCamId).string(), String8(externalCamId).string());
3092
Cliff Wud3a05312021-04-26 23:07:31 +08003093 {
3094 Mutex::Autolock lock(mInjectionParametersLock);
3095 mInjectionInternalCamId = String8(internalCamId);
3096 mInjectionExternalCamId = String8(externalCamId);
Cliff Wu646bd612021-11-23 23:21:29 +08003097 mInjectionStatusListener->addListener(callback);
3098 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003099 status_t res = NO_ERROR;
3100 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3101 // If the client already exists, we can directly connect to the camera device through the
3102 // client's injectCamera(), otherwise we need to wait until the client is established
3103 // (execute connectHelper()) before injecting the camera to the camera device.
3104 if (clientDescriptor != nullptr) {
3105 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003106 sp<BasicClient> clientSp = clientDescriptor->getValue();
3107 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3108 if(res != OK) {
3109 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3110 "No camera device with ID \"%s\" currently available",
3111 mInjectionExternalCamId.string());
3112 }
3113 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08003114 if(res != OK) {
3115 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3116 }
3117 } else {
3118 mInjectionInitPending = true;
3119 }
3120 }
Cliff Wud8cae102021-03-11 01:37:42 +08003121
Cliff Wud3a05312021-04-26 23:07:31 +08003122 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003123}
3124
Ruben Brunkcc776712015-02-17 20:18:47 -08003125void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003126 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003127 for (auto& i : mActiveClientManager.getAll()) {
3128 auto clientSp = i->getValue();
3129 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003130 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003131 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003132 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003133 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003134 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003135}
3136
Ruben Brunkcc776712015-02-17 20:18:47 -08003137bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003138 bool ret = false;
3139 {
3140 // Acquire mServiceLock and prevent other clients from connecting
3141 std::unique_ptr<AutoConditionLock> lock =
3142 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003143
Igor Murashkin634a5152013-02-20 17:15:11 -08003144
Ruben Brunkcc776712015-02-17 20:18:47 -08003145 std::vector<sp<BasicClient>> evicted;
3146 for (auto& i : mActiveClientManager.getAll()) {
3147 auto clientSp = i->getValue();
3148 if (clientSp.get() == nullptr) {
3149 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3150 mActiveClientManager.remove(i);
3151 continue;
3152 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003153 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003154 mActiveClientManager.remove(i);
3155 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003156
Ruben Brunkcc776712015-02-17 20:18:47 -08003157 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003158 clientSp->notifyError(
3159 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003160 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003161 }
3162 }
3163
Ruben Brunkcc776712015-02-17 20:18:47 -08003164 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3165 // other clients from connecting in mServiceLockWrapper if held
3166 mServiceLock.unlock();
3167
Ruben Brunk36597b22015-03-20 22:15:57 -07003168 // Do not clear caller identity, remote caller should be client proccess
3169
Ruben Brunkcc776712015-02-17 20:18:47 -08003170 for (auto& i : evicted) {
3171 if (i.get() != nullptr) {
3172 i->disconnect();
3173 ret = true;
3174 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003175 }
3176
Ruben Brunkcc776712015-02-17 20:18:47 -08003177 // Reacquire mServiceLock
3178 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003179
Ruben Brunkcc776712015-02-17 20:18:47 -08003180 } // lock is destroyed, allow further connect calls
3181
3182 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003183}
3184
Ruben Brunkcc776712015-02-17 20:18:47 -08003185std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
3186 const String8& cameraId) const {
3187 std::shared_ptr<CameraState> state;
3188 {
3189 Mutex::Autolock lock(mCameraStatesLock);
3190 auto iter = mCameraStates.find(cameraId);
3191 if (iter != mCameraStates.end()) {
3192 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003193 }
3194 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003195 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003196}
3197
Ruben Brunkcc776712015-02-17 20:18:47 -08003198sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
3199 // Remove from active clients list
3200 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3201 if (clientDescriptorPtr == nullptr) {
3202 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
3203 cameraId.string());
3204 return sp<BasicClient>{nullptr};
3205 }
3206
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003207 sp<BasicClient> client = clientDescriptorPtr->getValue();
3208 if (client.get() != nullptr) {
3209 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3210 }
3211 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003212}
3213
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003214void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003215 // Acquire mServiceLock and prevent other clients from connecting
3216 std::unique_ptr<AutoConditionLock> lock =
3217 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3218
Ruben Brunk6267b532015-04-30 17:44:07 -07003219 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003220 for (size_t i = 0; i < newUserIds.size(); i++) {
3221 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003222 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003223 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003224 return;
3225 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003226 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003227 }
3228
Ruben Brunka8ca9152015-04-07 14:23:40 -07003229
Ruben Brunk6267b532015-04-30 17:44:07 -07003230 if (newAllowedUsers == mAllowedUsers) {
3231 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3232 return;
3233 }
3234
3235 logUserSwitch(mAllowedUsers, newAllowedUsers);
3236
3237 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003238
3239 // Current user has switched, evict all current clients.
3240 std::vector<sp<BasicClient>> evicted;
3241 for (auto& i : mActiveClientManager.getAll()) {
3242 auto clientSp = i->getValue();
3243
3244 if (clientSp.get() == nullptr) {
3245 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3246 continue;
3247 }
3248
Ruben Brunk6267b532015-04-30 17:44:07 -07003249 // Don't evict clients that are still allowed.
3250 uid_t clientUid = clientSp->getClientUid();
3251 userid_t clientUserId = multiuser_get_user_id(clientUid);
3252 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3253 continue;
3254 }
3255
Ruben Brunk36597b22015-03-20 22:15:57 -07003256 evicted.push_back(clientSp);
3257
3258 String8 curTime = getFormattedCurrentTime();
3259
3260 ALOGE("Evicting conflicting client for camera ID %s due to user change",
3261 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003262
Ruben Brunk36597b22015-03-20 22:15:57 -07003263 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07003264 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003265 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
3266 " to user switch.", i->getKey().string(),
3267 String8{clientSp->getPackageName()}.string(),
3268 i->getOwnerId(), i->getPriority().getScore(),
3269 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003270
3271 }
3272
3273 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3274 // blocking other clients from connecting in mServiceLockWrapper if held.
3275 mServiceLock.unlock();
3276
3277 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07003278 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003279
3280 for (auto& i : evicted) {
3281 i->disconnect();
3282 }
3283
Jayant Chowdhary12361932018-08-27 14:46:13 -07003284 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003285
3286 // Reacquire mServiceLock
3287 mServiceLock.lock();
3288}
Ruben Brunkcc776712015-02-17 20:18:47 -08003289
Ruben Brunka8ca9152015-04-07 14:23:40 -07003290void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003291 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003292 Mutex::Autolock l(mLogLock);
Rucha Katakward9ea6452021-05-06 11:57:16 -07003293 String8 msg = String8::format("%s : %s", curTime.string(), event);
3294 // For service error events, print the msg only once.
3295 if(!msg.contains("SERVICE ERROR")) {
3296 mEventLog.add(msg);
3297 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3298 // Error event not added to the dumpsys log before
3299 mEventLog.add(msg);
3300 sServiceErrorEventSet.insert(msg);
3301 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003302}
3303
Ruben Brunka8ca9152015-04-07 14:23:40 -07003304void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003305 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003306 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07003307 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003308 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003309}
3310
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003311void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
3312 const char* clientPackage) {
3313 // Log the clients evicted
3314 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
3315 cameraId, clientPackage, clientPid));
3316}
3317
Ruben Brunka8ca9152015-04-07 14:23:40 -07003318void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003319 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003320 // Log the clients evicted
3321 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003322 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003323}
3324
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003325void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
3326 const char* clientPackage) {
3327 // Log the clients evicted
3328 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
3329 clientPackage, clientPid));
3330}
3331
Ruben Brunka8ca9152015-04-07 14:23:40 -07003332void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003333 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003334 // Log the client rejected
3335 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003336 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003337}
3338
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003339void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
3340 // Log torch event
3341 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
3342 torchState, clientPid));
3343}
3344
Ruben Brunk6267b532015-04-30 17:44:07 -07003345void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3346 const std::set<userid_t>& newUserIds) {
3347 String8 newUsers = toString(newUserIds);
3348 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003349 if (oldUsers.size() == 0) {
3350 oldUsers = "<None>";
3351 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003352 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003353 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07003354 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003355}
3356
3357void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
3358 // Log the device removal
3359 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
3360}
3361
3362void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
3363 // Log the device removal
3364 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
3365}
3366
3367void CameraService::logClientDied(int clientPid, const char* reason) {
3368 // Log the device removal
3369 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003370}
3371
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003372void CameraService::logServiceError(const char* msg, int errorCode) {
3373 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003374 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003375}
3376
Ruben Brunk36597b22015-03-20 22:15:57 -07003377status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3378 uint32_t flags) {
3379
Mathias Agopian65ab4712010-07-14 17:59:35 -07003380 // Permission checks
3381 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003382 case SHELL_COMMAND_TRANSACTION: {
3383 int in = data.readFileDescriptor();
3384 int out = data.readFileDescriptor();
3385 int err = data.readFileDescriptor();
3386 int argc = data.readInt32();
3387 Vector<String16> args;
3388 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3389 args.add(data.readString16());
3390 }
3391 sp<IBinder> unusedCallback;
3392 sp<IResultReceiver> resultReceiver;
3393 status_t status;
3394 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3395 return status;
3396 }
3397 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3398 return status;
3399 }
3400 status = shellCommand(in, out, err, args);
3401 if (resultReceiver != nullptr) {
3402 resultReceiver->send(status);
3403 }
3404 return NO_ERROR;
3405 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003406 }
3407
3408 return BnCameraService::onTransact(code, data, reply, flags);
3409}
3410
Mathias Agopian65ab4712010-07-14 17:59:35 -07003411// We share the media players for shutter and recording sound for all clients.
3412// A reference count is kept to determine when we will actually release the
3413// media players.
3414
Jaekyun Seokef498052018-03-23 13:09:44 +09003415sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3416 sp<MediaPlayer> mp = new MediaPlayer();
3417 status_t error;
3418 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003419 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003420 error = mp->prepare();
3421 }
3422 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003423 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003424 mp->disconnect();
3425 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003426 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003427 }
3428 return mp;
3429}
3430
username5755fea2018-12-27 09:48:08 +08003431void CameraService::increaseSoundRef() {
3432 Mutex::Autolock lock(mSoundLock);
3433 mSoundRef++;
3434}
3435
3436void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003437 ATRACE_CALL();
3438
username5755fea2018-12-27 09:48:08 +08003439 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3440 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3441 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3442 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3443 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3444 }
3445 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3446 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3447 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3448 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003449 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003450 }
3451 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3452 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3453 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3454 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3455 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003456 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003457}
3458
username5755fea2018-12-27 09:48:08 +08003459void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003460 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003461 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003462 if (--mSoundRef) return;
3463
3464 for (int i = 0; i < NUM_SOUNDS; i++) {
3465 if (mSoundPlayer[i] != 0) {
3466 mSoundPlayer[i]->disconnect();
3467 mSoundPlayer[i].clear();
3468 }
3469 }
3470}
3471
3472void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003473 ATRACE_CALL();
3474
Mathias Agopian65ab4712010-07-14 17:59:35 -07003475 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07003476 if (kind < 0 || kind >= NUM_SOUNDS) {
3477 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
3478 return;
3479 }
3480
Mathias Agopian65ab4712010-07-14 17:59:35 -07003481 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003482 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003483 sp<MediaPlayer> player = mSoundPlayer[kind];
3484 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08003485 player->seekTo(0);
3486 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003487 }
3488}
3489
3490// ----------------------------------------------------------------------------
3491
3492CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07003493 const sp<ICameraClient>& cameraClient,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003494 const String16& clientPackageName, bool systemNativeClient,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003495 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003496 const String8& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003497 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003498 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003499 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003500 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003501 IInterface::asBinder(cameraClient),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003502 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003503 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003504 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003505 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003506 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003507{
Jayant Chowdhary12361932018-08-27 14:46:13 -07003508 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003509 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003510
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003511 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003512
username5755fea2018-12-27 09:48:08 +08003513 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003514
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003515 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003516}
3517
Mathias Agopian65ab4712010-07-14 17:59:35 -07003518// tear down the client
3519CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003520 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08003521 mDestructionStarted = true;
3522
username5755fea2018-12-27 09:48:08 +08003523 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003524 // unconditionally disconnect. function is idempotent
3525 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003526}
3527
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003528sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
3529
Igor Murashkin634a5152013-02-20 17:15:11 -08003530CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003531 const sp<IBinder>& remoteCallback,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003532 const String16& clientPackageName, bool nativeClient,
3533 const std::optional<String16>& clientFeatureId, const String8& cameraIdStr,
3534 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003535 int servicePid, bool overrideToPortrait):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003536 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07003537 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003538 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
3539 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003540 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003541 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07003542 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07003543 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003544 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003545 mRemoteBinder(remoteCallback),
3546 mOpsActive(false),
3547 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08003548{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003549 if (sCameraService == nullptr) {
3550 sCameraService = cameraService;
3551 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08003552
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003553 // There are 2 scenarios in which a client won't have AppOps operations
3554 // (both scenarios : native clients)
3555 // 1) It's an system native client*, the package name will be empty
3556 // and it will return from this function in the previous if condition
3557 // (This is the same as the previously existing behavior).
3558 // 2) It is a system native client, but its package name has been
3559 // modified for debugging, however it still must not use AppOps since
3560 // the package name is not a real one.
3561 //
3562 // * system native client - native client with UID < AID_APP_START. It
3563 // doesn't exclude clients not on the system partition.
3564 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003565 mAppOpsManager = std::make_unique<AppOpsManager>();
3566 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07003567
3568 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08003569}
3570
3571CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003572 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08003573 mDestructionStarted = true;
3574}
3575
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003576binder::Status CameraService::BasicClient::disconnect() {
3577 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003578 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003579 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07003580 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07003581 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08003582
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003583 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003584 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07003585 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
3586 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003587
3588 sp<IBinder> remote = getRemote();
3589 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003590 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08003591 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003592
3593 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07003594 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003595 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
3596 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
3597 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003598
Igor Murashkincba2c162013-03-20 15:56:31 -07003599 // client shouldn't be able to call into us anymore
3600 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003601
3602 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08003603}
3604
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003605status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
3606 // No dumping of clients directly over Binder,
3607 // must go through CameraService::dump
3608 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003609 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003610 return OK;
3611}
3612
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07003613status_t CameraService::BasicClient::startWatchingTags(const String8&, int) {
3614 // Can't watch tags directly, must go through CameraService::startWatchingTags
3615 return OK;
3616}
3617
3618status_t CameraService::BasicClient::stopWatchingTags(int) {
3619 // Can't watch tags directly, must go through CameraService::stopWatchingTags
3620 return OK;
3621}
3622
3623status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
3624 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
3625 return OK;
3626}
3627
Ruben Brunkcc776712015-02-17 20:18:47 -08003628String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003629 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08003630}
3631
Emilian Peev8b64f282021-03-25 16:49:57 -07003632int CameraService::BasicClient::getCameraFacing() const {
3633 return mCameraFacing;
3634}
3635
3636int CameraService::BasicClient::getCameraOrientation() const {
3637 return mOrientation;
3638}
Ruben Brunkcc776712015-02-17 20:18:47 -08003639
3640int CameraService::BasicClient::getClientPid() const {
3641 return mClientPid;
3642}
3643
Ruben Brunk6267b532015-04-30 17:44:07 -07003644uid_t CameraService::BasicClient::getClientUid() const {
3645 return mClientUid;
3646}
3647
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003648bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
3649 // Defaults to API2.
3650 return level == API_2;
3651}
3652
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003653status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003654 {
3655 Mutex::Autolock l(mAudioRestrictionLock);
3656 mAudioRestriction = mode;
3657 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003658 sCameraService->updateAudioRestriction();
3659 return OK;
3660}
3661
3662int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003663 return sCameraService->updateAudioRestriction();
3664}
3665
3666int32_t CameraService::BasicClient::getAudioRestriction() const {
3667 Mutex::Autolock l(mAudioRestrictionLock);
3668 return mAudioRestriction;
3669}
3670
3671bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
3672 switch (mode) {
3673 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
3674 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
3675 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
3676 return true;
3677 default:
3678 return false;
3679 }
3680}
3681
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003682status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
3683 if (mode == AppOpsManager::MODE_ERRORED) {
3684 ALOGI("Camera %s: Access for \"%s\" has been revoked",
3685 mCameraIdStr.string(), String8(mClientPackageName).string());
3686 return PERMISSION_DENIED;
3687 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
3688 // If the calling Uid is trusted (a native service), the AppOpsManager could
3689 // return MODE_IGNORED. Do not treat such case as error.
3690 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
3691 mClientPackageName);
3692 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08003693 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayana8143e572023-01-09 08:46:49 -08003694 // We don't want to return EACCESS if the CameraPrivacy is enabled.
3695 // We prefer to successfully open the camera and perform camera muting
3696 // or blocking in connectHelper as handleAppOpMode can be called before the
3697 // connection has been fully established and at that time camera muting
3698 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003699 if (!isUidActive || !isCameraPrivacyEnabled) {
3700 ALOGI("Camera %s: Access for \"%s\" has been restricted",
3701 mCameraIdStr.string(), String8(mClientPackageName).string());
3702 // Return the same error as for device policy manager rejection
3703 return -EACCES;
3704 }
3705 }
3706 return OK;
3707}
3708
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003709status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003710 ATRACE_CALL();
3711
Igor Murashkine6800ce2013-03-04 17:25:57 -08003712 {
3713 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003714 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003715 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003716 if (mAppOpsManager != nullptr) {
3717 // Notify app ops that the camera is not available
3718 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003719 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
3720 mClientPackageName, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003721
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003722 // Just check for camera acccess here on open - delay startOp until
3723 // camera frames start streaming in startCameraStreamingOps
3724 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
3725 mClientPackageName);
3726 status_t res = handleAppOpMode(mode);
3727 if (res != OK) {
3728 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003729 }
Svetoslav28e8ef72015-05-11 19:21:31 -07003730 }
3731
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003732 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003733
3734 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003735 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003736
Emilian Peev53722fa2019-02-22 17:47:20 -08003737 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
3738
Shuzhen Wang695044d2020-03-06 09:02:23 -08003739 // Notify listeners of camera open/close status
3740 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
3741
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003742 return OK;
3743}
3744
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003745status_t CameraService::BasicClient::startCameraStreamingOps() {
3746 ATRACE_CALL();
3747
3748 if (!mOpsActive) {
3749 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3750 return INVALID_OPERATION;
3751 }
3752 if (mOpsStreaming) {
3753 ALOGV("%s: Streaming already active!", __FUNCTION__);
3754 return OK;
3755 }
3756
3757 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
3758 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3759
3760 if (mAppOpsManager != nullptr) {
3761 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
3762 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
3763 String16("start camera ") + String16(mCameraIdStr));
3764 status_t res = handleAppOpMode(mode);
3765 if (res != OK) {
3766 return res;
3767 }
3768 }
3769
3770 mOpsStreaming = true;
3771
3772 return OK;
3773}
3774
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003775status_t CameraService::BasicClient::noteAppOp() {
3776 ATRACE_CALL();
3777
3778 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
3779 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3780
3781 // noteAppOp is only used for when camera mute is not supported, in order
3782 // to trigger the sensor privacy "Unblock" dialog
3783 if (mAppOpsManager != nullptr) {
3784 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
3785 mClientPackageName, mClientFeatureId,
3786 String16("start camera ") + String16(mCameraIdStr));
3787 status_t res = handleAppOpMode(mode);
3788 if (res != OK) {
3789 return res;
3790 }
3791 }
3792
3793 return OK;
3794}
3795
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003796status_t CameraService::BasicClient::finishCameraStreamingOps() {
3797 ATRACE_CALL();
3798
3799 if (!mOpsActive) {
3800 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3801 return INVALID_OPERATION;
3802 }
3803 if (!mOpsStreaming) {
3804 ALOGV("%s: Streaming not active!", __FUNCTION__);
3805 return OK;
3806 }
3807
3808 if (mAppOpsManager != nullptr) {
3809 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
3810 mClientPackageName, mClientFeatureId);
3811 mOpsStreaming = false;
3812 }
3813
3814 return OK;
3815}
3816
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003817status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003818 ATRACE_CALL();
3819
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003820 if (mOpsStreaming) {
3821 // Make sure we've notified everyone about camera stopping
3822 finishCameraStreamingOps();
3823 }
3824
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003825 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003826 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003827 mOpsActive = false;
3828
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003829 // This function is called when a client disconnects. This should
3830 // release the camera, but actually only if it was in a proper
3831 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003832 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003833 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003834
Ruben Brunkcc776712015-02-17 20:18:47 -08003835 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003836 sCameraService->updateStatus(StatusInternal::PRESENT,
3837 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003838 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003839 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003840 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3841 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003842 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003843 mOpsCallback.clear();
3844
Emilian Peev53722fa2019-02-22 17:47:20 -08003845 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3846
Shuzhen Wang695044d2020-03-06 09:02:23 -08003847 // Notify listeners of camera open/close status
3848 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3849
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003850 return OK;
3851}
3852
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003853void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003854 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003855 if (mAppOpsManager == nullptr) {
3856 return;
3857 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003858 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003859 if (op != AppOpsManager::OP_CAMERA) {
3860 ALOGW("Unexpected app ops notification received: %d", op);
3861 return;
3862 }
3863
3864 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003865 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003866 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003867 ALOGV("checkOp returns: %d, %s ", res,
3868 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3869 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3870 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3871 "UNKNOWN");
3872
Shuzhen Wang64900852021-02-05 09:03:29 -08003873 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003874 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003875 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003876 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003877 } else if (res == AppOpsManager::MODE_IGNORED) {
3878 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08003879 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08003880 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Shuzhen Wang64900852021-02-05 09:03:29 -08003881 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3882 mCameraIdStr.string(), String8(mClientPackageName).string(),
3883 mUidIsTrusted, isUidActive);
3884 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3885 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3886 // error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003887 if (!mUidIsTrusted) {
3888 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
3889 setCameraMute(true);
3890 } else if (!isUidActive
3891 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
3892 block();
3893 }
Shuzhen Wang64900852021-02-05 09:03:29 -08003894 }
Evan Severson09ab4002021-02-10 14:15:19 -08003895 } else if (res == AppOpsManager::MODE_ALLOWED) {
3896 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003897 }
3898}
3899
Svet Ganova453d0d2018-01-11 15:37:58 -08003900void CameraService::BasicClient::block() {
3901 ATRACE_CALL();
3902
3903 // Reset the client PID to allow server-initiated disconnect,
3904 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003905 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003906 CaptureResultExtras resultExtras; // a dummy result (invalid)
3907 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3908 disconnect();
3909}
3910
Mathias Agopian65ab4712010-07-14 17:59:35 -07003911// ----------------------------------------------------------------------------
3912
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003913void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08003914 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003915 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003916 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3917 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3918 api1ErrorCode = CAMERA_ERROR_DISABLED;
3919 }
3920 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003921 } else {
3922 ALOGE("mRemoteCallback is NULL!!");
3923 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003924}
3925
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003926// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003927binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003928 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003929 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003930}
3931
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003932bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3933 return level == API_1;
3934}
3935
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003936CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3937 mClient(client) {
3938}
3939
3940void CameraService::Client::OpsCallback::opChanged(int32_t op,
3941 const String16& packageName) {
3942 sp<BasicClient> client = mClient.promote();
3943 if (client != NULL) {
3944 client->opChanged(op, packageName);
3945 }
3946}
3947
Mathias Agopian65ab4712010-07-14 17:59:35 -07003948// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003949// UidPolicy
3950// ----------------------------------------------------------------------------
3951
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08003952void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003953 Mutex::Autolock _l(mUidLock);
3954
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003955 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003956 status_t res = mAm.linkToDeath(this);
3957 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003958 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00003959 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
3960 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08003961 ActivityManager::PROCESS_STATE_UNKNOWN,
3962 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003963 if (res == OK) {
3964 mRegistered = true;
3965 ALOGV("UidPolicy: Registered with ActivityManager");
3966 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003967}
3968
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08003969void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
3970 if (name != String16(kActivityServiceName)) {
3971 return;
3972 }
3973
3974 registerWithActivityManager();
3975}
3976
3977void CameraService::UidPolicy::registerSelf() {
3978 // Use check service to see if the activity service is available
3979 // If not available then register for notifications, instead of blocking
3980 // till the service is ready
3981 sp<IServiceManager> sm = defaultServiceManager();
3982 sp<IBinder> binder = sm->checkService(String16(kActivityServiceName));
3983 if (!binder) {
3984 sm->registerForNotifications(String16(kActivityServiceName), this);
3985 } else {
3986 registerWithActivityManager();
3987 }
3988}
3989
Svet Ganova453d0d2018-01-11 15:37:58 -08003990void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003991 Mutex::Autolock _l(mUidLock);
3992
Steven Moreland2f348142019-07-02 15:59:07 -07003993 mAm.unregisterUidObserver(this);
3994 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003995 mRegistered = false;
3996 mActiveUids.clear();
3997 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003998}
3999
4000void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4001 onUidIdle(uid, disabled);
4002}
4003
4004void CameraService::UidPolicy::onUidActive(uid_t uid) {
4005 Mutex::Autolock _l(mUidLock);
4006 mActiveUids.insert(uid);
4007}
4008
4009void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4010 bool deleted = false;
4011 {
4012 Mutex::Autolock _l(mUidLock);
4013 if (mActiveUids.erase(uid) > 0) {
4014 deleted = true;
4015 }
4016 }
4017 if (deleted) {
4018 sp<CameraService> service = mService.promote();
4019 if (service != nullptr) {
4020 service->blockClientsForUid(uid);
4021 }
4022 }
4023}
4024
Emilian Peev53722fa2019-02-22 17:47:20 -08004025void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004026 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004027 bool procStateChange = false;
4028 {
4029 Mutex::Autolock _l(mUidLock);
4030 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4031 mMonitoredUids[uid].procState != procState) {
4032 mMonitoredUids[uid].procState = procState;
4033 procStateChange = true;
4034 }
4035 }
4036
4037 if (procStateChange) {
4038 sp<CameraService> service = mService.promote();
4039 if (service != nullptr) {
4040 service->notifyMonitoredUids();
4041 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004042 }
4043}
4044
Austin Borger65577682022-02-17 00:25:43 +00004045void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid) {
4046 bool procAdjChange = false;
4047 {
4048 Mutex::Autolock _l(mUidLock);
4049 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
4050 procAdjChange = true;
4051 }
4052 }
4053
4054 if (procAdjChange) {
4055 sp<CameraService> service = mService.promote();
4056 if (service != nullptr) {
4057 service->notifyMonitoredUids();
4058 }
4059 }
4060}
4061
Emilian Peev53722fa2019-02-22 17:47:20 -08004062void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
4063 Mutex::Autolock _l(mUidLock);
4064 auto it = mMonitoredUids.find(uid);
4065 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004066 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004067 } else {
Austin Borger65577682022-02-17 00:25:43 +00004068 MonitoredUid monitoredUid;
4069 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
4070 monitoredUid.refCount = 1;
4071 mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid));
Emilian Peev53722fa2019-02-22 17:47:20 -08004072 }
4073}
4074
4075void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
4076 Mutex::Autolock _l(mUidLock);
4077 auto it = mMonitoredUids.find(uid);
4078 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004079 it->second.refCount--;
4080 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004081 mMonitoredUids.erase(it);
4082 }
4083 } else {
4084 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4085 }
4086}
4087
Svet Ganov7b4ab782018-03-25 12:48:10 -07004088bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004089 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004090 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004091}
4092
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004093static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4094static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004095
Svet Ganov7b4ab782018-03-25 12:48:10 -07004096bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004097 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004098 // If activity manager is unreachable, assume everything is active
4099 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004100 return true;
4101 }
4102 auto it = mOverrideUids.find(uid);
4103 if (it != mOverrideUids.end()) {
4104 return it->second;
4105 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004106 bool active = mActiveUids.find(uid) != mActiveUids.end();
4107 if (!active) {
4108 // We want active UIDs to always access camera with their first attempt since
4109 // there is no guarantee the app is robustly written and would retry getting
4110 // the camera on failure. The inverse case is not a problem as we would take
4111 // camera away soon once we get the callback that the uid is no longer active.
4112 ActivityManager am;
4113 // Okay to access with a lock held as UID changes are dispatched without
4114 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004115 int64_t startTimeMillis = 0;
4116 do {
4117 // TODO: Fix this b/109950150!
4118 // Okay this is a hack. There is a race between the UID turning active and
4119 // activity being resumed. The proper fix is very risky, so we temporary add
4120 // some polling which should happen pretty rarely anyway as the race is hard
4121 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004122 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00004123 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07004124 if (active) {
4125 break;
4126 }
4127 if (startTimeMillis <= 0) {
4128 startTimeMillis = uptimeMillis();
4129 }
4130 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004131 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004132 if (remainingTimeMillis <= 0) {
4133 break;
4134 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004135 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4136
4137 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004138 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004139 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004140 } while (true);
4141
Svet Ganov7b4ab782018-03-25 12:48:10 -07004142 if (active) {
4143 // Now that we found out the UID is actually active, cache that
4144 mActiveUids.insert(uid);
4145 }
4146 }
4147 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004148}
4149
Varun Shahb42f1eb2019-04-16 14:45:13 -07004150int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4151 Mutex::Autolock _l(mUidLock);
4152 return getProcStateLocked(uid);
4153}
4154
4155int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4156 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4157 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004158 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004159 }
4160 return procState;
4161}
4162
Svet Ganov7b4ab782018-03-25 12:48:10 -07004163void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
4164 String16 callingPackage, bool active) {
4165 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004166}
4167
Svet Ganov7b4ab782018-03-25 12:48:10 -07004168void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
4169 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004170}
4171
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004172void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4173 Mutex::Autolock _l(mUidLock);
4174 ALOGV("UidPolicy: ActivityManager has died");
4175 mRegistered = false;
4176 mActiveUids.clear();
4177}
4178
Svet Ganov7b4ab782018-03-25 12:48:10 -07004179void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
4180 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004181 bool wasActive = false;
4182 bool isActive = false;
4183 {
4184 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004185 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004186 mOverrideUids.erase(uid);
4187 if (insert) {
4188 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4189 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004190 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004191 }
4192 if (wasActive != isActive && !isActive) {
4193 sp<CameraService> service = mService.promote();
4194 if (service != nullptr) {
4195 service->blockClientsForUid(uid);
4196 }
4197 }
4198}
4199
4200// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004201// SensorPrivacyPolicy
4202// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004203
4204void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4205{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004206 Mutex::Autolock _l(mSensorPrivacyLock);
4207 if (mRegistered) {
4208 return;
4209 }
Evan Severson09ab4002021-02-10 14:15:19 -08004210 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004211 mSpm.addSensorPrivacyListener(this);
4212 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
4213 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004214 if (res == OK) {
4215 mRegistered = true;
4216 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4217 }
4218}
4219
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004220void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4221 const sp<IBinder>&) {
4222 if (name != String16(kSensorPrivacyServiceName)) {
4223 return;
4224 }
4225
4226 registerWithSensorPrivacyManager();
4227}
4228
4229void CameraService::SensorPrivacyPolicy::registerSelf() {
4230 // Use checkservice to see if the sensor_privacy service is available
4231 // If service is not available then register for notification
4232 sp<IServiceManager> sm = defaultServiceManager();
4233 sp<IBinder> binder = sm->checkService(String16(kSensorPrivacyServiceName));
4234 if (!binder) {
4235 sm->registerForNotifications(String16(kSensorPrivacyServiceName),this);
4236 } else {
4237 registerWithSensorPrivacyManager();
4238 }
4239}
4240
Michael Grooverd1d435a2018-12-18 17:39:42 -08004241void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4242 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004243 mSpm.removeSensorPrivacyListener(this);
4244 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004245 mRegistered = false;
4246 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4247}
4248
4249bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004250 if (!mRegistered) {
4251 registerWithSensorPrivacyManager();
4252 }
4253
Michael Grooverd1d435a2018-12-18 17:39:42 -08004254 Mutex::Autolock _l(mSensorPrivacyLock);
4255 return mSensorPrivacyEnabled;
4256}
4257
Evan Seversond0b69922022-01-27 10:47:34 -08004258bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004259 if (!hasCameraPrivacyFeature()) {
4260 return false;
4261 }
Evan Seversond0b69922022-01-27 10:47:34 -08004262 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004263}
4264
Evan Seversond0b69922022-01-27 10:47:34 -08004265binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
4266 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08004267 {
4268 Mutex::Autolock _l(mSensorPrivacyLock);
Kwangkyu Parke3af2992022-11-05 02:46:52 +09004269 mSensorPrivacyEnabled = enabled;
Michael Grooverd1d435a2018-12-18 17:39:42 -08004270 }
4271 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08004272 if (enabled) {
4273 sp<CameraService> service = mService.promote();
4274 if (service != nullptr) {
4275 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004276 }
4277 }
4278 return binder::Status::ok();
4279}
4280
4281void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4282 Mutex::Autolock _l(mSensorPrivacyLock);
4283 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
4284 mRegistered = false;
4285}
4286
Evan Severson09ab4002021-02-10 14:15:19 -08004287bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08004288 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
4289 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4290 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
4291 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4292 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08004293}
4294
Michael Grooverd1d435a2018-12-18 17:39:42 -08004295// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004296// CameraState
4297// ----------------------------------------------------------------------------
4298
4299CameraService::CameraState::CameraState(const String8& id, int cost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004300 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind,
4301 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004302 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004303 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08004304
4305CameraService::CameraState::~CameraState() {}
4306
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004307CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004308 Mutex::Autolock lock(mStatusLock);
4309 return mStatus;
4310}
4311
Shuzhen Wang43858162020-01-10 13:42:15 -08004312std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
4313 Mutex::Autolock lock(mStatusLock);
4314 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
4315 return res;
4316}
4317
Ruben Brunkcc776712015-02-17 20:18:47 -08004318CameraParameters CameraService::CameraState::getShimParams() const {
4319 return mShimParams;
4320}
4321
4322void CameraService::CameraState::setShimParams(const CameraParameters& params) {
4323 mShimParams = params;
4324}
4325
4326int CameraService::CameraState::getCost() const {
4327 return mCost;
4328}
4329
4330std::set<String8> CameraService::CameraState::getConflicting() const {
4331 return mConflicting;
4332}
4333
4334String8 CameraService::CameraState::getId() const {
4335 return mId;
4336}
4337
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004338SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
4339 return mSystemCameraKind;
4340}
4341
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004342bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
4343 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
4344 != mPhysicalCameras.end();
4345}
4346
Shuzhen Wang43858162020-01-10 13:42:15 -08004347bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
4348 Mutex::Autolock lock(mStatusLock);
4349 auto result = mUnavailablePhysicalIds.insert(physicalId);
4350 return result.second;
4351}
4352
4353bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
4354 Mutex::Autolock lock(mStatusLock);
4355 auto count = mUnavailablePhysicalIds.erase(physicalId);
4356 return count > 0;
4357}
4358
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004359void CameraService::CameraState::setClientPackage(const String8& clientPackage) {
4360 Mutex::Autolock lock(mStatusLock);
4361 mClientPackage = clientPackage;
4362}
4363
4364String8 CameraService::CameraState::getClientPackage() const {
4365 Mutex::Autolock lock(mStatusLock);
4366 return mClientPackage;
4367}
4368
Ruben Brunkcc776712015-02-17 20:18:47 -08004369// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07004370// ClientEventListener
4371// ----------------------------------------------------------------------------
4372
4373void CameraService::ClientEventListener::onClientAdded(
4374 const resource_policy::ClientDescriptor<String8,
4375 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004376 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004377 if (basicClient.get() != nullptr) {
4378 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4379 notifier.noteStartCamera(descriptor.getKey(),
4380 static_cast<int>(basicClient->getClientUid()));
4381 }
4382}
4383
4384void CameraService::ClientEventListener::onClientRemoved(
4385 const resource_policy::ClientDescriptor<String8,
4386 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004387 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004388 if (basicClient.get() != nullptr) {
4389 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4390 notifier.noteStopCamera(descriptor.getKey(),
4391 static_cast<int>(basicClient->getClientUid()));
4392 }
4393}
4394
4395
4396// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004397// CameraClientManager
4398// ----------------------------------------------------------------------------
4399
Ruben Brunk99e69712015-05-26 17:25:07 -07004400CameraService::CameraClientManager::CameraClientManager() {
4401 setListener(std::make_shared<ClientEventListener>());
4402}
4403
Ruben Brunkcc776712015-02-17 20:18:47 -08004404CameraService::CameraClientManager::~CameraClientManager() {}
4405
4406sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
4407 const String8& id) const {
4408 auto descriptor = get(id);
4409 if (descriptor == nullptr) {
4410 return sp<BasicClient>{nullptr};
4411 }
4412 return descriptor->getValue();
4413}
4414
4415String8 CameraService::CameraClientManager::toString() const {
4416 auto all = getAll();
4417 String8 ret("[");
4418 bool hasAny = false;
4419 for (auto& i : all) {
4420 hasAny = true;
4421 String8 key = i->getKey();
4422 int32_t cost = i->getCost();
4423 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00004424 int32_t score = i->getPriority().getScore();
4425 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08004426 auto conflicting = i->getConflicting();
4427 auto clientSp = i->getValue();
4428 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07004429 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08004430 if (clientSp.get() != nullptr) {
4431 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07004432 uid_t clientUid = clientSp->getClientUid();
4433 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004434 }
Emilian Peev8131a262017-02-01 12:33:43 +00004435 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
4436 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08004437
Ruben Brunk6267b532015-04-30 17:44:07 -07004438 if (clientSp.get() != nullptr) {
4439 ret.appendFormat("User Id: %d, ", clientUserId);
4440 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004441 if (packageName.size() != 0) {
4442 ret.appendFormat("Client Package Name: %s", packageName.string());
4443 }
4444
4445 ret.append(", Conflicting Client Devices: {");
4446 for (auto& j : conflicting) {
4447 ret.appendFormat("%s, ", j.string());
4448 }
4449 ret.append("})");
4450 }
4451 if (hasAny) ret.append("\n");
4452 ret.append("]\n");
4453 return ret;
4454}
4455
4456CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
4457 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00004458 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004459 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004460
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004461 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
4462 int32_t state_adj = systemNativeClient ? kSystemNativeClientState: state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07004463
Ruben Brunkcc776712015-02-17 20:18:47 -08004464 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004465 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
4466 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08004467}
4468
4469CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004470 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004471 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004472 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00004473 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004474 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
4475 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08004476}
4477
4478// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08004479// InjectionStatusListener
4480// ----------------------------------------------------------------------------
4481
4482void CameraService::InjectionStatusListener::addListener(
4483 const sp<ICameraInjectionCallback>& callback) {
4484 Mutex::Autolock lock(mListenerLock);
4485 if (mCameraInjectionCallback) return;
4486 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
4487 if (res == OK) {
4488 mCameraInjectionCallback = callback;
4489 }
4490}
4491
4492void CameraService::InjectionStatusListener::removeListener() {
4493 Mutex::Autolock lock(mListenerLock);
4494 if (mCameraInjectionCallback == nullptr) {
4495 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4496 return;
4497 }
4498 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
4499 mCameraInjectionCallback = nullptr;
4500}
4501
4502void CameraService::InjectionStatusListener::notifyInjectionError(
Cliff Wud3a05312021-04-26 23:07:31 +08004503 String8 injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08004504 if (mCameraInjectionCallback == nullptr) {
4505 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4506 return;
4507 }
Cliff Wud3a05312021-04-26 23:07:31 +08004508
4509 switch (err) {
4510 case -ENODEV:
4511 mCameraInjectionCallback->onInjectionError(
4512 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4513 ALOGE("No camera device with ID \"%s\" currently available!",
4514 injectedCamId.string());
4515 break;
4516 case -EBUSY:
4517 mCameraInjectionCallback->onInjectionError(
4518 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4519 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
4520 injectedCamId.string());
4521 break;
4522 case DEAD_OBJECT:
4523 mCameraInjectionCallback->onInjectionError(
4524 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4525 ALOGE("Camera ID \"%s\" object is dead!",
4526 injectedCamId.string());
4527 break;
4528 case INVALID_OPERATION:
4529 mCameraInjectionCallback->onInjectionError(
4530 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4531 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
4532 injectedCamId.string());
4533 break;
4534 case UNKNOWN_TRANSACTION:
4535 mCameraInjectionCallback->onInjectionError(
4536 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
4537 ALOGE("Camera ID \"%s\" method doesn't support!",
4538 injectedCamId.string());
4539 break;
4540 default:
4541 mCameraInjectionCallback->onInjectionError(
4542 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
4543 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
4544 strerror(-err), err, injectedCamId.string());
4545 }
Cliff Wud8cae102021-03-11 01:37:42 +08004546}
4547
4548void CameraService::InjectionStatusListener::binderDied(
4549 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08004550 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
4551 auto parent = mParent.promote();
4552 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08004553 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4554 if (clientDescriptor != nullptr) {
4555 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4556 baseClientPtr->stopInjection();
4557 }
Cliff Wu3b268182021-07-06 15:44:43 +08004558 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004559 }
4560}
4561
4562// ----------------------------------------------------------------------------
4563// CameraInjectionSession
4564// ----------------------------------------------------------------------------
4565
4566binder::Status CameraService::CameraInjectionSession::stopInjection() {
4567 Mutex::Autolock lock(mInjectionSessionLock);
4568 auto parent = mParent.promote();
4569 if (parent == nullptr) {
4570 ALOGE("CameraInjectionSession: Parent is gone");
4571 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
4572 "Camera service encountered error");
4573 }
Cliff Wud3a05312021-04-26 23:07:31 +08004574
4575 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08004576 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4577 if (clientDescriptor != nullptr) {
4578 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4579 res = baseClientPtr->stopInjection();
4580 if (res != OK) {
4581 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
4582 " ret != NO_ERROR: %d", res);
4583 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
4584 "Camera session encountered error");
4585 }
4586 }
Cliff Wu3b268182021-07-06 15:44:43 +08004587 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004588 return binder::Status::ok();
4589}
4590
4591// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07004592
4593static const int kDumpLockRetries = 50;
4594static const int kDumpLockSleep = 60000;
4595
4596static bool tryLock(Mutex& mutex)
4597{
4598 bool locked = false;
4599 for (int i = 0; i < kDumpLockRetries; ++i) {
4600 if (mutex.tryLock() == NO_ERROR) {
4601 locked = true;
4602 break;
4603 }
4604 usleep(kDumpLockSleep);
4605 }
4606 return locked;
4607}
4608
Rucha Katakwardf223072021-06-15 10:21:00 -07004609void CameraService::cacheDump() {
4610 if (mMemFd != -1) {
4611 const Vector<String16> args;
4612 ATRACE_CALL();
4613 // Acquiring service lock here will avoid the deadlock since
4614 // cacheDump will not be called during the second disconnect.
4615 Mutex::Autolock lock(mServiceLock);
4616
4617 Mutex::Autolock l(mCameraStatesLock);
4618 // Start collecting the info for open sessions and store it in temp file.
4619 for (const auto& state : mCameraStates) {
4620 String8 cameraId = state.first;
4621 auto clientDescriptor = mActiveClientManager.get(cameraId);
4622 if (clientDescriptor != nullptr) {
4623 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.string());
4624 // Log the current open session info before device is disconnected.
4625 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
4626 }
4627 }
4628 }
4629}
4630
Mathias Agopian65ab4712010-07-14 17:59:35 -07004631status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004632 ATRACE_CALL();
4633
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004634 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004635 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004636 CameraThreadState::getCallingPid(),
4637 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004638 return NO_ERROR;
4639 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004640 bool locked = tryLock(mServiceLock);
4641 // failed to lock - CameraService is probably deadlocked
4642 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004643 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004644 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004645
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004646 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004647 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07004648
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004649 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004650 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08004651
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004652 if (locked) mServiceLock.unlock();
4653 return NO_ERROR;
4654 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004655 dprintf(fd, "\n== Service global info: ==\n\n");
4656 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004657 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07004658 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
4659 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004660 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
4661 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
4662 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004663 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004664 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
4665 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Shuzhen Wang16610a62022-12-15 22:38:07 -08004666 if (mStreamUseCaseOverrides.size() > 0) {
4667 dprintf(fd, "Active stream use case overrides:");
4668 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
4669 dprintf(fd, " %" PRId64, useCaseOverride);
4670 }
4671 dprintf(fd, "\n");
4672 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004673
4674 dumpEventLog(fd);
4675
4676 bool stateLocked = tryLock(mCameraStatesLock);
4677 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004678 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004679 }
4680
Emilian Peevbd8c5032018-02-14 23:05:40 +00004681 int argSize = args.size();
4682 for (int i = 0; i < argSize; i++) {
4683 if (args[i] == TagMonitor::kMonitorOption) {
4684 if (i + 1 < argSize) {
4685 mMonitorTags = String8(args[i + 1]);
4686 }
4687 break;
4688 }
4689 }
4690
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004691 for (auto& state : mCameraStates) {
4692 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004693
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004694 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004695
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004696 CameraParameters p = state.second->getShimParams();
4697 if (!p.isEmpty()) {
4698 dprintf(fd, " Camera1 API shim is using parameters:\n ");
4699 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004700 }
4701
4702 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004703 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004704 // log the current open session info
4705 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004706 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07004707 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004708 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004709
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004710 }
4711
4712 if (stateLocked) mCameraStatesLock.unlock();
4713
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004714 if (locked) mServiceLock.unlock();
4715
Emilian Peevf53f66e2017-04-11 14:29:43 +01004716 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004717
4718 dprintf(fd, "\n== Vendor tags: ==\n\n");
4719
4720 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
4721 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00004722 sp<VendorTagDescriptorCache> cache =
4723 VendorTagDescriptorCache::getGlobalVendorTagCache();
4724 if (cache == NULL) {
4725 dprintf(fd, "No vendor tags.\n");
4726 } else {
4727 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
4728 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004729 } else {
4730 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
4731 }
4732
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004733 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004734 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004735 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004736
4737 // Process dump arguments, if any
4738 int n = args.size();
4739 String16 verboseOption("-v");
4740 String16 unreachableOption("--unreachable");
4741 for (int i = 0; i < n; i++) {
4742 if (args[i] == verboseOption) {
4743 // change logging level
4744 if (i + 1 >= n) continue;
4745 String8 levelStr(args[i+1]);
4746 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004747 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004748 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004749 } else if (args[i] == unreachableOption) {
4750 // Dump memory analysis
4751 // TODO - should limit be an argument parameter?
4752 UnreachableMemoryInfo info;
4753 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
4754 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004755 dprintf(fd, "\n== Unable to dump unreachable memory. "
4756 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004757 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004758 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004759 std::string s = info.ToString(/*log_contents*/ true);
4760 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004761 }
4762 }
4763 }
Rucha Katakwardf223072021-06-15 10:21:00 -07004764
4765 bool serviceLocked = tryLock(mServiceLock);
4766
4767 // Dump info from previous open sessions.
4768 // Reposition the offset to beginning of the file before reading
4769
4770 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
4771 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
4772 ssize_t size_read;
4773 char buf[4096];
4774 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
4775 // Read data from file to a small buffer and write it to fd.
4776 write(fd, buf, size_read);
4777 if (size_read == -1) {
4778 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4779 break;
4780 }
4781 }
4782 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
4783 } else {
4784 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4785 }
4786
4787 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004788 return NO_ERROR;
4789}
4790
Rucha Katakwardf223072021-06-15 10:21:00 -07004791void CameraService::dumpOpenSessionClientLogs(int fd,
4792 const Vector<String16>& args, const String8& cameraId) {
4793 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07004794 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
4795 getFormattedCurrentTime().string(),
4796 cameraId.string());
Rucha Katakwardf223072021-06-15 10:21:00 -07004797 dprintf(fd, " Client priority score: %d state: %d\n",
4798 clientDescriptor->getPriority().getScore(),
4799 clientDescriptor->getPriority().getState());
4800 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
4801
4802 auto client = clientDescriptor->getValue();
4803 dprintf(fd, " Client package: %s\n",
4804 String8(client->getPackageName()).string());
4805
4806 client->dumpClient(fd, args);
4807}
4808
4809void CameraService::dumpClosedSessionClientLogs(int fd, const String8& cameraId) {
4810 dprintf(fd, " Device %s is closed, no client instance\n",
4811 cameraId.string());
4812}
4813
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004814void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004815 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004816
4817 Mutex::Autolock l(mLogLock);
4818 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004819 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004820 }
4821
4822 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004823 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004824 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004825 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004826 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004827 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004828}
4829
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004830void CameraService::cacheClientTagDumpIfNeeded(const char *cameraId, BasicClient* client) {
4831 Mutex::Autolock lock(mLogLock);
4832 if (!isClientWatchedLocked(client)) { return; }
4833
4834 std::vector<std::string> dumpVector;
4835 client->dumpWatchedEventsToVector(dumpVector);
4836
4837 if (dumpVector.empty()) { return; }
4838
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004839 std::string dumpString;
4840
4841 String8 currentTime = getFormattedCurrentTime();
4842 dumpString += "Cached @ ";
4843 dumpString += currentTime.string();
4844 dumpString += "\n"; // First line is the timestamp of when client is cached.
4845
4846
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004847 const String16 &packageName = client->getPackageName();
4848
4849 String8 packageName8 = String8(packageName);
4850 const char *printablePackageName = packageName8.lockBuffer(packageName.size());
4851
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004852
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004853 size_t i = dumpVector.size();
4854
4855 // Store the string in reverse order (latest last)
4856 while (i > 0) {
4857 i--;
4858 dumpString += cameraId;
4859 dumpString += ":";
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004860 dumpString += printablePackageName;
4861 dumpString += " ";
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004862 dumpString += dumpVector[i]; // implicitly ends with '\n'
4863 }
4864
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004865 packageName8.unlockBuffer();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004866 mWatchedClientsDumpCache[packageName] = dumpString;
4867}
4868
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004869void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004870 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004871 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
4872 if (mTorchClientMap[i] == who) {
4873 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004874 String8 cameraId = mTorchClientMap.keyAt(i);
4875 status_t res = mFlashlight->setTorchMode(cameraId, false);
4876 if (res) {
4877 ALOGE("%s: torch client died but couldn't turn off torch: "
4878 "%s (%d)", __FUNCTION__, strerror(-res), res);
4879 return;
4880 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004881 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004882 break;
4883 }
4884 }
4885}
4886
Ruben Brunkcc776712015-02-17 20:18:47 -08004887/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07004888
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004889 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07004890 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
4891 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004892 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08004893 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004894 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004895
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004896 // check torch client
4897 handleTorchClientBinderDied(who);
4898
4899 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08004900 if(!evictClientIdByRemote(who)) {
4901 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004902 return;
4903 }
4904
Ruben Brunkcc776712015-02-17 20:18:47 -08004905 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
4906 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004907}
4908
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004909void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004910 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08004911}
4912
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004913void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
4914 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004915 // Do not lock mServiceLock here or can get into a deadlock from
4916 // connect() -> disconnect -> updateStatus
4917
4918 auto state = getCameraState(cameraId);
4919
4920 if (state == nullptr) {
4921 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4922 cameraId.string());
4923 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07004924 }
4925
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004926 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
4927 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
4928 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
4929 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
4930 return;
4931 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004932
4933 // Collect the logical cameras without holding mStatusLock in updateStatus
4934 // as that can lead to a deadlock(b/162192331).
4935 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08004936 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08004937 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07004938 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004939 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004940 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004941
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004942 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004943 // Update torch status if it has a flash unit.
4944 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004945 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004946 if (getTorchStatusLocked(cameraId, &torchStatus) !=
4947 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004948 TorchModeStatus newTorchStatus =
4949 status == StatusInternal::PRESENT ?
4950 TorchModeStatus::AVAILABLE_OFF :
4951 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004952 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07004953 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004954 }
4955 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004956 }
4957
4958 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004959 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
4960 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08004961
Ruben Brunkcc776712015-02-17 20:18:47 -08004962 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07004963 bool isVendorListener = listener->isVendorListener();
4964 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
4965 listener->getListenerPid(), listener->getListenerUid()) ||
Shuzhen Wangb8259792021-05-27 09:27:06 -07004966 isVendorListener) {
4967 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004968 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08004969 continue;
4970 }
Austin Borgere8e2c422022-05-12 13:45:24 -07004971 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08004972 String16(cameraId));
Austin Borgere8e2c422022-05-12 13:45:24 -07004973 listener->handleBinderStatus(ret,
4974 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
4975 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
4976 ret.exceptionCode());
Ruben Brunkcc776712015-02-17 20:18:47 -08004977 }
4978 });
Igor Murashkincba2c162013-03-20 15:56:31 -07004979}
4980
Shuzhen Wang695044d2020-03-06 09:02:23 -08004981void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
4982 const String16& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004983 auto state = getCameraState(cameraId);
4984 if (state == nullptr) {
4985 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4986 cameraId.string());
4987 return;
4988 }
4989 if (open) {
4990 state->setClientPackage(String8(clientPackageName));
4991 } else {
4992 state->setClientPackage(String8::empty());
4993 }
4994
Shuzhen Wang695044d2020-03-06 09:02:23 -08004995 Mutex::Autolock lock(mStatusListenerLock);
4996
4997 for (const auto& it : mListenerList) {
4998 if (!it->isOpenCloseCallbackAllowed()) {
4999 continue;
5000 }
5001
5002 binder::Status ret;
5003 String16 cameraId64(cameraId);
5004 if (open) {
5005 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
5006 } else {
5007 ret = it->getListener()->onCameraClosed(cameraId64);
5008 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005009
5010 it->handleBinderStatus(ret,
5011 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5012 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005013 }
5014}
5015
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005016template<class Func>
5017void CameraService::CameraState::updateStatus(StatusInternal status,
5018 const String8& cameraId,
5019 std::initializer_list<StatusInternal> rejectSourceStates,
5020 Func onStatusUpdatedLocked) {
5021 Mutex::Autolock lock(mStatusLock);
5022 StatusInternal oldStatus = mStatus;
5023 mStatus = status;
5024
5025 if (oldStatus == status) {
5026 return;
5027 }
5028
5029 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
5030 cameraId.string(), oldStatus, status);
5031
5032 if (oldStatus == StatusInternal::NOT_PRESENT &&
5033 (status != StatusInternal::PRESENT &&
5034 status != StatusInternal::ENUMERATING)) {
5035
5036 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5037 __FUNCTION__);
5038 mStatus = oldStatus;
5039 return;
5040 }
5041
5042 /**
5043 * Sometimes we want to conditionally do a transition.
5044 * For example if a client disconnects, we want to go to PRESENT
5045 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5046 */
5047 for (auto& rejectStatus : rejectSourceStates) {
5048 if (oldStatus == rejectStatus) {
5049 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
5050 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
5051 mStatus = oldStatus;
5052 return;
5053 }
5054 }
5055
5056 onStatusUpdatedLocked(cameraId, status);
5057}
5058
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005059status_t CameraService::getTorchStatusLocked(
5060 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005061 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005062 if (!status) {
5063 return BAD_VALUE;
5064 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005065 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5066 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005067 // invalid camera ID or the camera doesn't have a flash unit
5068 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005069 }
5070
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005071 *status = mTorchStatusMap.valueAt(index);
5072 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005073}
5074
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005075status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005076 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005077 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5078 if (index == NAME_NOT_FOUND) {
5079 return BAD_VALUE;
5080 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005081 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005082
5083 return OK;
5084}
5085
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005086std::list<String16> CameraService::getLogicalCameras(
5087 const String8& physicalCameraId) {
5088 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005089 Mutex::Autolock lock(mCameraStatesLock);
5090 for (const auto& state : mCameraStates) {
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005091 if (state.second->containsPhysicalCamera(physicalCameraId.c_str())) {
5092 retList.emplace_back(String16(state.first));
Shuzhen Wang43858162020-01-10 13:42:15 -08005093 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005094 }
5095 return retList;
5096}
5097
5098void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
5099 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
5100 SystemCameraKind deviceKind) {
5101 // mStatusListenerLock is expected to be locked
5102 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005103 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005104 // Note: we check only the deviceKind of the physical camera id
5105 // since, logical camera ids and their physical camera ids are
5106 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005107 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5108 listener->getListenerPid(), listener->getListenerUid())) {
5109 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005110 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005111 continue;
5112 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005113 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005114 logicalCameraId, physicalCameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005115 listener->handleBinderStatus(ret,
5116 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5117 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5118 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005119 }
5120 }
5121}
5122
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005123
Svet Ganova453d0d2018-01-11 15:37:58 -08005124void CameraService::blockClientsForUid(uid_t uid) {
5125 const auto clients = mActiveClientManager.getAll();
5126 for (auto& current : clients) {
5127 if (current != nullptr) {
5128 const auto basicClient = current->getValue();
5129 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5130 basicClient->block();
5131 }
5132 }
5133 }
5134}
5135
Michael Grooverd1d435a2018-12-18 17:39:42 -08005136void CameraService::blockAllClients() {
5137 const auto clients = mActiveClientManager.getAll();
5138 for (auto& current : clients) {
5139 if (current != nullptr) {
5140 const auto basicClient = current->getValue();
5141 if (basicClient.get() != nullptr) {
5142 basicClient->block();
5143 }
5144 }
5145 }
5146}
5147
Svet Ganova453d0d2018-01-11 15:37:58 -08005148// NOTE: This is a remote API - make sure all args are validated
5149status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
5150 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
5151 return PERMISSION_DENIED;
5152 }
5153 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5154 return BAD_VALUE;
5155 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005156 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005157 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07005158 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005159 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07005160 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005161 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005162 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
5163 return handleSetRotateAndCrop(args);
5164 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
5165 return handleGetRotateAndCrop(out);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005166 } else if (args.size() >= 2 && args[0] == String16("set-autoframing")) {
5167 return handleSetAutoframing(args);
5168 } else if (args.size() >= 1 && args[0] == String16("get-autoframing")) {
5169 return handleGetAutoframing(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005170 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
5171 return handleSetImageDumpMask(args);
5172 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
5173 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005174 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
5175 return handleSetCameraMute(args);
Shuzhen Wang16610a62022-12-15 22:38:07 -08005176 } else if (args.size() >= 2 && args[0] == String16("set-stream-use-case-override")) {
5177 return handleSetStreamUseCaseOverrides(args);
5178 } else if (args.size() >= 1 && args[0] == String16("clear-stream-use-case-override")) {
5179 handleClearStreamUseCaseOverrides();
5180 return OK;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005181 } else if (args.size() >= 2 && args[0] == String16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005182 return handleWatchCommand(args, in, out);
Ravneetaeb20dc2022-03-30 05:33:03 +00005183 } else if (args.size() >= 2 && args[0] == String16("set-watchdog")) {
5184 return handleSetCameraServiceWatchdog(args);
Svet Ganova453d0d2018-01-11 15:37:58 -08005185 } else if (args.size() == 1 && args[0] == String16("help")) {
5186 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005187 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005188 }
5189 printHelp(err);
5190 return BAD_VALUE;
5191}
5192
5193status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07005194 String16 packageName = args[1];
5195
Svet Ganova453d0d2018-01-11 15:37:58 -08005196 bool active = false;
5197 if (args[2] == String16("active")) {
5198 active = true;
5199 } else if ((args[2] != String16("idle"))) {
5200 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
5201 return BAD_VALUE;
5202 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005203
5204 int userId = 0;
5205 if (args.size() >= 5 && args[3] == String16("--user")) {
5206 userId = atoi(String8(args[4]));
5207 }
5208
5209 uid_t uid;
5210 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5211 return BAD_VALUE;
5212 }
5213
5214 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005215 return NO_ERROR;
5216}
5217
5218status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07005219 String16 packageName = args[1];
5220
5221 int userId = 0;
5222 if (args.size() >= 4 && args[2] == String16("--user")) {
5223 userId = atoi(String8(args[3]));
5224 }
5225
5226 uid_t uid;
5227 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005228 return BAD_VALUE;
5229 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005230
5231 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005232 return NO_ERROR;
5233}
5234
5235status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07005236 String16 packageName = args[1];
5237
5238 int userId = 0;
5239 if (args.size() >= 4 && args[2] == String16("--user")) {
5240 userId = atoi(String8(args[3]));
5241 }
5242
5243 uid_t uid;
5244 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005245 return BAD_VALUE;
5246 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005247
5248 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005249 return dprintf(out, "active\n");
5250 } else {
5251 return dprintf(out, "idle\n");
5252 }
5253}
5254
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005255status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
5256 int rotateValue = atoi(String8(args[1]));
5257 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
5258 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
5259 Mutex::Autolock lock(mServiceLock);
5260
5261 mOverrideRotateAndCropMode = rotateValue;
5262
5263 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
5264
5265 const auto clients = mActiveClientManager.getAll();
5266 for (auto& current : clients) {
5267 if (current != nullptr) {
5268 const auto basicClient = current->getValue();
5269 if (basicClient.get() != nullptr) {
5270 basicClient->setRotateAndCropOverride(rotateValue);
5271 }
5272 }
5273 }
5274
5275 return OK;
5276}
5277
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005278status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
5279 char* end;
5280 int autoframingValue = (int) strtol(String8(args[1]), &end, /*base=*/10);
5281 if ((*end != '\0') ||
5282 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
5283 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
5284 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
5285 return BAD_VALUE;
5286 }
5287
5288 Mutex::Autolock lock(mServiceLock);
5289 mOverrideAutoframingMode = autoframingValue;
5290
5291 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
5292
5293 const auto clients = mActiveClientManager.getAll();
5294 for (auto& current : clients) {
5295 if (current != nullptr) {
5296 const auto basicClient = current->getValue();
5297 if (basicClient.get() != nullptr) {
5298 basicClient->setAutoframingOverride(autoframingValue);
5299 }
5300 }
5301 }
5302
5303 return OK;
5304}
5305
Ravneetaeb20dc2022-03-30 05:33:03 +00005306status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
5307 int enableWatchdog = atoi(String8(args[1]));
5308
5309 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
5310
5311 Mutex::Autolock lock(mServiceLock);
5312
5313 mCameraServiceWatchdogEnabled = enableWatchdog;
5314
5315 const auto clients = mActiveClientManager.getAll();
5316 for (auto& current : clients) {
5317 if (current != nullptr) {
5318 const auto basicClient = current->getValue();
5319 if (basicClient.get() != nullptr) {
5320 basicClient->setCameraServiceWatchdog(enableWatchdog);
5321 }
5322 }
5323 }
5324
5325 return OK;
5326}
5327
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005328status_t CameraService::handleGetRotateAndCrop(int out) {
5329 Mutex::Autolock lock(mServiceLock);
5330
5331 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
5332}
5333
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005334status_t CameraService::handleGetAutoframing(int out) {
5335 Mutex::Autolock lock(mServiceLock);
5336
5337 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
5338}
5339
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005340status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
5341 char *endPtr;
5342 errno = 0;
5343 String8 maskString8 = String8(args[1]);
5344 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
5345
5346 if (errno != 0) return BAD_VALUE;
5347 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
5348 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
5349
5350 Mutex::Autolock lock(mServiceLock);
5351
5352 mImageDumpMask = maskValue;
5353
5354 return OK;
5355}
5356
5357status_t CameraService::handleGetImageDumpMask(int out) {
5358 Mutex::Autolock lock(mServiceLock);
5359
5360 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
5361}
5362
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005363status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
5364 int muteValue = strtol(String8(args[1]), nullptr, 10);
5365 if (errno != 0) return BAD_VALUE;
5366
5367 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
5368 Mutex::Autolock lock(mServiceLock);
5369
5370 mOverrideCameraMuteMode = (muteValue == 1);
5371
5372 const auto clients = mActiveClientManager.getAll();
5373 for (auto& current : clients) {
5374 if (current != nullptr) {
5375 const auto basicClient = current->getValue();
5376 if (basicClient.get() != nullptr) {
5377 if (basicClient->supportsCameraMute()) {
5378 basicClient->setCameraMute(mOverrideCameraMuteMode);
5379 }
5380 }
5381 }
5382 }
5383
5384 return OK;
5385}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005386
Shuzhen Wang16610a62022-12-15 22:38:07 -08005387status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
5388 std::vector<int64_t> useCasesOverride;
5389 for (size_t i = 1; i < args.size(); i++) {
5390 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
5391 String8 arg8 = String8(args[i]);
5392 if (arg8 == "DEFAULT") {
5393 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
5394 } else if (arg8 == "PREVIEW") {
5395 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
5396 } else if (arg8 == "STILL_CAPTURE") {
5397 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
5398 } else if (arg8 == "VIDEO_RECORD") {
5399 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
5400 } else if (arg8 == "PREVIEW_VIDEO_STILL") {
5401 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
5402 } else if (arg8 == "VIDEO_CALL") {
5403 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
5404 } else if (arg8 == "CROPPED_RAW") {
5405 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
5406 } else {
5407 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg8.c_str());
5408 return BAD_VALUE;
5409 }
5410 useCasesOverride.push_back(useCase);
5411 }
5412
5413 Mutex::Autolock lock(mServiceLock);
5414 mStreamUseCaseOverrides = std::move(useCasesOverride);
5415
5416 return OK;
5417}
5418
5419void CameraService::handleClearStreamUseCaseOverrides() {
5420 Mutex::Autolock lock(mServiceLock);
5421 mStreamUseCaseOverrides.clear();
5422}
5423
Avichal Rakesh84147132021-11-11 17:47:11 -08005424status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005425 if (args.size() >= 3 && args[1] == String16("start")) {
5426 return startWatchingTags(args, outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005427 } else if (args.size() == 2 && args[1] == String16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005428 return stopWatchingTags(outFd);
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005429 } else if (args.size() == 2 && args[1] == String16("dump")) {
5430 return printWatchedTags(outFd);
5431 } else if (args.size() >= 2 && args[1] == String16("live")) {
5432 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005433 } else if (args.size() == 2 && args[1] == String16("clear")) {
5434 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005435 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005436 dprintf(outFd, "Camera service watch commands:\n"
5437 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
5438 " starts watching the provided tags for clients with provided package\n"
5439 " recognizes tag shorthands like '3a'\n"
5440 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005441 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005442 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005443 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005444 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08005445 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005446 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005447 return BAD_VALUE;
5448}
5449
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005450status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
5451 Mutex::Autolock lock(mLogLock);
5452 size_t tagsIdx; // index of '-m'
5453 String16 tags("");
5454 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != String16("-m"); tagsIdx++);
5455 if (tagsIdx < args.size() - 1) {
5456 tags = args[tagsIdx + 1];
5457 } else {
5458 dprintf(outFd, "No tags provided.\n");
5459 return BAD_VALUE;
5460 }
5461
5462 size_t clientsIdx; // index of '-c'
5463 String16 clients = kWatchAllClientsFlag; // watch all clients if no clients are provided
5464 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != String16("-c");
5465 clientsIdx++);
5466 if (clientsIdx < args.size() - 1) {
5467 clients = args[clientsIdx + 1];
5468 }
5469 parseClientsToWatchLocked(String8(clients));
5470
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005471 // track tags to initialize future clients with the monitoring information
5472 mMonitorTags = String8(tags);
5473
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005474 bool serviceLock = tryLock(mServiceLock);
5475 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005476 auto cameraClients = mActiveClientManager.getAll();
5477 for (const auto &clientDescriptor: cameraClients) {
5478 if (clientDescriptor == nullptr) { continue; }
5479 sp<BasicClient> client = clientDescriptor->getValue();
5480 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005481
5482 if (isClientWatchedLocked(client.get())) {
5483 client->startWatchingTags(mMonitorTags, outFd);
5484 numWatchedClients++;
5485 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005486 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005487 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
5488
5489 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005490 return OK;
5491}
5492
5493status_t CameraService::stopWatchingTags(int outFd) {
5494 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005495 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005496 mMonitorTags = String8::empty();
5497
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005498 mWatchedClientPackages.clear();
5499 mWatchedClientsDumpCache.clear();
5500
5501 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005502 auto cameraClients = mActiveClientManager.getAll();
5503 for (const auto &clientDescriptor : cameraClients) {
5504 if (clientDescriptor == nullptr) { continue; }
5505 sp<BasicClient> client = clientDescriptor->getValue();
5506 if (client.get() == nullptr) { continue; }
5507 client->stopWatchingTags(outFd);
5508 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005509 dprintf(outFd, "Stopped watching all clients.\n");
5510 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005511 return OK;
5512}
5513
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005514status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
5515 Mutex::Autolock lock(mLogLock);
5516 size_t clearedSize = mWatchedClientsDumpCache.size();
5517 mWatchedClientsDumpCache.clear();
5518 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
5519 return OK;
5520}
5521
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005522status_t CameraService::printWatchedTags(int outFd) {
5523 Mutex::Autolock logLock(mLogLock);
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08005524 std::set<String16> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005525
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005526 bool printedSomething = false; // tracks if any monitoring information was printed
5527 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005528
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005529 bool serviceLock = tryLock(mServiceLock);
5530 // get all watched clients that are currently connected
5531 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
5532 if (clientDescriptor == nullptr) { continue; }
5533
5534 sp<BasicClient> client = clientDescriptor->getValue();
5535 if (client.get() == nullptr) { continue; }
5536 if (!isClientWatchedLocked(client.get())) { continue; }
5537
5538 std::vector<std::string> dumpVector;
5539 client->dumpWatchedEventsToVector(dumpVector);
5540
5541 size_t printIdx = dumpVector.size();
5542 if (printIdx == 0) {
5543 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005544 }
5545
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005546 // Print tag dumps for active client
5547 const String8 &cameraId = clientDescriptor->getKey();
5548 String8 packageName8 = String8(client->getPackageName());
5549 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
5550 dprintf(outFd, "Client: %s (active)\n", printablePackageName);
5551 while(printIdx > 0) {
5552 printIdx--;
5553 dprintf(outFd, "%s:%s %s", cameraId.string(), printablePackageName,
5554 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005555 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005556 dprintf(outFd, "\n");
5557 packageName8.unlockBuffer();
5558 printedSomething = true;
5559
5560 connectedMonitoredClients.emplace(client->getPackageName());
5561 }
5562 if (serviceLock) { mServiceLock.unlock(); }
5563
5564 // Print entries in mWatchedClientsDumpCache for clients that are not connected
5565 for (const auto &kv: mWatchedClientsDumpCache) {
5566 const String16 &package = kv.first;
5567 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
5568 continue;
5569 }
5570
5571 dprintf(outFd, "Client: %s (cached)\n", String8(package).string());
5572 dprintf(outFd, "%s\n", kv.second.c_str());
5573 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005574 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005575
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005576 if (!printedSomething) {
5577 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005578 }
5579
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005580 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005581}
5582
Avichal Rakesh84147132021-11-11 17:47:11 -08005583// Print all events in vector `events' that came after lastPrintedEvent
5584void printNewWatchedEvents(int outFd,
5585 const char *cameraId,
5586 const String16 &packageName,
5587 const std::vector<std::string> &events,
5588 const std::string &lastPrintedEvent) {
5589 if (events.empty()) { return; }
5590
5591 // index of lastPrintedEvent in events.
5592 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
5593 size_t lastPrintedIdx;
5594 for (lastPrintedIdx = 0;
5595 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
5596 lastPrintedIdx++);
5597
5598 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
5599
5600 String8 packageName8(packageName);
5601 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
5602
5603 // print events in chronological order (latest event last)
5604 size_t idxToPrint = lastPrintedIdx;
5605 do {
5606 idxToPrint--;
5607 dprintf(outFd, "%s:%s %s", cameraId, printablePackageName, events[idxToPrint].c_str());
5608 } while (idxToPrint != 0);
5609
5610 packageName8.unlockBuffer();
5611}
5612
5613// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
5614// command should be interrupted if the user presses the return key, or if user loses any way to
5615// signal interrupt.
5616// If timeoutMs == 0, this function will always return false
5617bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
5618 struct timeval startTime;
5619 int startTimeError = gettimeofday(&startTime, nullptr);
5620 if (startTimeError) {
5621 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5622 return true;
5623 }
5624
5625 const nfds_t numFds = 1;
5626 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
5627
5628 struct timeval currTime;
5629 char buffer[2];
5630 while(true) {
5631 int currTimeError = gettimeofday(&currTime, nullptr);
5632 if (currTimeError) {
5633 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5634 return true;
5635 }
5636
5637 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
5638 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
5639 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
5640
5641 if (remainingTimeMs <= 0) {
5642 // No user interrupt within timeoutMs, don't interrupt watch command
5643 return false;
5644 }
5645
5646 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
5647 if (numFdsUpdated < 0) {
5648 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5649 return true;
5650 }
5651
5652 if (numFdsUpdated == 0) {
5653 // No user input within timeoutMs, don't interrupt watch command
5654 return false;
5655 }
5656
5657 if (!(pollFd.revents & POLLIN)) {
5658 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5659 return true;
5660 }
5661
5662 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
5663 if (sizeRead < 0) {
5664 dprintf(outFd, "Error reading user input. Exiting.\n");
5665 return true;
5666 }
5667
5668 if (sizeRead == 0) {
5669 // Reached end of input fd (can happen if input is piped)
5670 // User has no way to signal an interrupt, so interrupt here
5671 return true;
5672 }
5673
5674 if (buffer[0] == '\n') {
5675 // User pressed return, interrupt watch command.
5676 return true;
5677 }
5678 }
5679}
5680
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005681status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
5682 int inFd, int outFd) {
5683 // Figure out refresh interval, if present in args
5684 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005685 if (args.size() > 2) {
5686 size_t intervalIdx; // index of '-n'
5687 for (intervalIdx = 2; intervalIdx < args.size() && String16("-n") != args[intervalIdx];
5688 intervalIdx++);
5689
5690 size_t intervalValIdx = intervalIdx + 1;
5691 if (intervalValIdx < args.size()) {
5692 refreshTimeoutMs = strtol(String8(args[intervalValIdx].string()), nullptr, 10);
5693 if (errno) { return BAD_VALUE; }
5694 }
5695 }
5696
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005697 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
5698 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005699
Avichal Rakesh84147132021-11-11 17:47:11 -08005700 dprintf(outFd, "Press return to exit...\n\n");
Avichal Rakesha14d9832021-11-11 01:41:55 -08005701 std::map<String16, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005702
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005703 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005704 bool serviceLock = tryLock(mServiceLock);
5705 auto cameraClients = mActiveClientManager.getAll();
5706 if (serviceLock) { mServiceLock.unlock(); }
5707
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005708 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005709 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005710 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005711
5712 sp<BasicClient> client = clientDescriptor->getValue();
5713 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005714 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005715
Avichal Rakesha14d9832021-11-11 01:41:55 -08005716 const String16 &packageName = client->getPackageName();
5717 // This also initializes the map entries with an empty string
5718 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
5719
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005720 std::vector<std::string> latestEvents;
5721 client->dumpWatchedEventsToVector(latestEvents);
5722
5723 if (!latestEvents.empty()) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005724 String8 cameraId = clientDescriptor->getKey();
5725 const char *printableCameraId = cameraId.lockBuffer(cameraId.size());
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005726 printNewWatchedEvents(outFd,
Avichal Rakesha14d9832021-11-11 01:41:55 -08005727 printableCameraId,
5728 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005729 latestEvents,
5730 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08005731 packageNameToLastEvent[packageName] = latestEvents[0];
5732 cameraId.unlockBuffer();
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005733 }
5734 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005735 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005736 break;
5737 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005738 }
5739 return OK;
5740}
5741
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005742void CameraService::parseClientsToWatchLocked(String8 clients) {
5743 mWatchedClientPackages.clear();
5744
5745 const char *allSentinel = String8(kWatchAllClientsFlag).string();
5746
5747 char *tokenized = clients.lockBuffer(clients.size());
5748 char *savePtr;
5749 char *nextClient = strtok_r(tokenized, ",", &savePtr);
5750
5751 while (nextClient != nullptr) {
5752 if (strcmp(nextClient, allSentinel) == 0) {
5753 // Don't need to track any other package if 'all' is present
5754 mWatchedClientPackages.clear();
5755 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
5756 break;
5757 }
5758
5759 // track package names
5760 mWatchedClientPackages.emplace(nextClient);
5761 nextClient = strtok_r(nullptr, ",", &savePtr);
5762 }
5763 clients.unlockBuffer();
5764}
5765
Svet Ganova453d0d2018-01-11 15:37:58 -08005766status_t CameraService::printHelp(int out) {
5767 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07005768 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
5769 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
5770 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005771 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
5772 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
5773 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005774 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
5775 " Valid values 0=false, 1=true, 2=auto\n"
5776 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005777 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
5778 " Valid values 0=OFF, 1=ON for JPEG\n"
5779 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005780 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08005781 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
5782 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
5783 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
5784 " on. In case the number of usecases is smaller than the number of streams, the\n"
5785 " last use case is assigned to all the remaining streams. In case of multiple\n"
5786 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
5787 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
5788 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
5789 " clear-stream-use-case-override clear the stream use case override\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005790 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08005791 " help print this message\n");
5792}
5793
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005794bool CameraService::isClientWatched(const BasicClient *client) {
5795 Mutex::Autolock lock(mLogLock);
5796 return isClientWatchedLocked(client);
5797}
5798
5799bool CameraService::isClientWatchedLocked(const BasicClient *client) {
5800 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
5801 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
5802}
5803
Yin-Chia Yehdba03232019-08-19 15:54:28 -07005804int32_t CameraService::updateAudioRestriction() {
5805 Mutex::Autolock lock(mServiceLock);
5806 return updateAudioRestrictionLocked();
5807}
5808
5809int32_t CameraService::updateAudioRestrictionLocked() {
5810 int32_t mode = 0;
5811 // iterate through all active client
5812 for (const auto& i : mActiveClientManager.getAll()) {
5813 const auto clientSp = i->getValue();
5814 mode |= clientSp->getAudioRestriction();
5815 }
5816
5817 bool modeChanged = (mAudioRestriction != mode);
5818 mAudioRestriction = mode;
5819 if (modeChanged) {
5820 mAppOps.setCameraAudioRestriction(mode);
5821 }
5822 return mode;
5823}
5824
Cliff Wu646bd612021-11-23 23:21:29 +08005825status_t CameraService::checkIfInjectionCameraIsPresent(const String8& externalCamId,
5826 sp<BasicClient> clientSp) {
5827 std::unique_ptr<AutoConditionLock> lock =
5828 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
5829 status_t res = NO_ERROR;
5830 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
5831 ALOGW("Device %s is not usable!", externalCamId.string());
5832 mInjectionStatusListener->notifyInjectionError(
5833 externalCamId, UNKNOWN_TRANSACTION);
5834 clientSp->notifyError(
5835 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
5836 CaptureResultExtras());
5837
5838 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
5839 // other clients from connecting in mServiceLockWrapper if held
5840 mServiceLock.unlock();
5841
5842 // Clear caller identity temporarily so client disconnect PID checks work correctly
5843 int64_t token = CameraThreadState::clearCallingIdentity();
5844 clientSp->disconnect();
5845 CameraThreadState::restoreCallingIdentity(token);
5846
5847 // Reacquire mServiceLock
5848 mServiceLock.lock();
5849 }
5850
5851 return res;
5852}
5853
Cliff Wud3a05312021-04-26 23:07:31 +08005854void CameraService::clearInjectionParameters() {
5855 {
5856 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08005857 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08005858 mInjectionInternalCamId = "";
5859 }
5860 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08005861 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08005862}
5863
Mathias Agopian65ab4712010-07-14 17:59:35 -07005864}; // namespace android