blob: ec8d6b9b5728f6df1240ed5182d4dfc8d16c1841 [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>
Svet Ganova453d0d2018-01-11 15:37:58 -080040#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080041#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043#include <binder/MemoryBase.h>
44#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080045#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080046#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080047#include <binderthreadstate/CallerUtils.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070049#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080050#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080051#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070052#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070053#include "hidl/HidlCameraService.h"
54#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080055#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070056#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080058#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070059#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070060#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000061#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070062#include <utils/Errors.h>
63#include <utils/Log.h>
64#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070065#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080066#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080067#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080068#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080069#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070070#include <system/camera_metadata.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080071
Ruben Brunkb2119af2014-05-09 19:57:56 -070072#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070073
74#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070075#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070076#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070077#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000078#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070079#include "utils/CameraThreadState.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070080#include "utils/CameraServiceProxyWrapper.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070081
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080082namespace {
83 const char* kPermissionServiceName = "permission";
84}; // namespace anonymous
85
Mathias Agopian65ab4712010-07-14 17:59:35 -070086namespace android {
87
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070088using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080089using binder::Status;
Austin Borgerea931242021-12-13 23:10:41 +000090using namespace camera3;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070091using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -070092using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080093using hardware::ICamera;
94using hardware::ICameraClient;
95using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +080096using hardware::camera2::ICameraInjectionCallback;
97using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080098using hardware::camera2::utils::CameraIdAndSessionConfiguration;
99using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800100
Mathias Agopian65ab4712010-07-14 17:59:35 -0700101// ----------------------------------------------------------------------------
102// Logging support -- this is for debugging only
103// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700104volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700105
Steve Blockb8a80522011-12-20 16:23:08 +0000106#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
107#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108
109static void setLogLevel(int level) {
110 android_atomic_write(level, &gLogLevel);
111}
112
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800113// Convenience methods for constructing binder::Status objects for error returns
114
115#define STATUS_ERROR(errorCode, errorString) \
116 binder::Status::fromServiceSpecificError(errorCode, \
117 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
118
119#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
120 binder::Status::fromServiceSpecificError(errorCode, \
121 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
122 __VA_ARGS__))
123
Mathias Agopian65ab4712010-07-14 17:59:35 -0700124// ----------------------------------------------------------------------------
125
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700126static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800127static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700128static const String16 sCameraPermission("android.permission.CAMERA");
129static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
130static const String16
131 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Shuzhen Wang695044d2020-03-06 09:02:23 -0800132static const String16 sCameraOpenCloseListenerPermission(
133 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Cliff Wud8cae102021-03-11 01:37:42 +0800134static const String16
135 sCameraInjectExternalCameraPermission("android.permission.CAMERA_INJECT_EXTERNAL_CAMERA");
Rucha Katakwardf223072021-06-15 10:21:00 -0700136const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800137static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
138static constexpr int32_t kSystemNativeClientState =
139 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700140
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800141const String8 CameraService::kOfflineDevice("offline-");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -0700142const String16 CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700143
Rucha Katakward9ea6452021-05-06 11:57:16 -0700144// Set to keep track of logged service error events.
145static std::set<String8> sServiceErrorEventSet;
146
Austin Borger74fca042022-05-23 12:41:21 -0700147CameraService::CameraService(
148 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper) :
149 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
150 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800151 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800152 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700153 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700154 mSoundRef(0), mInitialized(false),
155 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000156 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800157 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700158 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
159 if (mMemFd == -1) {
160 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
161 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700162}
163
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800164// The word 'System' here does not refer to clients only on the system
165// partition. They just need to have a android system uid.
166static bool doesClientHaveSystemUid() {
167 return (CameraThreadState::getCallingUid() < AID_APP_START);
168}
169
Iliyan Malchev8951a972011-04-14 16:55:59 -0700170void CameraService::onFirstRef()
171{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700172
Ruben Brunkcc776712015-02-17 20:18:47 -0800173 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800174
Iliyan Malchev8951a972011-04-14 16:55:59 -0700175 BnCameraService::onFirstRef();
176
Ruben Brunk99e69712015-05-26 17:25:07 -0700177 // Update battery life tracking if service is restarting
178 BatteryNotifier& notifier(BatteryNotifier::getInstance());
179 notifier.noteResetCamera();
180 notifier.noteResetFlashlight();
181
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800182 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800183
Emilian Peevf53f66e2017-04-11 14:29:43 +0100184 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800185 if (res == OK) {
186 mInitialized = true;
187 }
188
Svet Ganova453d0d2018-01-11 15:37:58 -0800189 mUidPolicy = new UidPolicy(this);
190 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800191 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
192 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800193 mInjectionStatusListener = new InjectionStatusListener(this);
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700194 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700195 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
196 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000197 // Deprecated, so it will fail to register on newer devices
198 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700199 __FUNCTION__);
200 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700201
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700202 if (!AidlCameraService::registerService(this)) {
203 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
204 }
205
Shuzhen Wang24b44152019-09-20 10:38:11 -0700206 // This needs to be last call in this function, so that it's as close to
207 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700208 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700209 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800210}
211
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800212status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800213 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100214
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800215 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000216 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800217 {
218 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800219
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800220 if (nullptr == mCameraProviderManager.get()) {
221 mCameraProviderManager = new CameraProviderManager();
222 res = mCameraProviderManager->initialize(this);
223 if (res != OK) {
224 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
225 __FUNCTION__, strerror(-res), res);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700226 logServiceError(String8::format("Unable to initialize camera provider manager"),
227 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800228 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100229 }
230 }
231
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800232
233 // Setup vendor tags before we call get_camera_info the first time
234 // because HAL might need to setup static vendor keys in get_camera_info
235 // TODO: maybe put this into CameraProviderManager::initialize()?
236 mCameraProviderManager->setUpVendorTags();
237
238 if (nullptr == mFlashlight.get()) {
239 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700240 }
241
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800242 res = mFlashlight->findFlashUnits();
243 if (res != OK) {
244 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
245 }
246
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000247 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800248 }
249
250
251 for (auto& cameraId : deviceIds) {
252 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800253 if (getCameraState(id8) == nullptr) {
254 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
255 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000256 if (unavailPhysicalIds.count(cameraId) > 0) {
257 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
258 String8 physicalId8 = String8(physicalId.c_str());
259 onDeviceStatusChanged(id8, physicalId8, CameraDeviceStatus::NOT_PRESENT);
260 }
261 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800262 }
263
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700264 // Derive primary rear/front cameras, and filter their charactierstics.
265 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700266 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700267 // Assume internal cameras are advertised from the same
268 // provider. If multiple providers are registered at different time,
269 // and each provider contains multiple internal color cameras, the current
270 // logic may filter the characteristics of more than one front/rear color
271 // cameras.
272 Mutex::Autolock l(mServiceLock);
273 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700274 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700275
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800276 return OK;
277}
278
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700279void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status,
280 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800281 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800282 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700283 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
284 i->getListenerUid())) {
285 ALOGV("Skipping torch callback for system-only camera device %s",
286 cameraId.c_str());
287 continue;
288 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700289 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
290 String16{cameraId});
291 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
292 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800293 }
294}
295
Mathias Agopian65ab4712010-07-14 17:59:35 -0700296CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800297 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800298 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800299 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800300 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700301}
302
Emilian Peevaee727d2017-05-04 16:35:48 +0100303void CameraService::onNewProviderRegistered() {
304 enumerateProviders();
305}
306
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700307void CameraService::filterAPI1SystemCameraLocked(
308 const std::vector<std::string> &normalDeviceIds) {
309 mNormalDeviceIdsWithoutSystemCamera.clear();
310 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700311 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
312 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
313 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
314 continue;
315 }
316 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700317 // All system camera ids will necessarily come after public camera
318 // device ids as per the HAL interface contract.
319 break;
320 }
321 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
322 }
323 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
324 mNormalDeviceIdsWithoutSystemCamera.size());
325}
326
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700327status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
328 auto state = getCameraState(cameraId);
329 if (state != nullptr) {
330 *kind = state->getSystemCameraKind();
331 return OK;
332 }
333 // Hidden physical camera ids won't have CameraState
334 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
335}
336
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800337void CameraService::updateCameraNumAndIds() {
338 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700339 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
340 // Excludes hidden secure cameras
341 mNumberOfCameras =
342 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
343 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800344 mNormalDeviceIds =
345 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700346 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800347}
348
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700349void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700350 // To claim to be S Performance primary cameras, the cameras must be
351 // backward compatible. So performance class primary camera Ids must be API1
352 // compatible.
353 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
354 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
355 int facing = -1;
356 int orientation = 0;
357 String8 cameraId8(cameraId.c_str());
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800358 int portraitRotation;
359 getDeviceVersion(cameraId8, /*overrideToPortrait*/false, /*out*/&portraitRotation,
360 /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700361 if (facing == -1) {
362 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
363 return;
364 }
365
366 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
367 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700368 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
369 if (res == OK) {
370 mPerfClassPrimaryCameraIds.insert(cameraId);
371 } else {
372 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
373 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
374 break;
375 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700376
377 if (facing == hardware::CAMERA_FACING_BACK) {
378 firstRearCameraSeen = true;
379 }
380 if (facing == hardware::CAMERA_FACING_FRONT) {
381 firstFrontCameraSeen = true;
382 }
383 }
384
385 if (firstRearCameraSeen && firstFrontCameraSeen) {
386 break;
387 }
388 }
389}
390
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100391void CameraService::addStates(const String8 id) {
392 std::string cameraId(id.c_str());
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700393 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100394 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
395 if (res != OK) {
396 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
397 return;
398 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000399 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700400 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
401 if (res != OK) {
402 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
403 return;
404 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000405 std::vector<std::string> physicalCameraIds;
406 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100407 std::set<String8> conflicting;
408 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
409 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
410 }
411
412 {
413 Mutex::Autolock lock(mCameraStatesLock);
414 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000415 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100416 }
417
418 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100419 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100420 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800421
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700422 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100423 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800424
425 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100426 logDeviceAdded(id, "Device added");
427}
428
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100429void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800430 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100431 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100432 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100433 mTorchStatusMap.removeItem(id);
434 }
435
436 {
437 Mutex::Autolock lock(mCameraStatesLock);
438 mCameraStates.erase(id);
439 }
440}
441
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800442void CameraService::onDeviceStatusChanged(const String8& id,
443 CameraDeviceStatus newHalStatus) {
444 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
445 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700446
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800447 StatusInternal newStatus = mapToInternal(newHalStatus);
448
Ruben Brunkcc776712015-02-17 20:18:47 -0800449 std::shared_ptr<CameraState> state = getCameraState(id);
450
451 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700452 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100453 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700454 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100455
456 // First add as absent to make sure clients are notified below
457 addStates(id);
458
459 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700460 } else {
461 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
462 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700463 return;
464 }
465
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800466 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800467
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800468 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800469 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700470 return;
471 }
472
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800473 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700474 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
475 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800476
477 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
478 // to this device until the status changes
479 updateStatus(StatusInternal::NOT_PRESENT, id);
480
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800481 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700482 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800483 // Don't do this in updateStatus to avoid deadlock over mServiceLock
484 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700485
Ruben Brunkcc776712015-02-17 20:18:47 -0800486 // Remove cached shim parameters
487 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700488
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800489 // Remove online as well as offline client from the list of active clients,
490 // if they are present
491 clientToDisconnectOnline = removeClientLocked(id);
492 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700493 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800494
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800495 disconnectClient(id, clientToDisconnectOnline);
496 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700497
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100498 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800499 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800500 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700501 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
502 newStatus));
503 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800504 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700505 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800506}
Igor Murashkincba2c162013-03-20 15:56:31 -0700507
Shuzhen Wang43858162020-01-10 13:42:15 -0800508void CameraService::onDeviceStatusChanged(const String8& id,
509 const String8& physicalId,
510 CameraDeviceStatus newHalStatus) {
511 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
512 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
513
514 StatusInternal newStatus = mapToInternal(newHalStatus);
515
516 std::shared_ptr<CameraState> state = getCameraState(id);
517
518 if (state == nullptr) {
519 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000520 __FUNCTION__, physicalId.string(), id.string());
Shuzhen Wang43858162020-01-10 13:42:15 -0800521 return;
522 }
523
524 StatusInternal logicalCameraStatus = state->getStatus();
525 if (logicalCameraStatus != StatusInternal::PRESENT &&
526 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
527 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
528 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
529 return;
530 }
531
532 bool updated = false;
533 if (newStatus == StatusInternal::PRESENT) {
534 updated = state->removeUnavailablePhysicalId(physicalId);
535 } else {
536 updated = state->addUnavailablePhysicalId(physicalId);
537 }
538
539 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800540 String8 idCombo = id + " : " + physicalId;
541 if (newStatus == StatusInternal::PRESENT) {
542 logDeviceAdded(idCombo,
543 String8::format("Device status changed to %d", newStatus));
544 } else {
545 logDeviceRemoved(idCombo,
546 String8::format("Device status changed to %d", newStatus));
547 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700548 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
549 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
550 if (getSystemCameraKind(id, &deviceKind) != OK) {
551 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
552 return;
553 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800554 String16 id16(id), physicalId16(physicalId);
555 Mutex::Autolock lock(mStatusListenerLock);
556 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700557 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
558 listener->getListenerPid(), listener->getListenerUid())) {
559 ALOGV("Skipping discovery callback for system-only camera device %s",
560 id.c_str());
561 continue;
562 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700563 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
564 mapToInterface(newStatus), id16, physicalId16);
565 listener->handleBinderStatus(ret,
566 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
567 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
568 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800569 }
570 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700571}
572
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800573void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
574 if (clientToDisconnect.get() != nullptr) {
575 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
576 __FUNCTION__, id.string());
577 // Notify the client of disconnection
578 clientToDisconnect->notifyError(
579 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
580 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800581 clientToDisconnect->disconnect();
582 }
583}
584
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800585void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800586 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700587 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
588 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
589 if (res != OK) {
590 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
591 cameraId.string());
592 return;
593 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800594 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700595 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800596}
597
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700598
599void CameraService::onTorchStatusChanged(const String8& cameraId,
600 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
601 Mutex::Autolock al(mTorchStatusMutex);
602 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
603}
604
Rucha Katakwar38284522021-11-10 11:25:21 -0800605void CameraService::broadcastTorchStrengthLevel(const String8& cameraId,
606 int32_t newStrengthLevel) {
607 Mutex::Autolock lock(mStatusListenerLock);
608 for (auto& i : mListenerList) {
Austin Borgere8e2c422022-05-12 13:45:24 -0700609 auto ret = i->getListener()->onTorchStrengthLevelChanged(String16{cameraId},
Rucha Katakwar38284522021-11-10 11:25:21 -0800610 newStrengthLevel);
Austin Borgere8e2c422022-05-12 13:45:24 -0700611 i->handleBinderStatus(ret,
612 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
613 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800614 }
615}
616
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800617void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700618 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800619 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
620 __FUNCTION__, cameraId.string(), newStatus);
621
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800622 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800623 status_t res = getTorchStatusLocked(cameraId, &status);
624 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700625 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
626 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800627 return;
628 }
629 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800630 return;
631 }
632
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800633 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800634 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800635 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
636 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800637 return;
638 }
639
Ruben Brunkcc776712015-02-17 20:18:47 -0800640 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700641 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700642 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700643 auto iter = mTorchUidMap.find(cameraId);
644 if (iter != mTorchUidMap.end()) {
645 int oldUid = iter->second.second;
646 int newUid = iter->second.first;
647 BatteryNotifier& notifier(BatteryNotifier::getInstance());
648 if (oldUid != newUid) {
649 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800650 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700651 notifier.noteFlashlightOff(cameraId, oldUid);
652 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800653 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700654 notifier.noteFlashlightOn(cameraId, newUid);
655 }
656 iter->second.second = newUid;
657 } else {
658 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800659 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700660 notifier.noteFlashlightOn(cameraId, oldUid);
661 } else {
662 notifier.noteFlashlightOff(cameraId, oldUid);
663 }
664 }
665 }
666 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700667 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800668}
669
Jayant Chowdharyc3198c32021-07-28 20:59:14 +0000670static bool hasPermissionsForSystemCamera(int callingPid, int callingUid,
671 bool logPermissionFailure = false) {
672 return checkPermission(sSystemCameraPermission, callingPid, callingUid,
673 logPermissionFailure) &&
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700674 checkPermission(sCameraPermission, callingPid, callingUid);
675}
676
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800677Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700678 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100679 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700680 bool hasSystemCameraPermissions =
681 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
682 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700683 switch (type) {
684 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700685 if (hasSystemCameraPermissions) {
686 *numCameras = static_cast<int>(mNormalDeviceIds.size());
687 } else {
688 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
689 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800690 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700691 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700692 if (hasSystemCameraPermissions) {
693 *numCameras = mNumberOfCameras;
694 } else {
695 *numCameras = mNumberOfCamerasWithoutSystemCamera;
696 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800697 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700698 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800699 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700700 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800701 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
702 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700703 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800704 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700705}
706
Austin Borger18b30a72022-10-27 12:20:29 -0700707Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800708 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700709 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100710 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700711 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
712 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
713 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
714 "characteristics for system only device %s: ", cameraIdStr.c_str());
715 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100716
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800717 if (!mInitialized) {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700718 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800719 return STATUS_ERROR(ERROR_DISCONNECTED,
720 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700721 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700722 bool hasSystemCameraPermissions =
723 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
724 CameraThreadState::getCallingUid());
725 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
726 if (hasSystemCameraPermissions) {
727 cameraIdBound = mNumberOfCameras;
728 }
729 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800730 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
731 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700732 }
733
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800734 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -0700735 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800736 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borger18b30a72022-10-27 12:20:29 -0700737 cameraIdStr.c_str(), overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100738 if (err != OK) {
739 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
740 "Error retrieving camera info from device %d: %s (%d)", cameraId,
741 strerror(-err), err);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700742 logServiceError(String8::format("Error retrieving camera info from device %d",cameraId),
743 ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -0800744 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100745
Ruben Brunkcc776712015-02-17 20:18:47 -0800746 return ret;
747}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700748
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800749std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700750 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
751 auto callingPid = CameraThreadState::getCallingPid();
752 auto callingUid = CameraThreadState::getCallingUid();
Jayant Chowdharyc3198c32021-07-28 20:59:14 +0000753 if (checkPermission(sSystemCameraPermission, callingPid, callingUid,
754 /*logPermissionFailure*/false) || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700755 deviceIds = &mNormalDeviceIds;
756 }
757 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800758 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700759 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800760 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800761 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800762
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700763 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800764}
765
766String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
767 Mutex::Autolock lock(mServiceLock);
768 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800769}
770
771Status CameraService::getCameraCharacteristics(const String16& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -0700772 int targetSdkVersion, bool overrideToPortrait, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700773 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700774 if (!cameraInfo) {
775 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800776 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700777 }
778
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800779 if (!mInitialized) {
780 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700781 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800782 return STATUS_ERROR(ERROR_DISCONNECTED,
783 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700784 }
785
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700786 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
787 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
788 "characteristics for system only device %s: ", String8(cameraId).string());
789 }
790
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800791 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800792
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700793
794 std::string cameraIdStr = String8(cameraId).string();
795 bool overrideForPerfClass =
796 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
797 cameraIdStr, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100798 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borger18b30a72022-10-27 12:20:29 -0700799 cameraIdStr, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100800 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700801 if (res == NAME_NOT_FOUND) {
802 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
803 "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
804 strerror(-res), res);
805 } else {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700806 logServiceError(String8::format("Unable to retrieve camera characteristics for "
807 "device %s.", String8(cameraId).string()),ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700808 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
809 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
810 strerror(-res), res);
811 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700812 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700813 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
814 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
815 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
816 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
817 "for device %s", String8(cameraId).string());
818 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700819 int callingPid = CameraThreadState::getCallingPid();
820 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100821 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700822 // If it's not calling from cameraserver, check the permission only if
823 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
824 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100825 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700826 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700827 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100828 res = cameraInfo->removePermissionEntries(
829 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
830 &tagsRemoved);
831 if (res != OK) {
832 cameraInfo->clear();
833 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
834 " characteristics needing camera permission for device %s: %s (%d)",
835 String8(cameraId).string(), strerror(-res), res);
836 }
837 }
838
839 if (!tagsRemoved.empty()) {
840 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
841 tagsRemoved.data(), tagsRemoved.size());
842 if (res != OK) {
843 cameraInfo->clear();
844 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
845 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
846 strerror(-res), res);
847 }
848 }
849
Zhijun He2b59be82013-09-25 10:14:30 -0700850 return ret;
851}
852
Rucha Katakwar38284522021-11-10 11:25:21 -0800853Status CameraService::getTorchStrengthLevel(const String16& cameraId,
854 int32_t* torchStrength) {
855 ATRACE_CALL();
856 Mutex::Autolock l(mServiceLock);
857 if (!mInitialized) {
858 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
859 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
860 }
861
862 if(torchStrength == NULL) {
863 ALOGE("%s: strength level must not be null.", __FUNCTION__);
864 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
865 }
866
867 status_t res = mCameraProviderManager->getTorchStrengthLevel(String8(cameraId).string(),
868 torchStrength);
869 if (res != OK) {
870 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
871 "strength level for device %s: %s (%d)", String8(cameraId).string(),
872 strerror(-res), res);
873 }
874 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
875 return Status::ok();
876}
877
Ruben Brunkcc776712015-02-17 20:18:47 -0800878String8 CameraService::getFormattedCurrentTime() {
879 time_t now = time(nullptr);
880 char formattedTime[64];
881 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
882 return String8(formattedTime);
883}
884
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800885Status CameraService::getCameraVendorTagDescriptor(
886 /*out*/
887 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700888 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800889 if (!mInitialized) {
890 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800891 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800892 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800893 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
894 if (globalDescriptor != nullptr) {
895 *desc = *(globalDescriptor.get());
896 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800897 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800898}
899
Emilian Peev71c73a22017-03-21 16:35:51 +0000900Status CameraService::getCameraVendorTagCache(
901 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
902 ATRACE_CALL();
903 if (!mInitialized) {
904 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
905 return STATUS_ERROR(ERROR_DISCONNECTED,
906 "Camera subsystem not available");
907 }
908 sp<VendorTagDescriptorCache> globalCache =
909 VendorTagDescriptorCache::getGlobalVendorTagCache();
910 if (globalCache != nullptr) {
911 *cache = *(globalCache.get());
912 }
913 return Status::ok();
914}
915
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700916void CameraService::clearCachedVariables() {
917 BasicClient::BasicClient::sCameraService = nullptr;
918}
919
Austin Borger18b30a72022-10-27 12:20:29 -0700920std::pair<int, IPCTransport> CameraService::getDeviceVersion(const String8& cameraId,
921 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700922 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800923
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800924 int deviceVersion = 0;
925
Emilian Peevf53f66e2017-04-11 14:29:43 +0100926 status_t res;
927 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +0000928 IPCTransport transport = IPCTransport::INVALID;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100929 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +0000930 &maxVersion, &transport);
931 if (res != OK || transport == IPCTransport::INVALID) {
932 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
933 cameraId.string());
934 return std::make_pair(-1, IPCTransport::INVALID) ;
935 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100936 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800937
Emilian Peevf53f66e2017-04-11 14:29:43 +0100938 hardware::CameraInfo info;
939 if (facing) {
Austin Borger18b30a72022-10-27 12:20:29 -0700940 res = mCameraProviderManager->getCameraInfo(cameraId.string(), overrideToPortrait,
941 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +0000942 if (res != OK) {
943 return std::make_pair(-1, IPCTransport::INVALID);
944 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100945 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -0700946 if (orientation) {
947 *orientation = info.orientation;
948 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800949 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100950
Jayant Chowdharyffc5d682022-05-12 18:34:34 +0000951 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -0800952}
953
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800954Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700955 switch(err) {
956 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800957 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800958 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800959 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
960 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800961 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800962 return STATUS_ERROR(ERROR_DISCONNECTED,
963 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700964 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800965 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
966 "Camera HAL encountered error %d: %s",
967 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700968 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800969}
970
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800971Status CameraService::makeClient(const sp<CameraService>& cameraService,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800972 const sp<IInterface>& cameraCb, const String16& packageName, bool systemNativeClient,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700973 const std::optional<String16>& featureId, const String8& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700974 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +0000975 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -0700976 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
977 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +0000978 // For HIDL devices
979 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
980 // Create CameraClient based on device version reported by the HAL.
981 int deviceVersion = deviceVersionAndTransport.first;
982 switch(deviceVersion) {
983 case CAMERA_DEVICE_API_VERSION_1_0:
984 ALOGE("Camera using old HAL version: %d", deviceVersion);
985 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
986 "Camera device \"%s\" HAL version %d no longer supported",
987 cameraId.string(), deviceVersion);
988 break;
989 case CAMERA_DEVICE_API_VERSION_3_0:
990 case CAMERA_DEVICE_API_VERSION_3_1:
991 case CAMERA_DEVICE_API_VERSION_3_2:
992 case CAMERA_DEVICE_API_VERSION_3_3:
993 case CAMERA_DEVICE_API_VERSION_3_4:
994 case CAMERA_DEVICE_API_VERSION_3_5:
995 case CAMERA_DEVICE_API_VERSION_3_6:
996 case CAMERA_DEVICE_API_VERSION_3_7:
997 break;
998 default:
999 // Should not be reachable
1000 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1001 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1002 "Camera device \"%s\" has unknown HAL version %d",
1003 cameraId.string(), deviceVersion);
1004 }
1005 }
1006 if (effectiveApiLevel == API_1) { // Camera1 API route
1007 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001008 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
1009 packageName, featureId, cameraId, api1CameraId, facing, sensorOrientation,
Austin Borger18b30a72022-10-27 12:20:29 -07001010 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait);
1011 ALOGI("%s: Camera1 API (legacy), override to portrait %d", __FUNCTION__,
1012 overrideToPortrait);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001013 } else { // Camera2 API route
1014 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1015 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001016 *client = new CameraDeviceClient(cameraService, tmp,
1017 cameraService->mCameraServiceProxyWrapper, packageName, systemNativeClient,
1018 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
Austin Borger18b30a72022-10-27 12:20:29 -07001019 overrideForPerfClass, overrideToPortrait);
1020 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001021 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001022 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001023}
1024
Ruben Brunk6267b532015-04-30 17:44:07 -07001025String8 CameraService::toString(std::set<userid_t> intSet) {
1026 String8 s("");
1027 bool first = true;
1028 for (userid_t i : intSet) {
1029 if (first) {
1030 s.appendFormat("%d", i);
1031 first = false;
1032 } else {
1033 s.appendFormat(", %d", i);
1034 }
1035 }
1036 return s;
1037}
1038
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001039int32_t CameraService::mapToInterface(TorchModeStatus status) {
1040 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1041 switch (status) {
1042 case TorchModeStatus::NOT_AVAILABLE:
1043 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1044 break;
1045 case TorchModeStatus::AVAILABLE_OFF:
1046 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1047 break;
1048 case TorchModeStatus::AVAILABLE_ON:
1049 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1050 break;
1051 default:
1052 ALOGW("Unknown new flash status: %d", status);
1053 }
1054 return serviceStatus;
1055}
1056
1057CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1058 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1059 switch (status) {
1060 case CameraDeviceStatus::NOT_PRESENT:
1061 serviceStatus = StatusInternal::NOT_PRESENT;
1062 break;
1063 case CameraDeviceStatus::PRESENT:
1064 serviceStatus = StatusInternal::PRESENT;
1065 break;
1066 case CameraDeviceStatus::ENUMERATING:
1067 serviceStatus = StatusInternal::ENUMERATING;
1068 break;
1069 default:
1070 ALOGW("Unknown new HAL device status: %d", status);
1071 }
1072 return serviceStatus;
1073}
1074
1075int32_t CameraService::mapToInterface(StatusInternal status) {
1076 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1077 switch (status) {
1078 case StatusInternal::NOT_PRESENT:
1079 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1080 break;
1081 case StatusInternal::PRESENT:
1082 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1083 break;
1084 case StatusInternal::ENUMERATING:
1085 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1086 break;
1087 case StatusInternal::NOT_AVAILABLE:
1088 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1089 break;
1090 case StatusInternal::UNKNOWN:
1091 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1092 break;
1093 default:
1094 ALOGW("Unknown new internal device status: %d", status);
1095 }
1096 return serviceStatus;
1097}
1098
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001099Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001100 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001101
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001102 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -08001103 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001104 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001105 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001106 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001107 sp<ICameraClient>{nullptr}, id, cameraId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001108 internalPackageName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001109 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Austin Borger18b30a72022-10-27 12:20:29 -07001110 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001111 ).isOk()) {
1112 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001113 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001114 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001115}
1116
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001117Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001118 /*out*/
1119 CameraParameters* parameters) {
1120
1121 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1122
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001123 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001124
1125 if (parameters == NULL) {
1126 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001127 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001128 }
1129
Ruben Brunkcc776712015-02-17 20:18:47 -08001130 String8 id = String8::format("%d", cameraId);
1131
1132 // Check if we already have parameters
1133 {
1134 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001135 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001136 auto cameraState = getCameraState(id);
1137 if (cameraState == nullptr) {
1138 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001139 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1140 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001141 }
1142 CameraParameters p = cameraState->getShimParams();
1143 if (!p.isEmpty()) {
1144 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001145 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001146 }
1147 }
1148
Jayant Chowdhary12361932018-08-27 14:46:13 -07001149 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001150 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001151 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001152 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001153 // Error already logged by callee
1154 return ret;
1155 }
1156
1157 // Check for parameters again
1158 {
1159 // Scope for service lock
1160 Mutex::Autolock lock(mServiceLock);
1161 auto cameraState = getCameraState(id);
1162 if (cameraState == nullptr) {
1163 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001164 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1165 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001166 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001167 CameraParameters p = cameraState->getShimParams();
1168 if (!p.isEmpty()) {
1169 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001170 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001171 }
1172 }
1173
Ruben Brunkcc776712015-02-17 20:18:47 -08001174 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1175 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001176 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001177}
1178
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001179// Can camera service trust the caller based on the calling UID?
1180static bool isTrustedCallingUid(uid_t uid) {
1181 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001182 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001183 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001184 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001185 return true;
1186 default:
1187 return false;
1188 }
1189}
1190
Nicholas Sauera3620332019-04-03 14:05:17 -07001191static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1192 PermissionController pc;
1193 uid = pc.getPackageUid(packageName, 0);
1194 if (uid <= 0) {
1195 ALOGE("Unknown package: '%s'", String8(packageName).string());
1196 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1197 return BAD_VALUE;
1198 }
1199
1200 if (userId < 0) {
1201 ALOGE("Invalid user: %d", userId);
1202 dprintf(err, "Invalid user: %d\n", userId);
1203 return BAD_VALUE;
1204 }
1205
1206 uid = multiuser_get_uid(userId, uid);
1207 return NO_ERROR;
1208}
1209
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001210Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001211 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1212 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001213
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001214#ifdef __BRILLO__
1215 UNUSED(clientName8);
1216 UNUSED(clientUid);
1217 UNUSED(clientPid);
1218 UNUSED(originalClientPid);
1219#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001220 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1221 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001222 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001223 return allowed;
1224 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001225#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001226
Jayant Chowdhary12361932018-08-27 14:46:13 -07001227 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001228
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001229 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001230 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1231 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001232 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1233 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001234 }
1235
Ruben Brunkcc776712015-02-17 20:18:47 -08001236 if (getCameraState(cameraId) == nullptr) {
1237 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1238 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001239 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1240 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001241 }
1242
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001243 status_t err = checkIfDeviceIsUsable(cameraId);
1244 if (err != NO_ERROR) {
1245 switch(err) {
1246 case -ENODEV:
1247 case -EBUSY:
1248 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1249 "No camera device with ID \"%s\" currently available", cameraId.string());
1250 default:
1251 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1252 "Unknown error connecting to ID \"%s\"", cameraId.string());
1253 }
1254 }
1255 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001256}
1257
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001258Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001259 const String8& clientName8, int& clientUid, int& clientPid,
1260 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001261 int callingPid = CameraThreadState::getCallingPid();
1262 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001263
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001264 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001265 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001266 clientUid = callingUid;
1267 } else if (!isTrustedCallingUid(callingUid)) {
1268 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1269 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001270 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1271 "Untrusted caller (calling PID %d, UID %d) trying to "
1272 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1273 callingPid, callingUid, cameraId.string(),
1274 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001275 }
1276
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001277 // Check if we can trust clientPid
1278 if (clientPid == USE_CALLING_PID) {
1279 clientPid = callingPid;
1280 } else if (!isTrustedCallingUid(callingUid)) {
1281 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1282 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001283 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1284 "Untrusted caller (calling PID %d, UID %d) trying to "
1285 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1286 callingPid, callingUid, cameraId.string(),
1287 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001288 }
1289
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001290 if (shouldRejectSystemCameraConnection(cameraId)) {
1291 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1292 cameraId.c_str());
1293 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1294 "available", cameraId.string());
1295 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001296 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1297 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1298 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1299 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1300 "found while trying to query device kind", cameraId.string());
1301
1302 }
1303
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001304 // If it's not calling from cameraserver, check the permission if the
1305 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1306 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001307 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001308 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001309 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001310 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001311 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1312 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1313 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001314 }
1315
Svet Ganova453d0d2018-01-11 15:37:58 -08001316 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001317 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001318 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001319 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1320 clientPid, clientUid);
1321 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001322 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1323 "calling UID %d proc state %" PRId32 ")",
1324 clientName8.string(), clientUid, clientPid, cameraId.string(),
1325 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001326 }
1327
Michael Grooverd1d435a2018-12-18 17:39:42 -08001328 // If sensor privacy is enabled then prevent access to the camera
1329 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1330 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1331 return STATUS_ERROR_FMT(ERROR_DISABLED,
1332 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1333 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1334 }
1335
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001336 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1337 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001338 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001339 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001340
Ruben Brunk6267b532015-04-30 17:44:07 -07001341 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001342
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001343 // For non-system clients : Only allow clients who are being used by the current foreground
1344 // device user, unless calling from our own process.
1345 if (!doesClientHaveSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001346 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001347 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1348 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1349 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001350 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1351 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1352 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001353 }
1354
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001355 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001356}
1357
1358status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1359 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001360 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001361 if (cameraState == nullptr) {
1362 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1363 cameraId.string());
1364 return -ENODEV;
1365 }
1366
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001367 StatusInternal currentStatus = cameraState->getStatus();
1368 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001369 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1370 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001371 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001372 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001373 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1374 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001375 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001376 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001377
Ruben Brunkcc776712015-02-17 20:18:47 -08001378 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001379}
1380
Ruben Brunkcc776712015-02-17 20:18:47 -08001381void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001382 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001383
Ruben Brunkcc776712015-02-17 20:18:47 -08001384 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001385 auto clientDescriptor =
1386 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001387 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001388 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1389
1390 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1391 String8(client->getPackageName()));
1392
1393 if (evicted.size() > 0) {
1394 // This should never happen - clients should already have been removed in disconnect
1395 for (auto& i : evicted) {
1396 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1397 __FUNCTION__, i->getKey().string());
1398 }
1399
1400 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1401 __FUNCTION__);
1402 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001403
1404 // And register a death notification for the client callback. Do
1405 // this last to avoid Binder policy where a nested Binder
1406 // transaction might be pre-empted to service the client death
1407 // notification if the client process dies before linkToDeath is
1408 // invoked.
1409 sp<IBinder> remoteCallback = client->getRemote();
1410 if (remoteCallback != nullptr) {
1411 remoteCallback->linkToDeath(this);
1412 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001413}
1414
1415status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1416 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001417 int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001418 /*out*/
1419 sp<BasicClient>* client,
1420 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001421 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001422 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001423 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001424 DescriptorPtr clientDescriptor;
1425 {
1426 if (effectiveApiLevel == API_1) {
1427 // If we are using API1, any existing client for this camera ID with the same remote
1428 // should be returned rather than evicted to allow MediaRecorder to work properly.
1429
1430 auto current = mActiveClientManager.get(cameraId);
1431 if (current != nullptr) {
1432 auto clientSp = current->getValue();
1433 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001434 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001435 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001436 " API level, evicting prior client...");
1437 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001438 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001439 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001440 *client = clientSp;
1441 return NO_ERROR;
1442 }
1443 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001444 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001445 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001446
Ruben Brunkcc776712015-02-17 20:18:47 -08001447 // Get current active client PIDs
1448 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1449 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001450
Emilian Peev8131a262017-02-01 12:33:43 +00001451 std::vector<int> priorityScores(ownerPids.size());
1452 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001453
Emilian Peev8131a262017-02-01 12:33:43 +00001454 // Get priority scores of all active PIDs
1455 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1456 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1457 /*out*/&priorityScores[0]);
1458 if (err != OK) {
1459 ALOGE("%s: Priority score query failed: %d",
1460 __FUNCTION__, err);
1461 return err;
1462 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001463
Ruben Brunkcc776712015-02-17 20:18:47 -08001464 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001465 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001466 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001467 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001468 resource_policy::ClientPriority(priorityScores[i], states[i],
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001469 /* isVendorClient won't get copied over*/ false,
1470 /* oomScoreOffset won't get copied over*/ 0));
Ruben Brunkcc776712015-02-17 20:18:47 -08001471 }
1472 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001473
Ruben Brunkcc776712015-02-17 20:18:47 -08001474 // Get state for the given cameraId
1475 auto state = getCameraState(cameraId);
1476 if (state == nullptr) {
1477 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1478 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001479 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001480 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001481 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001482
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001483 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1484 int32_t actualState = states[states.size() - 1];
1485
1486 // Make descriptor for incoming client. We store the oomScoreOffset
1487 // since we might need it later on new handleEvictionsLocked and
1488 // ProcessInfoService would not take that into account.
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001489 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001490 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001491 state->getConflicting(), actualScore, clientPid, actualState,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001492 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001493
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001494 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1495
Ruben Brunkcc776712015-02-17 20:18:47 -08001496 // Find clients that would be evicted
1497 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1498
1499 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1500 // background, so we cannot do evictions
1501 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1502 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1503 " priority).", clientPid);
1504
1505 sp<BasicClient> clientSp = clientDescriptor->getValue();
1506 String8 curTime = getFormattedCurrentTime();
1507 auto incompatibleClients =
1508 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1509
1510 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001511 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001512 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001513 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001514
1515 for (auto& i : incompatibleClients) {
1516 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001517 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1518 i->getKey().string(),
1519 String8{i->getValue()->getPackageName()}.string(),
1520 i->getOwnerId(), i->getPriority().getScore(),
1521 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001522 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001523 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001524 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001525 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001526 }
1527
1528 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001529 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001530 mEventLog.add(msg);
1531
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001532 auto current = mActiveClientManager.get(cameraId);
1533 if (current != nullptr) {
1534 return -EBUSY; // CAMERA_IN_USE
1535 } else {
1536 return -EUSERS; // MAX_CAMERAS_IN_USE
1537 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001538 }
1539
1540 for (auto& i : evicted) {
1541 sp<BasicClient> clientSp = i->getValue();
1542 if (clientSp.get() == nullptr) {
1543 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1544
1545 // TODO: Remove this
1546 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1547 __FUNCTION__);
1548 mActiveClientManager.remove(i);
1549 continue;
1550 }
1551
1552 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1553 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001554 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001555
Ruben Brunkcc776712015-02-17 20:18:47 -08001556 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001557 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001558 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1559 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001560 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001561 i->getOwnerId(), i->getPriority().getScore(),
1562 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001563 packageName.string(), clientPid, clientPriority.getScore(),
1564 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001565
1566 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001567 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001568 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001569 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001570 }
1571
Ruben Brunkcc776712015-02-17 20:18:47 -08001572 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1573 // other clients from connecting in mServiceLockWrapper if held
1574 mServiceLock.unlock();
1575
1576 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001577 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001578
1579 // Destroy evicted clients
1580 for (auto& i : evictedClients) {
1581 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001582 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001583 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001584
Jayant Chowdhary12361932018-08-27 14:46:13 -07001585 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001586
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001587 for (const auto& i : evictedClients) {
1588 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1589 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1590 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1591 if (ret == TIMED_OUT) {
1592 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1593 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1594 mActiveClientManager.toString().string());
1595 return -EBUSY;
1596 }
1597 if (ret != NO_ERROR) {
1598 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1599 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1600 ret, mActiveClientManager.toString().string());
1601 return ret;
1602 }
1603 }
1604
1605 evictedClients.clear();
1606
Ruben Brunkcc776712015-02-17 20:18:47 -08001607 // Once clients have been disconnected, relock
1608 mServiceLock.lock();
1609
1610 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1611 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1612 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001613 }
1614
Ruben Brunkcc776712015-02-17 20:18:47 -08001615 *partial = clientDescriptor;
1616 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001617}
1618
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001619Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001620 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001621 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001622 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001623 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001624 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001625 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001626 bool overrideToPortrait,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001627 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001628 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001629
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001630 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001631 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001632
1633 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001634 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001635 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001636 clientPackageName,/*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07001637 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
1638 overrideToPortrait, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001639
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001640 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001641 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001642 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001643 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001644 }
1645
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001646 *device = client;
1647 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001648}
1649
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001650bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1651 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001652 // If the client is not a vendor client, don't add listener if
1653 // a) the camera is a publicly hidden secure camera OR
1654 // b) the camera is a system only camera and the client doesn't
1655 // have android.permission.SYSTEM_CAMERA permissions.
1656 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1657 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1658 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001659 return true;
1660 }
1661 return false;
1662}
1663
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001664bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1665 // Rules for rejection:
1666 // 1) If cameraserver tries to access this camera device, accept the
1667 // connection.
1668 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001669 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001670 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1671 // and the serving thread is a non hwbinder thread, the client must have
1672 // android.permission.SYSTEM_CAMERA permissions to connect.
1673
1674 int cPid = CameraThreadState::getCallingPid();
1675 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001676 bool systemClient = doesClientHaveSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001677 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1678 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001679 // This isn't a known camera ID, so it's not a system camera
1680 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1681 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001682 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001683
1684 // (1) Cameraserver trying to connect, accept.
1685 if (CameraThreadState::getCallingPid() == getpid()) {
1686 return false;
1687 }
1688 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001689 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001690 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1691 return true;
1692 }
1693 // (3) Here we only check for permissions if it is a system only camera device. This is since
1694 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1695 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1696 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001697 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jayant Chowdharyc3198c32021-07-28 20:59:14 +00001698 !hasPermissionsForSystemCamera(cPid, cUid, /*logPermissionFailure*/true)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001699 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1700 cameraId.c_str());
1701 return true;
1702 }
1703
1704 return false;
1705}
1706
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001707Status CameraService::connectDevice(
1708 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001709 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001710 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001711 const std::optional<String16>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001712 int clientUid, int oomScoreOffset, int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001713 bool overrideToPortrait,
Ruben Brunkcc776712015-02-17 20:18:47 -08001714 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001715 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001716
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001717 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001718 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001719 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001720 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001721 String16 clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001722 int callingPid = CameraThreadState::getCallingPid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001723 bool systemNativeClient = false;
1724 if (doesClientHaveSystemUid() && (clientPackageNameAdj.size() == 0)) {
1725 std::string systemClient =
1726 StringPrintf("client.pid<%d>", CameraThreadState::getCallingPid());
1727 clientPackageNameAdj = String16(systemClient.c_str());
1728 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001729 }
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001730
1731 if (oomScoreOffset < 0) {
1732 String8 msg =
1733 String8::format("Cannot increase the priority of a client %s pid %d for "
1734 "camera id %s", String8(clientPackageNameAdj).string(), callingPid,
1735 id.string());
1736 ALOGE("%s: %s", __FUNCTION__, msg.string());
1737 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1738 }
1739
Austin Borger9bfa0a72022-08-03 17:50:40 -07001740 userid_t clientUserId = multiuser_get_user_id(clientUid);
1741 int callingUid = CameraThreadState::getCallingUid();
1742 if (clientUid == USE_CALLING_UID) {
1743 clientUserId = multiuser_get_user_id(callingUid);
1744 }
1745
1746 if (mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borger5f7abe22022-04-26 15:55:10 -07001747 String8 msg =
1748 String8::format("Camera disabled by device policy");
1749 ALOGE("%s: %s", __FUNCTION__, msg.string());
1750 return STATUS_ERROR(ERROR_DISABLED, msg.string());
1751 }
1752
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001753 // enforce system camera permissions
1754 if (oomScoreOffset > 0 &&
Austin Borger86a588e2022-05-23 12:41:58 -07001755 !hasPermissionsForSystemCamera(callingPid, CameraThreadState::getCallingUid()) &&
1756 !isTrustedCallingUid(CameraThreadState::getCallingUid())) {
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001757 String8 msg =
1758 String8::format("Cannot change the priority of a client %s pid %d for "
1759 "camera id %s without SYSTEM_CAMERA permissions",
1760 String8(clientPackageNameAdj).string(), callingPid, id.string());
1761 ALOGE("%s: %s", __FUNCTION__, msg.string());
1762 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.string());
1763 }
1764
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001765 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001766 /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient,clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001767 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
Austin Borger18b30a72022-10-27 12:20:29 -07001768 targetSdkVersion, overrideToPortrait, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001769
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001770 if(!ret.isOk()) {
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001771 logRejected(id, callingPid, String8(clientPackageNameAdj), ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001772 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001773 }
1774
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001775 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07001776 Mutex::Autolock lock(mServiceLock);
1777
1778 // Clear the previous cached logs and reposition the
1779 // file offset to beginning of the file to log new data.
1780 // If either truncate or lseek fails, close the previous file and create a new one.
1781 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
1782 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
1783 // Close the previous memfd.
1784 close(mMemFd);
1785 // If failure to wipe the data, then create a new file and
1786 // assign the new value to mMemFd.
1787 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
1788 if (mMemFd == -1) {
1789 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
1790 }
1791 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001792 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001793}
1794
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001795String16 CameraService::getPackageNameFromUid(int clientUid) {
1796 String16 packageName("");
1797
1798 sp<IServiceManager> sm = defaultServiceManager();
1799 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
1800 if (binder == 0) {
1801 ALOGE("Cannot get permission service");
1802 // Return empty package name and the further interaction
1803 // with camera will likely fail
1804 return packageName;
1805 }
1806
1807 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
1808 Vector<String16> packages;
1809
1810 permCtrl->getPackagesForUid(clientUid, packages);
1811
1812 if (packages.isEmpty()) {
1813 ALOGE("No packages for calling UID %d", clientUid);
1814 // Return empty package name and the further interaction
1815 // with camera will likely fail
1816 return packageName;
1817 }
1818
1819 // Arbitrarily pick the first name in the list
1820 packageName = packages[0];
1821
1822 return packageName;
1823}
1824
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001825template<class CALLBACK, class CLIENT>
1826Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001827 int api1CameraId, const String16& clientPackageNameMaybe, bool systemNativeClient,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001828 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001829 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001830 bool overrideToPortrait, /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001831 binder::Status ret = binder::Status::ok();
1832
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001833 bool isNonSystemNdk = false;
1834 String16 clientPackageName;
1835 if (clientPackageNameMaybe.size() <= 0) {
1836 // NDK calls don't come with package names, but we need one for various cases.
1837 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
1838 // do exist. For all authentication cases, all packages under the same UID get the
1839 // same permissions, so picking any associated package name is sufficient. For some
1840 // other cases, this may give inaccurate names for clients in logs.
1841 isNonSystemNdk = true;
1842 int packageUid = (clientUid == USE_CALLING_UID) ?
1843 CameraThreadState::getCallingUid() : clientUid;
1844 clientPackageName = getPackageNameFromUid(packageUid);
1845 } else {
1846 clientPackageName = clientPackageNameMaybe;
1847 }
1848
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001849 String8 clientName8(clientPackageName);
1850
1851 int originalClientPid = 0;
1852
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001853 int packagePid = (clientPid == USE_CALLING_PID) ?
1854 CameraThreadState::getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001855 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001856 "Camera API version %d", packagePid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001857 static_cast<int>(effectiveApiLevel));
1858
Shuzhen Wang316781a2020-08-18 18:11:01 -07001859 nsecs_t openTimeNs = systemTime();
1860
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001861 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001862 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07001863 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001864
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001865 {
1866 // Acquire mServiceLock and prevent other clients from connecting
1867 std::unique_ptr<AutoConditionLock> lock =
1868 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1869
1870 if (lock == nullptr) {
1871 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1872 , clientPid);
1873 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1874 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1875 cameraId.string(), clientName8.string(), clientPid);
1876 }
1877
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001878 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001879 if(!(ret = validateConnectLocked(cameraId, clientName8,
1880 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1881 return ret;
1882 }
1883
1884 // Check the shim parameters after acquiring lock, if they have already been updated and
1885 // we were doing a shim update, return immediately
1886 if (shimUpdateOnly) {
1887 auto cameraState = getCameraState(cameraId);
1888 if (cameraState != nullptr) {
1889 if (!cameraState->getShimParams().isEmpty()) return ret;
1890 }
1891 }
1892
1893 status_t err;
1894
1895 sp<BasicClient> clientTmp = nullptr;
1896 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1897 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001898 IInterface::asBinder(cameraCb), clientName8, oomScoreOffset, systemNativeClient,
1899 /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001900 switch (err) {
1901 case -ENODEV:
1902 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1903 "No camera device with ID \"%s\" currently available",
1904 cameraId.string());
1905 case -EBUSY:
1906 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1907 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1908 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001909 case -EUSERS:
1910 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1911 "Too many cameras already open, cannot open camera \"%s\"",
1912 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001913 default:
1914 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1915 "Unexpected error %s (%d) opening camera \"%s\"",
1916 strerror(-err), err, cameraId.string());
1917 }
1918 }
1919
1920 if (clientTmp.get() != nullptr) {
1921 // Handle special case for API1 MediaRecorder where the existing client is returned
1922 device = static_cast<CLIENT*>(clientTmp.get());
1923 return ret;
1924 }
1925
1926 // give flashlight a chance to close devices if necessary.
1927 mFlashlight->prepareDeviceOpen(cameraId);
1928
Austin Borger18b30a72022-10-27 12:20:29 -07001929 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001930 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07001931 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
1932 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001933 if (facing == -1) {
1934 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1935 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1936 "Unable to get camera device \"%s\" facing", cameraId.string());
1937 }
1938
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001939 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001940 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1941 mPerfClassPrimaryCameraIds, cameraId.string(), targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001942 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
1943 clientFeatureId, cameraId, api1CameraId, facing, orientation,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001944 clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001945 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
Austin Borger18b30a72022-10-27 12:20:29 -07001946 overrideToPortrait, /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001947 return ret;
1948 }
1949 client = static_cast<CLIENT*>(tmp.get());
1950
1951 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1952 __FUNCTION__);
1953
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07001954 String8 monitorTags = isClientWatched(client.get()) ? mMonitorTags : String8("");
1955 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001956 if (err != OK) {
1957 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001958 // Errors could be from the HAL module open call or from AppOpsManager
1959 switch(err) {
1960 case BAD_VALUE:
1961 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1962 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1963 case -EBUSY:
1964 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1965 "Camera \"%s\" is already open", cameraId.string());
1966 case -EUSERS:
1967 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1968 "Too many cameras already open, cannot open camera \"%s\"",
1969 cameraId.string());
1970 case PERMISSION_DENIED:
1971 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1972 "No permission to open camera \"%s\"", cameraId.string());
1973 case -EACCES:
1974 return STATUS_ERROR_FMT(ERROR_DISABLED,
1975 "Camera \"%s\" disabled by policy", cameraId.string());
1976 case -ENODEV:
1977 default:
1978 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1979 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1980 strerror(-err), err);
1981 }
1982 }
1983
1984 // Update shim paremeters for legacy clients
1985 if (effectiveApiLevel == API_1) {
1986 // Assume we have always received a Client subclass for API1
1987 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1988 String8 rawParams = shimClient->getParameters();
1989 CameraParameters params(rawParams);
1990
1991 auto cameraState = getCameraState(cameraId);
1992 if (cameraState != nullptr) {
1993 cameraState->setShimParams(params);
1994 } else {
1995 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1996 __FUNCTION__, cameraId.string());
1997 }
1998 }
1999
Ravneetaeb20dc2022-03-30 05:33:03 +00002000 // Enable/disable camera service watchdog
2001 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2002
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002003 // Set rotate-and-crop override behavior
2004 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2005 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Austin Borger18b30a72022-10-27 12:20:29 -07002006 } else if (overrideToPortrait && portraitRotation != 0) {
2007 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2008 switch (portraitRotation) {
2009 case 90:
2010 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2011 break;
2012 case 180:
2013 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2014 break;
2015 case 270:
2016 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2017 break;
2018 default:
2019 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2020 break;
2021 }
2022 client->setRotateAndCropOverride(rotateAndCropMode);
Emilian Peev13f35ad2022-04-27 11:28:48 -07002023 } else {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002024 client->setRotateAndCropOverride(
2025 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2026 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2027 }
2028
2029 // Set autoframing override behaviour
2030 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2031 client->setAutoframingOverride(mOverrideAutoframingMode);
2032 } else {
2033 client->setAutoframingOverride(
2034 mCameraServiceProxyWrapper->getAutoframingOverride(
2035 clientPackageName));
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002036 }
2037
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002038 // Set camera muting behavior
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002039 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08002040 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002041 if (client->supportsCameraMute()) {
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002042 client->setCameraMute(
2043 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2044 } else if (isCameraPrivacyEnabled) {
2045 // no camera mute supported, but privacy is on! => disconnect
2046 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2047 String8(client->getPackageName()).string(), cameraId.string());
2048 // Do not hold mServiceLock while disconnecting clients, but
2049 // retain the condition blocking other clients from connecting
2050 // in mServiceLockWrapper if held.
2051 mServiceLock.unlock();
2052 // Clear caller identity temporarily so client disconnect PID
2053 // checks work correctly
2054 int64_t token = CameraThreadState::clearCallingIdentity();
2055 // Note AppOp to trigger the "Unblock" dialog
2056 client->noteAppOp();
2057 client->disconnect();
2058 CameraThreadState::restoreCallingIdentity(token);
2059 // Reacquire mServiceLock
2060 mServiceLock.lock();
2061
2062 return STATUS_ERROR_FMT(ERROR_DISABLED,
2063 "Camera \"%s\" disabled due to camera mute", cameraId.string());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002064 }
2065
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002066 if (shimUpdateOnly) {
2067 // If only updating legacy shim parameters, immediately disconnect client
2068 mServiceLock.unlock();
2069 client->disconnect();
2070 mServiceLock.lock();
2071 } else {
2072 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002073 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002074 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002075
2076 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002077 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002078 } // lock is destroyed, allow further connect calls
2079
2080 // Important: release the mutex here so the client can call back into the service from its
2081 // destructor (can be at the end of the call)
2082 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002083
2084 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002085 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002086 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002087
Cliff Wud3a05312021-04-26 23:07:31 +08002088 {
2089 Mutex::Autolock lock(mInjectionParametersLock);
2090 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2091 mInjectionInitPending = false;
2092 status_t res = NO_ERROR;
2093 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2094 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002095 sp<BasicClient> clientSp = clientDescriptor->getValue();
2096 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2097 if(res != OK) {
2098 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2099 "No camera device with ID \"%s\" currently available",
2100 mInjectionExternalCamId.string());
2101 }
2102 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002103 if (res != OK) {
2104 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2105 }
2106 } else {
2107 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
2108 __FUNCTION__, mInjectionInternalCamId.string());
2109 res = NO_INIT;
2110 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2111 }
2112 }
2113 }
2114
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002115 return ret;
2116}
2117
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002118status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
2119 if (offlineClient.get() == nullptr) {
2120 return BAD_VALUE;
2121 }
2122
2123 {
2124 // Acquire mServiceLock and prevent other clients from connecting
2125 std::unique_ptr<AutoConditionLock> lock =
2126 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2127
2128 if (lock == nullptr) {
2129 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2130 , __FUNCTION__, offlineClient->getClientPid());
2131 return TIMED_OUT;
2132 }
2133
2134 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2135 if (onlineClientDesc.get() == nullptr) {
2136 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2137 cameraId.c_str());
2138 return BAD_VALUE;
2139 }
2140
2141 // Offline clients do not evict or conflict with other online devices. Resource sharing
2142 // conflicts are handled by the camera provider which will either succeed or fail before
2143 // reaching this method.
2144 const auto& onlinePriority = onlineClientDesc->getPriority();
2145 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2146 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
2147 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002148 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002149 // native clients don't have offline processing support.
2150 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002151 if (offlineClientDesc == nullptr) {
2152 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2153 return BAD_VALUE;
2154 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002155
2156 // Allow only one offline device per camera
2157 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2158 if (!incompatibleClients.empty()) {
2159 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2160 return BAD_VALUE;
2161 }
2162
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002163 String8 monitorTags = isClientWatched(offlineClient.get()) ? mMonitorTags : String8("");
2164 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002165 if (err != OK) {
2166 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2167 return err;
2168 }
2169
2170 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2171 if (evicted.size() > 0) {
2172 for (auto& i : evicted) {
2173 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
2174 __FUNCTION__, i->getKey().string());
2175 }
2176
2177 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2178 "properly", __FUNCTION__);
2179
2180 return BAD_VALUE;
2181 }
2182
2183 logConnectedOffline(offlineClientDesc->getKey(),
2184 static_cast<int>(offlineClientDesc->getOwnerId()),
2185 String8(offlineClient->getPackageName()));
2186
2187 sp<IBinder> remoteCallback = offlineClient->getRemote();
2188 if (remoteCallback != nullptr) {
2189 remoteCallback->linkToDeath(this);
2190 }
2191 } // lock is destroyed, allow further connect calls
2192
2193 return OK;
2194}
2195
Rucha Katakwar38284522021-11-10 11:25:21 -08002196Status CameraService::turnOnTorchWithStrengthLevel(const String16& cameraId, int32_t torchStrength,
2197 const sp<IBinder>& clientBinder) {
2198 Mutex::Autolock lock(mServiceLock);
2199
2200 ATRACE_CALL();
2201 if (clientBinder == nullptr) {
2202 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2203 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2204 "Torch client binder in null.");
2205 }
2206
2207 String8 id = String8(cameraId.string());
2208 int uid = CameraThreadState::getCallingUid();
2209
2210 if (shouldRejectSystemCameraConnection(id)) {
2211 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
2212 "for system only device %s: ", id.string());
2213 }
2214
2215 // verify id is valid
2216 auto state = getCameraState(id);
2217 if (state == nullptr) {
2218 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
2219 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2220 "Camera ID \"%s\" is a not valid camera ID", id.string());
2221 }
2222
2223 StatusInternal cameraStatus = state->getStatus();
2224 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2225 cameraStatus != StatusInternal::PRESENT) {
2226 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(),
2227 (int)cameraStatus);
2228 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2229 "Camera ID \"%s\" is a not valid camera ID", id.string());
2230 }
2231
2232 {
2233 Mutex::Autolock al(mTorchStatusMutex);
2234 TorchModeStatus status;
2235 status_t err = getTorchStatusLocked(id, &status);
2236 if (err != OK) {
2237 if (err == NAME_NOT_FOUND) {
2238 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2239 "Camera \"%s\" does not have a flash unit", id.string());
2240 }
2241 ALOGE("%s: getting current torch status failed for camera %s",
2242 __FUNCTION__, id.string());
2243 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2244 "Error changing torch strength level for camera \"%s\": %s (%d)",
2245 id.string(), strerror(-err), err);
2246 }
2247
2248 if (status == TorchModeStatus::NOT_AVAILABLE) {
2249 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2250 ALOGE("%s: torch mode of camera %s is not available because "
2251 "camera is in use.", __FUNCTION__, id.string());
2252 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2253 "Torch for camera \"%s\" is not available due to an existing camera user",
2254 id.string());
2255 } else {
2256 ALOGE("%s: torch mode of camera %s is not available due to "
2257 "insufficient resources", __FUNCTION__, id.string());
2258 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2259 "Torch for camera \"%s\" is not available due to insufficient resources",
2260 id.string());
2261 }
2262 }
2263 }
2264
2265 {
2266 Mutex::Autolock al(mTorchUidMapMutex);
2267 updateTorchUidMapLocked(cameraId, uid);
2268 }
2269 // Check if the current torch strength level is same as the new one.
2270 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
2271 id.string(), torchStrength);
2272
2273 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(id, torchStrength);
2274
2275 if (err != OK) {
2276 int32_t errorCode;
2277 String8 msg;
2278 switch (err) {
2279 case -ENOSYS:
2280 msg = String8::format("Camera \"%s\" has no flashlight.",
2281 id.string());
2282 errorCode = ERROR_ILLEGAL_ARGUMENT;
2283 break;
2284 case -EBUSY:
2285 msg = String8::format("Camera \"%s\" is in use",
2286 id.string());
2287 errorCode = ERROR_CAMERA_IN_USE;
2288 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002289 case -EINVAL:
2290 msg = String8::format("Torch strength level %d is not within the "
2291 "valid range.", torchStrength);
2292 errorCode = ERROR_ILLEGAL_ARGUMENT;
2293 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002294 default:
2295 msg = String8::format("Changing torch strength level failed.");
2296 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002297 }
2298 ALOGE("%s: %s", __FUNCTION__, msg.string());
2299 return STATUS_ERROR(errorCode, msg.string());
2300 }
2301
2302 {
2303 // update the link to client's death
2304 // Store the last client that turns on each camera's torch mode.
2305 Mutex::Autolock al(mTorchClientMapMutex);
2306 ssize_t index = mTorchClientMap.indexOfKey(id);
2307 if (index == NAME_NOT_FOUND) {
2308 mTorchClientMap.add(id, clientBinder);
2309 } else {
2310 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2311 mTorchClientMap.replaceValueAt(index, clientBinder);
2312 }
2313 clientBinder->linkToDeath(this);
2314 }
2315
2316 int clientPid = CameraThreadState::getCallingPid();
2317 const char *id_cstr = id.c_str();
2318 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
2319 __FUNCTION__, id_cstr, torchStrength, clientPid);
2320 if (!shouldSkipTorchStrengthUpdates) {
2321 broadcastTorchStrengthLevel(id, torchStrength);
2322 }
2323 return Status::ok();
2324}
2325
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002326Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002327 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002328 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002329
2330 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002331 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002332 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002333 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2334 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002335 }
2336
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002337 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07002338 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002339
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002340 if (shouldRejectSystemCameraConnection(id)) {
2341 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
2342 " for system only device %s: ", id.string());
2343 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002344 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08002345 auto state = getCameraState(id);
2346 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002347 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002348 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2349 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002350 }
2351
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002352 StatusInternal cameraStatus = state->getStatus();
2353 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002354 cameraStatus != StatusInternal::NOT_AVAILABLE) {
2355 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002356 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2357 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002358 }
2359
2360 {
2361 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002362 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002363 status_t err = getTorchStatusLocked(id, &status);
2364 if (err != OK) {
2365 if (err == NAME_NOT_FOUND) {
2366 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2367 "Camera \"%s\" does not have a flash unit", id.string());
2368 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002369 ALOGE("%s: getting current torch status failed for camera %s",
2370 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002371 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2372 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
2373 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002374 }
2375
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002376 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002377 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002378 ALOGE("%s: torch mode of camera %s is not available because "
2379 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002380 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2381 "Torch for camera \"%s\" is not available due to an existing camera user",
2382 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002383 } else {
2384 ALOGE("%s: torch mode of camera %s is not available due to "
2385 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002386 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2387 "Torch for camera \"%s\" is not available due to insufficient resources",
2388 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002389 }
2390 }
2391 }
2392
Ruben Brunk99e69712015-05-26 17:25:07 -07002393 {
2394 // Update UID map - this is used in the torch status changed callbacks, so must be done
2395 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002396 Mutex::Autolock al(mTorchUidMapMutex);
Rucha Katakwar38284522021-11-10 11:25:21 -08002397 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07002398 }
2399
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002400 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002401
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002402 if (err != OK) {
2403 int32_t errorCode;
2404 String8 msg;
2405 switch (err) {
2406 case -ENOSYS:
2407 msg = String8::format("Camera \"%s\" has no flashlight",
2408 id.string());
2409 errorCode = ERROR_ILLEGAL_ARGUMENT;
2410 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08002411 case -EBUSY:
2412 msg = String8::format("Camera \"%s\" is in use",
2413 id.string());
2414 errorCode = ERROR_CAMERA_IN_USE;
2415 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002416 default:
2417 msg = String8::format(
2418 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
2419 id.string(), enabled, strerror(-err), err);
2420 errorCode = ERROR_INVALID_OPERATION;
2421 }
2422 ALOGE("%s: %s", __FUNCTION__, msg.string());
Rucha Katakward9ea6452021-05-06 11:57:16 -07002423 logServiceError(msg,errorCode);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002424 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002425 }
2426
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002427 {
2428 // update the link to client's death
2429 Mutex::Autolock al(mTorchClientMapMutex);
2430 ssize_t index = mTorchClientMap.indexOfKey(id);
2431 if (enabled) {
2432 if (index == NAME_NOT_FOUND) {
2433 mTorchClientMap.add(id, clientBinder);
2434 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07002435 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002436 mTorchClientMap.replaceValueAt(index, clientBinder);
2437 }
2438 clientBinder->linkToDeath(this);
2439 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07002440 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002441 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002442 }
2443
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002444 int clientPid = CameraThreadState::getCallingPid();
2445 const char *id_cstr = id.c_str();
2446 const char *torchState = enabled ? "on" : "off";
2447 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
2448 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002449 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002450}
2451
Rucha Katakwar38284522021-11-10 11:25:21 -08002452void CameraService::updateTorchUidMapLocked(const String16& cameraId, int uid) {
2453 String8 id = String8(cameraId.string());
2454 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
2455 mTorchUidMap[id].first = uid;
2456 mTorchUidMap[id].second = uid;
2457 } else {
2458 // Set the pending UID
2459 mTorchUidMap[id].first = uid;
2460 }
2461}
2462
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002463Status CameraService::notifySystemEvent(int32_t eventId,
2464 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002465 const int pid = CameraThreadState::getCallingPid();
2466 const int selfPid = getpid();
2467
2468 // Permission checks
2469 if (pid != selfPid) {
2470 // Ensure we're being called by system_server, or similar process with
2471 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002472 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002473 const int uid = CameraThreadState::getCallingUid();
2474 ALOGE("Permission Denial: cannot send updates to camera service about system"
2475 " events from pid=%d, uid=%d", pid, uid);
2476 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09002477 "No permission to send updates to camera service about system events"
2478 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002479 }
2480 }
2481
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002482 ATRACE_CALL();
2483
Ruben Brunk36597b22015-03-20 22:15:57 -07002484 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002485 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002486 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002487 // from a system server crash
2488 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002489 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002490 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002491 break;
2492 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02002493 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
2494 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
2495 // Notify CameraProviderManager for lazy HALs
2496 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
2497 std::to_string(args[0]));
2498 break;
2499 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002500 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002501 default: {
2502 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2503 eventId);
2504 break;
2505 }
2506 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002507 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002508}
2509
Emilian Peev53722fa2019-02-22 17:47:20 -08002510void CameraService::notifyMonitoredUids() {
2511 Mutex::Autolock lock(mStatusListenerLock);
2512
2513 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002514 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07002515 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
2516 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08002517 }
2518}
2519
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002520Status CameraService::notifyDeviceStateChange(int64_t newState) {
2521 const int pid = CameraThreadState::getCallingPid();
2522 const int selfPid = getpid();
2523
2524 // Permission checks
2525 if (pid != selfPid) {
2526 // Ensure we're being called by system_server, or similar process with
2527 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002528 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002529 const int uid = CameraThreadState::getCallingUid();
2530 ALOGE("Permission Denial: cannot send updates to camera service about device"
2531 " state changes from pid=%d, uid=%d", pid, uid);
2532 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2533 "No permission to send updates to camera service about device state"
2534 " changes from pid=%d, uid=%d", pid, uid);
2535 }
2536 }
2537
2538 ATRACE_CALL();
2539
Austin Borger18b30a72022-10-27 12:20:29 -07002540 {
2541 Mutex::Autolock lock(mServiceLock);
2542 mDeviceState = newState;
2543 }
2544
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07002545 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002546
2547 return Status::ok();
2548}
2549
Emilian Peev8b64f282021-03-25 16:49:57 -07002550Status CameraService::notifyDisplayConfigurationChange() {
2551 ATRACE_CALL();
2552 const int callingPid = CameraThreadState::getCallingPid();
2553 const int selfPid = getpid();
2554
2555 // Permission checks
2556 if (callingPid != selfPid) {
2557 // Ensure we're being called by system_server, or similar process with
2558 // permissions to notify the camera service about system events
2559 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2560 const int uid = CameraThreadState::getCallingUid();
2561 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2562 " changes from pid=%d, uid=%d", callingPid, uid);
2563 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2564 "No permission to send updates to camera service about orientation"
2565 " changes from pid=%d, uid=%d", callingPid, uid);
2566 }
2567 }
2568
2569 Mutex::Autolock lock(mServiceLock);
2570
2571 // Don't do anything if rotate-and-crop override via cmd is active
2572 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2573
2574 const auto clients = mActiveClientManager.getAll();
2575 for (auto& current : clients) {
2576 if (current != nullptr) {
2577 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07002578 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
2579 basicClient->setRotateAndCropOverride(
2580 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2581 basicClient->getPackageName(),
2582 basicClient->getCameraFacing(),
2583 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07002584 }
2585 }
2586 }
2587
2588 return Status::ok();
2589}
2590
2591Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002592 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2593 ATRACE_CALL();
2594 if (!concurrentCameraIds) {
2595 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2596 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2597 }
2598
2599 if (!mInitialized) {
2600 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002601 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002602 return STATUS_ERROR(ERROR_DISCONNECTED,
2603 "Camera subsystem is not available");
2604 }
2605 // First call into the provider and get the set of concurrent camera
2606 // combinations
2607 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002608 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002609 for (auto &combination : concurrentCameraCombinations) {
2610 std::vector<std::string> validCombination;
2611 for (auto &cameraId : combination) {
2612 // if the camera state is not present, skip
2613 String8 cameraIdStr(cameraId.c_str());
2614 auto state = getCameraState(cameraIdStr);
2615 if (state == nullptr) {
2616 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2617 continue;
2618 }
2619 StatusInternal status = state->getStatus();
2620 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2621 continue;
2622 }
2623 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2624 continue;
2625 }
2626 validCombination.push_back(cameraId);
2627 }
2628 if (validCombination.size() != 0) {
2629 concurrentCameraIds->push_back(std::move(validCombination));
2630 }
2631 }
2632 return Status::ok();
2633}
2634
2635Status CameraService::isConcurrentSessionConfigurationSupported(
2636 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002637 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002638 if (!isSupported) {
2639 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2640 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2641 }
2642
2643 if (!mInitialized) {
2644 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2645 return STATUS_ERROR(ERROR_DISCONNECTED,
2646 "Camera subsystem is not available");
2647 }
2648
2649 // Check for camera permissions
2650 int callingPid = CameraThreadState::getCallingPid();
2651 int callingUid = CameraThreadState::getCallingUid();
2652 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2653 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2654 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2655 "android.permission.CAMERA needed to call"
2656 "isConcurrentSessionConfigurationSupported");
2657 }
2658
2659 status_t res =
2660 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002661 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
2662 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002663 if (res != OK) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07002664 logServiceError(String8::format("Unable to query session configuration support"),
2665 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002666 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2667 "support %s (%d)", strerror(-res), res);
2668 }
2669 return Status::ok();
2670}
2671
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002672Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2673 /*out*/
2674 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002675 return addListenerHelper(listener, cameraStatuses);
2676}
2677
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002678binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2679 std::vector<hardware::CameraStatus>* cameraStatuses) {
2680 return addListenerHelper(listener, cameraStatuses, false, true);
2681}
2682
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002683Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2684 /*out*/
2685 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002686 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002687
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002688 ATRACE_CALL();
2689
Igor Murashkinbfc99152013-02-27 12:55:20 -08002690 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002691
Ruben Brunk3450ba72015-06-16 11:00:37 -07002692 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002693 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002694 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002695 }
2696
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002697 auto clientUid = CameraThreadState::getCallingUid();
2698 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002699 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
Jayant Chowdharyc3198c32021-07-28 20:59:14 +00002700 clientPid, clientUid, /*logPermissionFailure*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002701
Igor Murashkinbfc99152013-02-27 12:55:20 -08002702 Mutex::Autolock lock(mServiceLock);
2703
Ruben Brunkcc776712015-02-17 20:18:47 -08002704 {
2705 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002706 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002707 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002708 ALOGW("%s: Tried to add listener %p which was already subscribed",
2709 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002710 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002711 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002712 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002713
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002714 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002715 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2716 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002717 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08002718 if (ret != NO_ERROR) {
2719 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2720 strerror(-ret), ret);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002721 logServiceError(msg,ERROR_ILLEGAL_ARGUMENT);
Emilian Peev53722fa2019-02-22 17:47:20 -08002722 ALOGE("%s: %s", __FUNCTION__, msg.string());
2723 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2724 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002725 // The listener still needs to be added to the list of listeners, regardless of what
2726 // permissions the listener process has / whether it is a vendor listener. Since it might be
2727 // eligible to listen to other camera ids.
2728 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002729 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002730 }
2731
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002732 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002733 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002734 Mutex::Autolock lock(mCameraStatesLock);
2735 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002736 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07002737 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
2738 openCloseCallbackAllowed ? i.second->getClientPackage() : String8::empty());
Igor Murashkincba2c162013-03-20 15:56:31 -07002739 }
2740 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002741 // Remove the camera statuses that should be hidden from the client, we do
2742 // this after collecting the states in order to avoid holding
2743 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2744 // the same time.
2745 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2746 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2747 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2748 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2749 ALOGE("%s: Invalid camera id %s, skipping status update",
2750 __FUNCTION__, s.cameraId.c_str());
2751 return true;
2752 }
2753 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2754 clientUid);}), cameraStatuses->end());
2755
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002756 //cameraStatuses will have non-eligible camera ids removed.
2757 std::set<String16> idsChosenForCallback;
2758 for (const auto &s : *cameraStatuses) {
2759 idsChosenForCallback.insert(String16(s.cameraId));
2760 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002761
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002762 /*
2763 * Immediately signal current torch status to this listener only
2764 * This may be a subset of all the devices, so don't include it in the response directly
2765 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002766 {
2767 Mutex::Autolock al(mTorchStatusMutex);
2768 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002769 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002770 // The camera id is visible to the client. Fine to send torch
2771 // callback.
2772 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2773 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2774 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002775 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002776 }
2777
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002778 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002779}
Ruben Brunkcc776712015-02-17 20:18:47 -08002780
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002781Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002782 ATRACE_CALL();
2783
Igor Murashkinbfc99152013-02-27 12:55:20 -08002784 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2785
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002786 if (listener == 0) {
2787 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002788 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002789 }
2790
Igor Murashkinbfc99152013-02-27 12:55:20 -08002791 Mutex::Autolock lock(mServiceLock);
2792
Ruben Brunkcc776712015-02-17 20:18:47 -08002793 {
2794 Mutex::Autolock lock(mStatusListenerLock);
2795 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002796 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2797 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2798 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002799 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002800 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002801 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002802 }
2803 }
2804
2805 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2806 __FUNCTION__, listener.get());
2807
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002808 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002809}
2810
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002811Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002812
2813 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002814 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2815
2816 if (parameters == NULL) {
2817 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002818 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002819 }
2820
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002821 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002822
2823 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002824 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002825 // Error logged by caller
2826 return ret;
2827 }
2828
2829 String8 shimParamsString8 = shimParams.flatten();
2830 String16 shimParamsString16 = String16(shimParamsString8);
2831
2832 *parameters = shimParamsString16;
2833
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002834 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002835}
2836
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002837Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2838 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002839 ATRACE_CALL();
2840
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002841 const String8 id = String8(cameraId);
2842
2843 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002844
2845 switch (apiVersion) {
2846 case API_VERSION_1:
2847 case API_VERSION_2:
2848 break;
2849 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002850 String8 msg = String8::format("Unknown API version %d", apiVersion);
2851 ALOGE("%s: %s", __FUNCTION__, msg.string());
2852 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002853 }
2854
Austin Borger18b30a72022-10-27 12:20:29 -07002855 int portraitRotation;
2856 auto deviceVersionAndTransport = getDeviceVersion(id, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002857 if (deviceVersionAndTransport.first == -1) {
2858 String8 msg = String8::format("Unknown camera ID %s", id.string());
2859 ALOGE("%s: %s", __FUNCTION__, msg.string());
2860 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2861 }
2862 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
2863 int deviceVersion = deviceVersionAndTransport.first;
2864 switch (deviceVersion) {
2865 case CAMERA_DEVICE_API_VERSION_1_0:
2866 case CAMERA_DEVICE_API_VERSION_3_0:
2867 case CAMERA_DEVICE_API_VERSION_3_1:
2868 if (apiVersion == API_VERSION_2) {
2869 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
2870 "shim", __FUNCTION__, id.string(), deviceVersion);
2871 *isSupported = false;
2872 } else { // if (apiVersion == API_VERSION_1) {
2873 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
2874 "supported", __FUNCTION__, id.string());
2875 *isSupported = true;
2876 }
2877 break;
2878 case CAMERA_DEVICE_API_VERSION_3_2:
2879 case CAMERA_DEVICE_API_VERSION_3_3:
2880 case CAMERA_DEVICE_API_VERSION_3_4:
2881 case CAMERA_DEVICE_API_VERSION_3_5:
2882 case CAMERA_DEVICE_API_VERSION_3_6:
2883 case CAMERA_DEVICE_API_VERSION_3_7:
2884 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002885 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002886 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002887 break;
2888 default: {
2889 String8 msg = String8::format("Unknown device version %x for device %s",
2890 deviceVersion, id.string());
2891 ALOGE("%s: %s", __FUNCTION__, msg.string());
2892 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002893 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002894 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002895 } else {
2896 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002897 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002898 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002899}
2900
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002901Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2902 /*out*/ bool *isSupported) {
2903 ATRACE_CALL();
2904
2905 const String8 id = String8(cameraId);
2906
2907 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2908 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2909
2910 return Status::ok();
2911}
2912
Cliff Wud8cae102021-03-11 01:37:42 +08002913Status CameraService::injectCamera(
2914 const String16& packageName, const String16& internalCamId,
2915 const String16& externalCamId,
2916 const sp<ICameraInjectionCallback>& callback,
2917 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08002918 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08002919 ATRACE_CALL();
2920
2921 if (!checkCallingPermission(sCameraInjectExternalCameraPermission)) {
2922 const int pid = CameraThreadState::getCallingPid();
2923 const int uid = CameraThreadState::getCallingUid();
2924 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
2925 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2926 "Permission Denial: no permission to inject camera");
2927 }
2928
2929 ALOGV(
2930 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
2931 "%s",
2932 __FUNCTION__, String8(packageName).string(),
2933 String8(internalCamId).string(), String8(externalCamId).string());
2934
Cliff Wud3a05312021-04-26 23:07:31 +08002935 {
2936 Mutex::Autolock lock(mInjectionParametersLock);
2937 mInjectionInternalCamId = String8(internalCamId);
2938 mInjectionExternalCamId = String8(externalCamId);
Cliff Wu646bd612021-11-23 23:21:29 +08002939 mInjectionStatusListener->addListener(callback);
2940 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08002941 status_t res = NO_ERROR;
2942 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2943 // If the client already exists, we can directly connect to the camera device through the
2944 // client's injectCamera(), otherwise we need to wait until the client is established
2945 // (execute connectHelper()) before injecting the camera to the camera device.
2946 if (clientDescriptor != nullptr) {
2947 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08002948 sp<BasicClient> clientSp = clientDescriptor->getValue();
2949 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2950 if(res != OK) {
2951 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2952 "No camera device with ID \"%s\" currently available",
2953 mInjectionExternalCamId.string());
2954 }
2955 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002956 if(res != OK) {
2957 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2958 }
2959 } else {
2960 mInjectionInitPending = true;
2961 }
2962 }
Cliff Wud8cae102021-03-11 01:37:42 +08002963
Cliff Wud3a05312021-04-26 23:07:31 +08002964 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08002965}
2966
Ruben Brunkcc776712015-02-17 20:18:47 -08002967void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002968 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002969 for (auto& i : mActiveClientManager.getAll()) {
2970 auto clientSp = i->getValue();
2971 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002972 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08002973 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002974 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002975 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002976 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002977}
2978
Ruben Brunkcc776712015-02-17 20:18:47 -08002979bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002980 bool ret = false;
2981 {
2982 // Acquire mServiceLock and prevent other clients from connecting
2983 std::unique_ptr<AutoConditionLock> lock =
2984 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002985
Igor Murashkin634a5152013-02-20 17:15:11 -08002986
Ruben Brunkcc776712015-02-17 20:18:47 -08002987 std::vector<sp<BasicClient>> evicted;
2988 for (auto& i : mActiveClientManager.getAll()) {
2989 auto clientSp = i->getValue();
2990 if (clientSp.get() == nullptr) {
2991 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2992 mActiveClientManager.remove(i);
2993 continue;
2994 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002995 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002996 mActiveClientManager.remove(i);
2997 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002998
Ruben Brunkcc776712015-02-17 20:18:47 -08002999 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003000 clientSp->notifyError(
3001 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003002 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003003 }
3004 }
3005
Ruben Brunkcc776712015-02-17 20:18:47 -08003006 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3007 // other clients from connecting in mServiceLockWrapper if held
3008 mServiceLock.unlock();
3009
Ruben Brunk36597b22015-03-20 22:15:57 -07003010 // Do not clear caller identity, remote caller should be client proccess
3011
Ruben Brunkcc776712015-02-17 20:18:47 -08003012 for (auto& i : evicted) {
3013 if (i.get() != nullptr) {
3014 i->disconnect();
3015 ret = true;
3016 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003017 }
3018
Ruben Brunkcc776712015-02-17 20:18:47 -08003019 // Reacquire mServiceLock
3020 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003021
Ruben Brunkcc776712015-02-17 20:18:47 -08003022 } // lock is destroyed, allow further connect calls
3023
3024 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003025}
3026
Ruben Brunkcc776712015-02-17 20:18:47 -08003027std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
3028 const String8& cameraId) const {
3029 std::shared_ptr<CameraState> state;
3030 {
3031 Mutex::Autolock lock(mCameraStatesLock);
3032 auto iter = mCameraStates.find(cameraId);
3033 if (iter != mCameraStates.end()) {
3034 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003035 }
3036 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003037 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003038}
3039
Ruben Brunkcc776712015-02-17 20:18:47 -08003040sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
3041 // Remove from active clients list
3042 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3043 if (clientDescriptorPtr == nullptr) {
3044 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
3045 cameraId.string());
3046 return sp<BasicClient>{nullptr};
3047 }
3048
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003049 sp<BasicClient> client = clientDescriptorPtr->getValue();
3050 if (client.get() != nullptr) {
3051 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3052 }
3053 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003054}
3055
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003056void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003057 // Acquire mServiceLock and prevent other clients from connecting
3058 std::unique_ptr<AutoConditionLock> lock =
3059 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3060
Ruben Brunk6267b532015-04-30 17:44:07 -07003061 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003062 for (size_t i = 0; i < newUserIds.size(); i++) {
3063 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003064 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003065 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003066 return;
3067 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003068 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003069 }
3070
Ruben Brunka8ca9152015-04-07 14:23:40 -07003071
Ruben Brunk6267b532015-04-30 17:44:07 -07003072 if (newAllowedUsers == mAllowedUsers) {
3073 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3074 return;
3075 }
3076
3077 logUserSwitch(mAllowedUsers, newAllowedUsers);
3078
3079 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003080
3081 // Current user has switched, evict all current clients.
3082 std::vector<sp<BasicClient>> evicted;
3083 for (auto& i : mActiveClientManager.getAll()) {
3084 auto clientSp = i->getValue();
3085
3086 if (clientSp.get() == nullptr) {
3087 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3088 continue;
3089 }
3090
Ruben Brunk6267b532015-04-30 17:44:07 -07003091 // Don't evict clients that are still allowed.
3092 uid_t clientUid = clientSp->getClientUid();
3093 userid_t clientUserId = multiuser_get_user_id(clientUid);
3094 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3095 continue;
3096 }
3097
Ruben Brunk36597b22015-03-20 22:15:57 -07003098 evicted.push_back(clientSp);
3099
3100 String8 curTime = getFormattedCurrentTime();
3101
3102 ALOGE("Evicting conflicting client for camera ID %s due to user change",
3103 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003104
Ruben Brunk36597b22015-03-20 22:15:57 -07003105 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07003106 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003107 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
3108 " to user switch.", i->getKey().string(),
3109 String8{clientSp->getPackageName()}.string(),
3110 i->getOwnerId(), i->getPriority().getScore(),
3111 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003112
3113 }
3114
3115 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3116 // blocking other clients from connecting in mServiceLockWrapper if held.
3117 mServiceLock.unlock();
3118
3119 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07003120 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003121
3122 for (auto& i : evicted) {
3123 i->disconnect();
3124 }
3125
Jayant Chowdhary12361932018-08-27 14:46:13 -07003126 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003127
3128 // Reacquire mServiceLock
3129 mServiceLock.lock();
3130}
Ruben Brunkcc776712015-02-17 20:18:47 -08003131
Ruben Brunka8ca9152015-04-07 14:23:40 -07003132void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003133 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003134 Mutex::Autolock l(mLogLock);
Rucha Katakward9ea6452021-05-06 11:57:16 -07003135 String8 msg = String8::format("%s : %s", curTime.string(), event);
3136 // For service error events, print the msg only once.
3137 if(!msg.contains("SERVICE ERROR")) {
3138 mEventLog.add(msg);
3139 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3140 // Error event not added to the dumpsys log before
3141 mEventLog.add(msg);
3142 sServiceErrorEventSet.insert(msg);
3143 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003144}
3145
Ruben Brunka8ca9152015-04-07 14:23:40 -07003146void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003147 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003148 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07003149 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003150 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003151}
3152
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003153void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
3154 const char* clientPackage) {
3155 // Log the clients evicted
3156 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
3157 cameraId, clientPackage, clientPid));
3158}
3159
Ruben Brunka8ca9152015-04-07 14:23:40 -07003160void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003161 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003162 // Log the clients evicted
3163 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003164 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003165}
3166
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003167void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
3168 const char* clientPackage) {
3169 // Log the clients evicted
3170 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
3171 clientPackage, clientPid));
3172}
3173
Ruben Brunka8ca9152015-04-07 14:23:40 -07003174void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003175 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003176 // Log the client rejected
3177 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003178 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003179}
3180
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003181void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
3182 // Log torch event
3183 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
3184 torchState, clientPid));
3185}
3186
Ruben Brunk6267b532015-04-30 17:44:07 -07003187void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3188 const std::set<userid_t>& newUserIds) {
3189 String8 newUsers = toString(newUserIds);
3190 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003191 if (oldUsers.size() == 0) {
3192 oldUsers = "<None>";
3193 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003194 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003195 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07003196 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003197}
3198
3199void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
3200 // Log the device removal
3201 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
3202}
3203
3204void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
3205 // Log the device removal
3206 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
3207}
3208
3209void CameraService::logClientDied(int clientPid, const char* reason) {
3210 // Log the device removal
3211 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003212}
3213
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003214void CameraService::logServiceError(const char* msg, int errorCode) {
3215 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003216 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003217}
3218
Ruben Brunk36597b22015-03-20 22:15:57 -07003219status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3220 uint32_t flags) {
3221
Mathias Agopian65ab4712010-07-14 17:59:35 -07003222 // Permission checks
3223 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003224 case SHELL_COMMAND_TRANSACTION: {
3225 int in = data.readFileDescriptor();
3226 int out = data.readFileDescriptor();
3227 int err = data.readFileDescriptor();
3228 int argc = data.readInt32();
3229 Vector<String16> args;
3230 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3231 args.add(data.readString16());
3232 }
3233 sp<IBinder> unusedCallback;
3234 sp<IResultReceiver> resultReceiver;
3235 status_t status;
3236 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3237 return status;
3238 }
3239 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3240 return status;
3241 }
3242 status = shellCommand(in, out, err, args);
3243 if (resultReceiver != nullptr) {
3244 resultReceiver->send(status);
3245 }
3246 return NO_ERROR;
3247 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003248 }
3249
3250 return BnCameraService::onTransact(code, data, reply, flags);
3251}
3252
Mathias Agopian65ab4712010-07-14 17:59:35 -07003253// We share the media players for shutter and recording sound for all clients.
3254// A reference count is kept to determine when we will actually release the
3255// media players.
3256
Jaekyun Seokef498052018-03-23 13:09:44 +09003257sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3258 sp<MediaPlayer> mp = new MediaPlayer();
3259 status_t error;
3260 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003261 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003262 error = mp->prepare();
3263 }
3264 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003265 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003266 mp->disconnect();
3267 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003268 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003269 }
3270 return mp;
3271}
3272
username5755fea2018-12-27 09:48:08 +08003273void CameraService::increaseSoundRef() {
3274 Mutex::Autolock lock(mSoundLock);
3275 mSoundRef++;
3276}
3277
3278void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003279 ATRACE_CALL();
3280
username5755fea2018-12-27 09:48:08 +08003281 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3282 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3283 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3284 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3285 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3286 }
3287 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3288 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3289 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3290 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003291 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003292 }
3293 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3294 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3295 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3296 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3297 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003298 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003299}
3300
username5755fea2018-12-27 09:48:08 +08003301void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003302 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003303 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003304 if (--mSoundRef) return;
3305
3306 for (int i = 0; i < NUM_SOUNDS; i++) {
3307 if (mSoundPlayer[i] != 0) {
3308 mSoundPlayer[i]->disconnect();
3309 mSoundPlayer[i].clear();
3310 }
3311 }
3312}
3313
3314void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003315 ATRACE_CALL();
3316
Mathias Agopian65ab4712010-07-14 17:59:35 -07003317 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07003318 if (kind < 0 || kind >= NUM_SOUNDS) {
3319 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
3320 return;
3321 }
3322
Mathias Agopian65ab4712010-07-14 17:59:35 -07003323 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003324 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003325 sp<MediaPlayer> player = mSoundPlayer[kind];
3326 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08003327 player->seekTo(0);
3328 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003329 }
3330}
3331
3332// ----------------------------------------------------------------------------
3333
3334CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07003335 const sp<ICameraClient>& cameraClient,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003336 const String16& clientPackageName, bool systemNativeClient,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003337 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003338 const String8& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003339 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003340 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003341 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003342 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003343 IInterface::asBinder(cameraClient),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003344 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003345 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003346 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003347 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003348 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003349{
Jayant Chowdhary12361932018-08-27 14:46:13 -07003350 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003351 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003352
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003353 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003354
username5755fea2018-12-27 09:48:08 +08003355 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003356
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003357 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003358}
3359
Mathias Agopian65ab4712010-07-14 17:59:35 -07003360// tear down the client
3361CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003362 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08003363 mDestructionStarted = true;
3364
username5755fea2018-12-27 09:48:08 +08003365 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003366 // unconditionally disconnect. function is idempotent
3367 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003368}
3369
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003370sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
3371
Igor Murashkin634a5152013-02-20 17:15:11 -08003372CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003373 const sp<IBinder>& remoteCallback,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003374 const String16& clientPackageName, bool nativeClient,
3375 const std::optional<String16>& clientFeatureId, const String8& cameraIdStr,
3376 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003377 int servicePid, bool overrideToPortrait):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003378 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07003379 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003380 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
3381 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003382 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003383 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07003384 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07003385 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003386 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003387 mRemoteBinder(remoteCallback),
3388 mOpsActive(false),
3389 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08003390{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003391 if (sCameraService == nullptr) {
3392 sCameraService = cameraService;
3393 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08003394
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003395 // There are 2 scenarios in which a client won't have AppOps operations
3396 // (both scenarios : native clients)
3397 // 1) It's an system native client*, the package name will be empty
3398 // and it will return from this function in the previous if condition
3399 // (This is the same as the previously existing behavior).
3400 // 2) It is a system native client, but its package name has been
3401 // modified for debugging, however it still must not use AppOps since
3402 // the package name is not a real one.
3403 //
3404 // * system native client - native client with UID < AID_APP_START. It
3405 // doesn't exclude clients not on the system partition.
3406 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003407 mAppOpsManager = std::make_unique<AppOpsManager>();
3408 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07003409
3410 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08003411}
3412
3413CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003414 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08003415 mDestructionStarted = true;
3416}
3417
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003418binder::Status CameraService::BasicClient::disconnect() {
3419 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003420 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003421 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07003422 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07003423 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08003424
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003425 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003426 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07003427 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
3428 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003429
3430 sp<IBinder> remote = getRemote();
3431 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003432 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08003433 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003434
3435 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07003436 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003437 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
3438 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
3439 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003440
Igor Murashkincba2c162013-03-20 15:56:31 -07003441 // client shouldn't be able to call into us anymore
3442 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003443
3444 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08003445}
3446
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003447status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
3448 // No dumping of clients directly over Binder,
3449 // must go through CameraService::dump
3450 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003451 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003452 return OK;
3453}
3454
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07003455status_t CameraService::BasicClient::startWatchingTags(const String8&, int) {
3456 // Can't watch tags directly, must go through CameraService::startWatchingTags
3457 return OK;
3458}
3459
3460status_t CameraService::BasicClient::stopWatchingTags(int) {
3461 // Can't watch tags directly, must go through CameraService::stopWatchingTags
3462 return OK;
3463}
3464
3465status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
3466 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
3467 return OK;
3468}
3469
Ruben Brunkcc776712015-02-17 20:18:47 -08003470String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003471 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08003472}
3473
Emilian Peev8b64f282021-03-25 16:49:57 -07003474int CameraService::BasicClient::getCameraFacing() const {
3475 return mCameraFacing;
3476}
3477
3478int CameraService::BasicClient::getCameraOrientation() const {
3479 return mOrientation;
3480}
Ruben Brunkcc776712015-02-17 20:18:47 -08003481
3482int CameraService::BasicClient::getClientPid() const {
3483 return mClientPid;
3484}
3485
Ruben Brunk6267b532015-04-30 17:44:07 -07003486uid_t CameraService::BasicClient::getClientUid() const {
3487 return mClientUid;
3488}
3489
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003490bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
3491 // Defaults to API2.
3492 return level == API_2;
3493}
3494
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003495status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003496 {
3497 Mutex::Autolock l(mAudioRestrictionLock);
3498 mAudioRestriction = mode;
3499 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003500 sCameraService->updateAudioRestriction();
3501 return OK;
3502}
3503
3504int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003505 return sCameraService->updateAudioRestriction();
3506}
3507
3508int32_t CameraService::BasicClient::getAudioRestriction() const {
3509 Mutex::Autolock l(mAudioRestrictionLock);
3510 return mAudioRestriction;
3511}
3512
3513bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
3514 switch (mode) {
3515 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
3516 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
3517 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
3518 return true;
3519 default:
3520 return false;
3521 }
3522}
3523
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003524status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
3525 if (mode == AppOpsManager::MODE_ERRORED) {
3526 ALOGI("Camera %s: Access for \"%s\" has been revoked",
3527 mCameraIdStr.string(), String8(mClientPackageName).string());
3528 return PERMISSION_DENIED;
3529 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
3530 // If the calling Uid is trusted (a native service), the AppOpsManager could
3531 // return MODE_IGNORED. Do not treat such case as error.
3532 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
3533 mClientPackageName);
3534 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08003535 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003536 if (!isUidActive || !isCameraPrivacyEnabled) {
3537 ALOGI("Camera %s: Access for \"%s\" has been restricted",
3538 mCameraIdStr.string(), String8(mClientPackageName).string());
3539 // Return the same error as for device policy manager rejection
3540 return -EACCES;
3541 }
3542 }
3543 return OK;
3544}
3545
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003546status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003547 ATRACE_CALL();
3548
Igor Murashkine6800ce2013-03-04 17:25:57 -08003549 {
3550 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003551 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003552 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003553 if (mAppOpsManager != nullptr) {
3554 // Notify app ops that the camera is not available
3555 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003556 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
3557 mClientPackageName, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003558
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003559 // Just check for camera acccess here on open - delay startOp until
3560 // camera frames start streaming in startCameraStreamingOps
3561 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
3562 mClientPackageName);
3563 status_t res = handleAppOpMode(mode);
3564 if (res != OK) {
3565 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003566 }
Svetoslav28e8ef72015-05-11 19:21:31 -07003567 }
3568
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003569 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003570
3571 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003572 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003573
Emilian Peev53722fa2019-02-22 17:47:20 -08003574 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
3575
Shuzhen Wang695044d2020-03-06 09:02:23 -08003576 // Notify listeners of camera open/close status
3577 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
3578
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003579 return OK;
3580}
3581
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003582status_t CameraService::BasicClient::startCameraStreamingOps() {
3583 ATRACE_CALL();
3584
3585 if (!mOpsActive) {
3586 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3587 return INVALID_OPERATION;
3588 }
3589 if (mOpsStreaming) {
3590 ALOGV("%s: Streaming already active!", __FUNCTION__);
3591 return OK;
3592 }
3593
3594 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
3595 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3596
3597 if (mAppOpsManager != nullptr) {
3598 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
3599 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
3600 String16("start camera ") + String16(mCameraIdStr));
3601 status_t res = handleAppOpMode(mode);
3602 if (res != OK) {
3603 return res;
3604 }
3605 }
3606
3607 mOpsStreaming = true;
3608
3609 return OK;
3610}
3611
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003612status_t CameraService::BasicClient::noteAppOp() {
3613 ATRACE_CALL();
3614
3615 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
3616 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3617
3618 // noteAppOp is only used for when camera mute is not supported, in order
3619 // to trigger the sensor privacy "Unblock" dialog
3620 if (mAppOpsManager != nullptr) {
3621 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
3622 mClientPackageName, mClientFeatureId,
3623 String16("start camera ") + String16(mCameraIdStr));
3624 status_t res = handleAppOpMode(mode);
3625 if (res != OK) {
3626 return res;
3627 }
3628 }
3629
3630 return OK;
3631}
3632
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003633status_t CameraService::BasicClient::finishCameraStreamingOps() {
3634 ATRACE_CALL();
3635
3636 if (!mOpsActive) {
3637 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3638 return INVALID_OPERATION;
3639 }
3640 if (!mOpsStreaming) {
3641 ALOGV("%s: Streaming not active!", __FUNCTION__);
3642 return OK;
3643 }
3644
3645 if (mAppOpsManager != nullptr) {
3646 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
3647 mClientPackageName, mClientFeatureId);
3648 mOpsStreaming = false;
3649 }
3650
3651 return OK;
3652}
3653
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003654status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003655 ATRACE_CALL();
3656
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003657 if (mOpsStreaming) {
3658 // Make sure we've notified everyone about camera stopping
3659 finishCameraStreamingOps();
3660 }
3661
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003662 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003663 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003664 mOpsActive = false;
3665
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003666 // This function is called when a client disconnects. This should
3667 // release the camera, but actually only if it was in a proper
3668 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003669 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003670 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003671
Ruben Brunkcc776712015-02-17 20:18:47 -08003672 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003673 sCameraService->updateStatus(StatusInternal::PRESENT,
3674 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003675 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003676 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003677 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3678 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003679 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003680 mOpsCallback.clear();
3681
Emilian Peev53722fa2019-02-22 17:47:20 -08003682 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3683
Shuzhen Wang695044d2020-03-06 09:02:23 -08003684 // Notify listeners of camera open/close status
3685 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3686
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003687 return OK;
3688}
3689
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003690void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003691 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003692 if (mAppOpsManager == nullptr) {
3693 return;
3694 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003695 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003696 if (op != AppOpsManager::OP_CAMERA) {
3697 ALOGW("Unexpected app ops notification received: %d", op);
3698 return;
3699 }
3700
3701 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003702 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003703 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003704 ALOGV("checkOp returns: %d, %s ", res,
3705 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3706 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3707 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3708 "UNKNOWN");
3709
Shuzhen Wang64900852021-02-05 09:03:29 -08003710 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003711 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003712 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003713 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003714 } else if (res == AppOpsManager::MODE_IGNORED) {
3715 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08003716 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08003717 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Shuzhen Wang64900852021-02-05 09:03:29 -08003718 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3719 mCameraIdStr.string(), String8(mClientPackageName).string(),
3720 mUidIsTrusted, isUidActive);
3721 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3722 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3723 // error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003724 if (!mUidIsTrusted) {
3725 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
3726 setCameraMute(true);
3727 } else if (!isUidActive
3728 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
3729 block();
3730 }
Shuzhen Wang64900852021-02-05 09:03:29 -08003731 }
Evan Severson09ab4002021-02-10 14:15:19 -08003732 } else if (res == AppOpsManager::MODE_ALLOWED) {
3733 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003734 }
3735}
3736
Svet Ganova453d0d2018-01-11 15:37:58 -08003737void CameraService::BasicClient::block() {
3738 ATRACE_CALL();
3739
3740 // Reset the client PID to allow server-initiated disconnect,
3741 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003742 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003743 CaptureResultExtras resultExtras; // a dummy result (invalid)
3744 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3745 disconnect();
3746}
3747
Mathias Agopian65ab4712010-07-14 17:59:35 -07003748// ----------------------------------------------------------------------------
3749
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003750void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003751 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003752 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003753 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003754 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3755 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3756 api1ErrorCode = CAMERA_ERROR_DISABLED;
3757 }
3758 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003759 } else {
3760 ALOGE("mRemoteCallback is NULL!!");
3761 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003762}
3763
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003764// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003765binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003766 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003767 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003768}
3769
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003770bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3771 return level == API_1;
3772}
3773
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003774CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3775 mClient(client) {
3776}
3777
3778void CameraService::Client::OpsCallback::opChanged(int32_t op,
3779 const String16& packageName) {
3780 sp<BasicClient> client = mClient.promote();
3781 if (client != NULL) {
3782 client->opChanged(op, packageName);
3783 }
3784}
3785
Mathias Agopian65ab4712010-07-14 17:59:35 -07003786// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003787// UidPolicy
3788// ----------------------------------------------------------------------------
3789
3790void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003791 Mutex::Autolock _l(mUidLock);
3792
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003793 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003794 status_t res = mAm.linkToDeath(this);
3795 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003796 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00003797 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
3798 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08003799 ActivityManager::PROCESS_STATE_UNKNOWN,
3800 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003801 if (res == OK) {
3802 mRegistered = true;
3803 ALOGV("UidPolicy: Registered with ActivityManager");
3804 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003805}
3806
3807void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003808 Mutex::Autolock _l(mUidLock);
3809
Steven Moreland2f348142019-07-02 15:59:07 -07003810 mAm.unregisterUidObserver(this);
3811 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003812 mRegistered = false;
3813 mActiveUids.clear();
3814 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003815}
3816
3817void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3818 onUidIdle(uid, disabled);
3819}
3820
3821void CameraService::UidPolicy::onUidActive(uid_t uid) {
3822 Mutex::Autolock _l(mUidLock);
3823 mActiveUids.insert(uid);
3824}
3825
3826void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3827 bool deleted = false;
3828 {
3829 Mutex::Autolock _l(mUidLock);
3830 if (mActiveUids.erase(uid) > 0) {
3831 deleted = true;
3832 }
3833 }
3834 if (deleted) {
3835 sp<CameraService> service = mService.promote();
3836 if (service != nullptr) {
3837 service->blockClientsForUid(uid);
3838 }
3839 }
3840}
3841
Emilian Peev53722fa2019-02-22 17:47:20 -08003842void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003843 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00003844 bool procStateChange = false;
3845 {
3846 Mutex::Autolock _l(mUidLock);
3847 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
3848 mMonitoredUids[uid].procState != procState) {
3849 mMonitoredUids[uid].procState = procState;
3850 procStateChange = true;
3851 }
3852 }
3853
3854 if (procStateChange) {
3855 sp<CameraService> service = mService.promote();
3856 if (service != nullptr) {
3857 service->notifyMonitoredUids();
3858 }
Emilian Peev53722fa2019-02-22 17:47:20 -08003859 }
3860}
3861
Austin Borger65577682022-02-17 00:25:43 +00003862void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid) {
3863 bool procAdjChange = false;
3864 {
3865 Mutex::Autolock _l(mUidLock);
3866 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3867 procAdjChange = true;
3868 }
3869 }
3870
3871 if (procAdjChange) {
3872 sp<CameraService> service = mService.promote();
3873 if (service != nullptr) {
3874 service->notifyMonitoredUids();
3875 }
3876 }
3877}
3878
Emilian Peev53722fa2019-02-22 17:47:20 -08003879void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3880 Mutex::Autolock _l(mUidLock);
3881 auto it = mMonitoredUids.find(uid);
3882 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00003883 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08003884 } else {
Austin Borger65577682022-02-17 00:25:43 +00003885 MonitoredUid monitoredUid;
3886 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
3887 monitoredUid.refCount = 1;
3888 mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid));
Emilian Peev53722fa2019-02-22 17:47:20 -08003889 }
3890}
3891
3892void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3893 Mutex::Autolock _l(mUidLock);
3894 auto it = mMonitoredUids.find(uid);
3895 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00003896 it->second.refCount--;
3897 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003898 mMonitoredUids.erase(it);
3899 }
3900 } else {
3901 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3902 }
3903}
3904
Svet Ganov7b4ab782018-03-25 12:48:10 -07003905bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003906 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003907 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003908}
3909
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003910static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3911static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003912
Svet Ganov7b4ab782018-03-25 12:48:10 -07003913bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003914 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003915 // If activity manager is unreachable, assume everything is active
3916 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003917 return true;
3918 }
3919 auto it = mOverrideUids.find(uid);
3920 if (it != mOverrideUids.end()) {
3921 return it->second;
3922 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003923 bool active = mActiveUids.find(uid) != mActiveUids.end();
3924 if (!active) {
3925 // We want active UIDs to always access camera with their first attempt since
3926 // there is no guarantee the app is robustly written and would retry getting
3927 // the camera on failure. The inverse case is not a problem as we would take
3928 // camera away soon once we get the callback that the uid is no longer active.
3929 ActivityManager am;
3930 // Okay to access with a lock held as UID changes are dispatched without
3931 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003932 int64_t startTimeMillis = 0;
3933 do {
3934 // TODO: Fix this b/109950150!
3935 // Okay this is a hack. There is a race between the UID turning active and
3936 // activity being resumed. The proper fix is very risky, so we temporary add
3937 // some polling which should happen pretty rarely anyway as the race is hard
3938 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003939 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003940 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003941 if (active) {
3942 break;
3943 }
3944 if (startTimeMillis <= 0) {
3945 startTimeMillis = uptimeMillis();
3946 }
3947 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003948 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003949 if (remainingTimeMillis <= 0) {
3950 break;
3951 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003952 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3953
3954 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003955 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003956 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003957 } while (true);
3958
Svet Ganov7b4ab782018-03-25 12:48:10 -07003959 if (active) {
3960 // Now that we found out the UID is actually active, cache that
3961 mActiveUids.insert(uid);
3962 }
3963 }
3964 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003965}
3966
Varun Shahb42f1eb2019-04-16 14:45:13 -07003967int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3968 Mutex::Autolock _l(mUidLock);
3969 return getProcStateLocked(uid);
3970}
3971
3972int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3973 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3974 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00003975 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07003976 }
3977 return procState;
3978}
3979
Svet Ganov7b4ab782018-03-25 12:48:10 -07003980void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3981 String16 callingPackage, bool active) {
3982 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003983}
3984
Svet Ganov7b4ab782018-03-25 12:48:10 -07003985void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3986 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003987}
3988
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003989void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3990 Mutex::Autolock _l(mUidLock);
3991 ALOGV("UidPolicy: ActivityManager has died");
3992 mRegistered = false;
3993 mActiveUids.clear();
3994}
3995
Svet Ganov7b4ab782018-03-25 12:48:10 -07003996void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3997 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003998 bool wasActive = false;
3999 bool isActive = false;
4000 {
4001 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004002 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004003 mOverrideUids.erase(uid);
4004 if (insert) {
4005 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4006 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004007 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004008 }
4009 if (wasActive != isActive && !isActive) {
4010 sp<CameraService> service = mService.promote();
4011 if (service != nullptr) {
4012 service->blockClientsForUid(uid);
4013 }
4014 }
4015}
4016
4017// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004018// SensorPrivacyPolicy
4019// ----------------------------------------------------------------------------
4020void CameraService::SensorPrivacyPolicy::registerSelf() {
4021 Mutex::Autolock _l(mSensorPrivacyLock);
4022 if (mRegistered) {
4023 return;
4024 }
Evan Severson09ab4002021-02-10 14:15:19 -08004025 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004026 mSpm.addSensorPrivacyListener(this);
4027 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
4028 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004029 if (res == OK) {
4030 mRegistered = true;
4031 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4032 }
4033}
4034
4035void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4036 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004037 mSpm.removeSensorPrivacyListener(this);
4038 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004039 mRegistered = false;
4040 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4041}
4042
4043bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
4044 Mutex::Autolock _l(mSensorPrivacyLock);
4045 return mSensorPrivacyEnabled;
4046}
4047
Evan Seversond0b69922022-01-27 10:47:34 -08004048bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004049 if (!hasCameraPrivacyFeature()) {
4050 return false;
4051 }
Evan Seversond0b69922022-01-27 10:47:34 -08004052 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004053}
4054
Evan Seversond0b69922022-01-27 10:47:34 -08004055binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
4056 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08004057 {
4058 Mutex::Autolock _l(mSensorPrivacyLock);
Kwangkyu Parke3af2992022-11-05 02:46:52 +09004059 mSensorPrivacyEnabled = enabled;
Michael Grooverd1d435a2018-12-18 17:39:42 -08004060 }
4061 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08004062 if (enabled) {
4063 sp<CameraService> service = mService.promote();
4064 if (service != nullptr) {
4065 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004066 }
4067 }
4068 return binder::Status::ok();
4069}
4070
4071void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4072 Mutex::Autolock _l(mSensorPrivacyLock);
4073 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
4074 mRegistered = false;
4075}
4076
Evan Severson09ab4002021-02-10 14:15:19 -08004077bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08004078 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
4079 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4080 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
4081 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4082 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08004083}
4084
Michael Grooverd1d435a2018-12-18 17:39:42 -08004085// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004086// CameraState
4087// ----------------------------------------------------------------------------
4088
4089CameraService::CameraState::CameraState(const String8& id, int cost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004090 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind,
4091 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004092 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004093 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08004094
4095CameraService::CameraState::~CameraState() {}
4096
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004097CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004098 Mutex::Autolock lock(mStatusLock);
4099 return mStatus;
4100}
4101
Shuzhen Wang43858162020-01-10 13:42:15 -08004102std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
4103 Mutex::Autolock lock(mStatusLock);
4104 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
4105 return res;
4106}
4107
Ruben Brunkcc776712015-02-17 20:18:47 -08004108CameraParameters CameraService::CameraState::getShimParams() const {
4109 return mShimParams;
4110}
4111
4112void CameraService::CameraState::setShimParams(const CameraParameters& params) {
4113 mShimParams = params;
4114}
4115
4116int CameraService::CameraState::getCost() const {
4117 return mCost;
4118}
4119
4120std::set<String8> CameraService::CameraState::getConflicting() const {
4121 return mConflicting;
4122}
4123
4124String8 CameraService::CameraState::getId() const {
4125 return mId;
4126}
4127
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004128SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
4129 return mSystemCameraKind;
4130}
4131
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004132bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
4133 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
4134 != mPhysicalCameras.end();
4135}
4136
Shuzhen Wang43858162020-01-10 13:42:15 -08004137bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
4138 Mutex::Autolock lock(mStatusLock);
4139 auto result = mUnavailablePhysicalIds.insert(physicalId);
4140 return result.second;
4141}
4142
4143bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
4144 Mutex::Autolock lock(mStatusLock);
4145 auto count = mUnavailablePhysicalIds.erase(physicalId);
4146 return count > 0;
4147}
4148
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004149void CameraService::CameraState::setClientPackage(const String8& clientPackage) {
4150 Mutex::Autolock lock(mStatusLock);
4151 mClientPackage = clientPackage;
4152}
4153
4154String8 CameraService::CameraState::getClientPackage() const {
4155 Mutex::Autolock lock(mStatusLock);
4156 return mClientPackage;
4157}
4158
Ruben Brunkcc776712015-02-17 20:18:47 -08004159// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07004160// ClientEventListener
4161// ----------------------------------------------------------------------------
4162
4163void CameraService::ClientEventListener::onClientAdded(
4164 const resource_policy::ClientDescriptor<String8,
4165 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004166 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004167 if (basicClient.get() != nullptr) {
4168 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4169 notifier.noteStartCamera(descriptor.getKey(),
4170 static_cast<int>(basicClient->getClientUid()));
4171 }
4172}
4173
4174void CameraService::ClientEventListener::onClientRemoved(
4175 const resource_policy::ClientDescriptor<String8,
4176 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004177 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004178 if (basicClient.get() != nullptr) {
4179 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4180 notifier.noteStopCamera(descriptor.getKey(),
4181 static_cast<int>(basicClient->getClientUid()));
4182 }
4183}
4184
4185
4186// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004187// CameraClientManager
4188// ----------------------------------------------------------------------------
4189
Ruben Brunk99e69712015-05-26 17:25:07 -07004190CameraService::CameraClientManager::CameraClientManager() {
4191 setListener(std::make_shared<ClientEventListener>());
4192}
4193
Ruben Brunkcc776712015-02-17 20:18:47 -08004194CameraService::CameraClientManager::~CameraClientManager() {}
4195
4196sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
4197 const String8& id) const {
4198 auto descriptor = get(id);
4199 if (descriptor == nullptr) {
4200 return sp<BasicClient>{nullptr};
4201 }
4202 return descriptor->getValue();
4203}
4204
4205String8 CameraService::CameraClientManager::toString() const {
4206 auto all = getAll();
4207 String8 ret("[");
4208 bool hasAny = false;
4209 for (auto& i : all) {
4210 hasAny = true;
4211 String8 key = i->getKey();
4212 int32_t cost = i->getCost();
4213 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00004214 int32_t score = i->getPriority().getScore();
4215 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08004216 auto conflicting = i->getConflicting();
4217 auto clientSp = i->getValue();
4218 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07004219 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08004220 if (clientSp.get() != nullptr) {
4221 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07004222 uid_t clientUid = clientSp->getClientUid();
4223 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004224 }
Emilian Peev8131a262017-02-01 12:33:43 +00004225 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
4226 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08004227
Ruben Brunk6267b532015-04-30 17:44:07 -07004228 if (clientSp.get() != nullptr) {
4229 ret.appendFormat("User Id: %d, ", clientUserId);
4230 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004231 if (packageName.size() != 0) {
4232 ret.appendFormat("Client Package Name: %s", packageName.string());
4233 }
4234
4235 ret.append(", Conflicting Client Devices: {");
4236 for (auto& j : conflicting) {
4237 ret.appendFormat("%s, ", j.string());
4238 }
4239 ret.append("})");
4240 }
4241 if (hasAny) ret.append("\n");
4242 ret.append("]\n");
4243 return ret;
4244}
4245
4246CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
4247 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00004248 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004249 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004250
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004251 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
4252 int32_t state_adj = systemNativeClient ? kSystemNativeClientState: state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07004253
Ruben Brunkcc776712015-02-17 20:18:47 -08004254 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004255 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
4256 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08004257}
4258
4259CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004260 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004261 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004262 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00004263 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004264 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
4265 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08004266}
4267
4268// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08004269// InjectionStatusListener
4270// ----------------------------------------------------------------------------
4271
4272void CameraService::InjectionStatusListener::addListener(
4273 const sp<ICameraInjectionCallback>& callback) {
4274 Mutex::Autolock lock(mListenerLock);
4275 if (mCameraInjectionCallback) return;
4276 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
4277 if (res == OK) {
4278 mCameraInjectionCallback = callback;
4279 }
4280}
4281
4282void CameraService::InjectionStatusListener::removeListener() {
4283 Mutex::Autolock lock(mListenerLock);
4284 if (mCameraInjectionCallback == nullptr) {
4285 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4286 return;
4287 }
4288 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
4289 mCameraInjectionCallback = nullptr;
4290}
4291
4292void CameraService::InjectionStatusListener::notifyInjectionError(
Cliff Wud3a05312021-04-26 23:07:31 +08004293 String8 injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08004294 if (mCameraInjectionCallback == nullptr) {
4295 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4296 return;
4297 }
Cliff Wud3a05312021-04-26 23:07:31 +08004298
4299 switch (err) {
4300 case -ENODEV:
4301 mCameraInjectionCallback->onInjectionError(
4302 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4303 ALOGE("No camera device with ID \"%s\" currently available!",
4304 injectedCamId.string());
4305 break;
4306 case -EBUSY:
4307 mCameraInjectionCallback->onInjectionError(
4308 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4309 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
4310 injectedCamId.string());
4311 break;
4312 case DEAD_OBJECT:
4313 mCameraInjectionCallback->onInjectionError(
4314 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4315 ALOGE("Camera ID \"%s\" object is dead!",
4316 injectedCamId.string());
4317 break;
4318 case INVALID_OPERATION:
4319 mCameraInjectionCallback->onInjectionError(
4320 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4321 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
4322 injectedCamId.string());
4323 break;
4324 case UNKNOWN_TRANSACTION:
4325 mCameraInjectionCallback->onInjectionError(
4326 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
4327 ALOGE("Camera ID \"%s\" method doesn't support!",
4328 injectedCamId.string());
4329 break;
4330 default:
4331 mCameraInjectionCallback->onInjectionError(
4332 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
4333 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
4334 strerror(-err), err, injectedCamId.string());
4335 }
Cliff Wud8cae102021-03-11 01:37:42 +08004336}
4337
4338void CameraService::InjectionStatusListener::binderDied(
4339 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08004340 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
4341 auto parent = mParent.promote();
4342 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08004343 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4344 if (clientDescriptor != nullptr) {
4345 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4346 baseClientPtr->stopInjection();
4347 }
Cliff Wu3b268182021-07-06 15:44:43 +08004348 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004349 }
4350}
4351
4352// ----------------------------------------------------------------------------
4353// CameraInjectionSession
4354// ----------------------------------------------------------------------------
4355
4356binder::Status CameraService::CameraInjectionSession::stopInjection() {
4357 Mutex::Autolock lock(mInjectionSessionLock);
4358 auto parent = mParent.promote();
4359 if (parent == nullptr) {
4360 ALOGE("CameraInjectionSession: Parent is gone");
4361 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
4362 "Camera service encountered error");
4363 }
Cliff Wud3a05312021-04-26 23:07:31 +08004364
4365 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08004366 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4367 if (clientDescriptor != nullptr) {
4368 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4369 res = baseClientPtr->stopInjection();
4370 if (res != OK) {
4371 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
4372 " ret != NO_ERROR: %d", res);
4373 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
4374 "Camera session encountered error");
4375 }
4376 }
Cliff Wu3b268182021-07-06 15:44:43 +08004377 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004378 return binder::Status::ok();
4379}
4380
4381// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07004382
4383static const int kDumpLockRetries = 50;
4384static const int kDumpLockSleep = 60000;
4385
4386static bool tryLock(Mutex& mutex)
4387{
4388 bool locked = false;
4389 for (int i = 0; i < kDumpLockRetries; ++i) {
4390 if (mutex.tryLock() == NO_ERROR) {
4391 locked = true;
4392 break;
4393 }
4394 usleep(kDumpLockSleep);
4395 }
4396 return locked;
4397}
4398
Rucha Katakwardf223072021-06-15 10:21:00 -07004399void CameraService::cacheDump() {
4400 if (mMemFd != -1) {
4401 const Vector<String16> args;
4402 ATRACE_CALL();
4403 // Acquiring service lock here will avoid the deadlock since
4404 // cacheDump will not be called during the second disconnect.
4405 Mutex::Autolock lock(mServiceLock);
4406
4407 Mutex::Autolock l(mCameraStatesLock);
4408 // Start collecting the info for open sessions and store it in temp file.
4409 for (const auto& state : mCameraStates) {
4410 String8 cameraId = state.first;
4411 auto clientDescriptor = mActiveClientManager.get(cameraId);
4412 if (clientDescriptor != nullptr) {
4413 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.string());
4414 // Log the current open session info before device is disconnected.
4415 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
4416 }
4417 }
4418 }
4419}
4420
Mathias Agopian65ab4712010-07-14 17:59:35 -07004421status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004422 ATRACE_CALL();
4423
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004424 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004425 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004426 CameraThreadState::getCallingPid(),
4427 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004428 return NO_ERROR;
4429 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004430 bool locked = tryLock(mServiceLock);
4431 // failed to lock - CameraService is probably deadlocked
4432 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004433 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004434 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004435
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004436 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004437 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07004438
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004439 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004440 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08004441
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004442 if (locked) mServiceLock.unlock();
4443 return NO_ERROR;
4444 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004445 dprintf(fd, "\n== Service global info: ==\n\n");
4446 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004447 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07004448 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
4449 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004450 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
4451 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
4452 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004453 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004454 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
4455 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Shuzhen Wang16610a62022-12-15 22:38:07 -08004456 if (mStreamUseCaseOverrides.size() > 0) {
4457 dprintf(fd, "Active stream use case overrides:");
4458 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
4459 dprintf(fd, " %" PRId64, useCaseOverride);
4460 }
4461 dprintf(fd, "\n");
4462 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004463
4464 dumpEventLog(fd);
4465
4466 bool stateLocked = tryLock(mCameraStatesLock);
4467 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004468 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004469 }
4470
Emilian Peevbd8c5032018-02-14 23:05:40 +00004471 int argSize = args.size();
4472 for (int i = 0; i < argSize; i++) {
4473 if (args[i] == TagMonitor::kMonitorOption) {
4474 if (i + 1 < argSize) {
4475 mMonitorTags = String8(args[i + 1]);
4476 }
4477 break;
4478 }
4479 }
4480
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004481 for (auto& state : mCameraStates) {
4482 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004483
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004484 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004485
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004486 CameraParameters p = state.second->getShimParams();
4487 if (!p.isEmpty()) {
4488 dprintf(fd, " Camera1 API shim is using parameters:\n ");
4489 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004490 }
4491
4492 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004493 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004494 // log the current open session info
4495 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004496 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07004497 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004498 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004499
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004500 }
4501
4502 if (stateLocked) mCameraStatesLock.unlock();
4503
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004504 if (locked) mServiceLock.unlock();
4505
Emilian Peevf53f66e2017-04-11 14:29:43 +01004506 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004507
4508 dprintf(fd, "\n== Vendor tags: ==\n\n");
4509
4510 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
4511 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00004512 sp<VendorTagDescriptorCache> cache =
4513 VendorTagDescriptorCache::getGlobalVendorTagCache();
4514 if (cache == NULL) {
4515 dprintf(fd, "No vendor tags.\n");
4516 } else {
4517 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
4518 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004519 } else {
4520 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
4521 }
4522
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004523 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004524 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004525 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004526
4527 // Process dump arguments, if any
4528 int n = args.size();
4529 String16 verboseOption("-v");
4530 String16 unreachableOption("--unreachable");
4531 for (int i = 0; i < n; i++) {
4532 if (args[i] == verboseOption) {
4533 // change logging level
4534 if (i + 1 >= n) continue;
4535 String8 levelStr(args[i+1]);
4536 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004537 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004538 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004539 } else if (args[i] == unreachableOption) {
4540 // Dump memory analysis
4541 // TODO - should limit be an argument parameter?
4542 UnreachableMemoryInfo info;
4543 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
4544 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004545 dprintf(fd, "\n== Unable to dump unreachable memory. "
4546 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004547 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004548 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004549 std::string s = info.ToString(/*log_contents*/ true);
4550 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004551 }
4552 }
4553 }
Rucha Katakwardf223072021-06-15 10:21:00 -07004554
4555 bool serviceLocked = tryLock(mServiceLock);
4556
4557 // Dump info from previous open sessions.
4558 // Reposition the offset to beginning of the file before reading
4559
4560 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
4561 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
4562 ssize_t size_read;
4563 char buf[4096];
4564 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
4565 // Read data from file to a small buffer and write it to fd.
4566 write(fd, buf, size_read);
4567 if (size_read == -1) {
4568 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4569 break;
4570 }
4571 }
4572 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
4573 } else {
4574 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4575 }
4576
4577 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004578 return NO_ERROR;
4579}
4580
Rucha Katakwardf223072021-06-15 10:21:00 -07004581void CameraService::dumpOpenSessionClientLogs(int fd,
4582 const Vector<String16>& args, const String8& cameraId) {
4583 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07004584 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
4585 getFormattedCurrentTime().string(),
4586 cameraId.string());
Rucha Katakwardf223072021-06-15 10:21:00 -07004587 dprintf(fd, " Client priority score: %d state: %d\n",
4588 clientDescriptor->getPriority().getScore(),
4589 clientDescriptor->getPriority().getState());
4590 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
4591
4592 auto client = clientDescriptor->getValue();
4593 dprintf(fd, " Client package: %s\n",
4594 String8(client->getPackageName()).string());
4595
4596 client->dumpClient(fd, args);
4597}
4598
4599void CameraService::dumpClosedSessionClientLogs(int fd, const String8& cameraId) {
4600 dprintf(fd, " Device %s is closed, no client instance\n",
4601 cameraId.string());
4602}
4603
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004604void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004605 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004606
4607 Mutex::Autolock l(mLogLock);
4608 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004609 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004610 }
4611
4612 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004613 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004614 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004615 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004616 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004617 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004618}
4619
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004620void CameraService::cacheClientTagDumpIfNeeded(const char *cameraId, BasicClient* client) {
4621 Mutex::Autolock lock(mLogLock);
4622 if (!isClientWatchedLocked(client)) { return; }
4623
4624 std::vector<std::string> dumpVector;
4625 client->dumpWatchedEventsToVector(dumpVector);
4626
4627 if (dumpVector.empty()) { return; }
4628
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004629 std::string dumpString;
4630
4631 String8 currentTime = getFormattedCurrentTime();
4632 dumpString += "Cached @ ";
4633 dumpString += currentTime.string();
4634 dumpString += "\n"; // First line is the timestamp of when client is cached.
4635
4636
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004637 const String16 &packageName = client->getPackageName();
4638
4639 String8 packageName8 = String8(packageName);
4640 const char *printablePackageName = packageName8.lockBuffer(packageName.size());
4641
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004642
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004643 size_t i = dumpVector.size();
4644
4645 // Store the string in reverse order (latest last)
4646 while (i > 0) {
4647 i--;
4648 dumpString += cameraId;
4649 dumpString += ":";
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004650 dumpString += printablePackageName;
4651 dumpString += " ";
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004652 dumpString += dumpVector[i]; // implicitly ends with '\n'
4653 }
4654
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004655 packageName8.unlockBuffer();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004656 mWatchedClientsDumpCache[packageName] = dumpString;
4657}
4658
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004659void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004660 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004661 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
4662 if (mTorchClientMap[i] == who) {
4663 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004664 String8 cameraId = mTorchClientMap.keyAt(i);
4665 status_t res = mFlashlight->setTorchMode(cameraId, false);
4666 if (res) {
4667 ALOGE("%s: torch client died but couldn't turn off torch: "
4668 "%s (%d)", __FUNCTION__, strerror(-res), res);
4669 return;
4670 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004671 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004672 break;
4673 }
4674 }
4675}
4676
Ruben Brunkcc776712015-02-17 20:18:47 -08004677/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07004678
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004679 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07004680 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
4681 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004682 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08004683 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004684 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004685
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004686 // check torch client
4687 handleTorchClientBinderDied(who);
4688
4689 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08004690 if(!evictClientIdByRemote(who)) {
4691 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004692 return;
4693 }
4694
Ruben Brunkcc776712015-02-17 20:18:47 -08004695 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
4696 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004697}
4698
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004699void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004700 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08004701}
4702
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004703void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
4704 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004705 // Do not lock mServiceLock here or can get into a deadlock from
4706 // connect() -> disconnect -> updateStatus
4707
4708 auto state = getCameraState(cameraId);
4709
4710 if (state == nullptr) {
4711 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4712 cameraId.string());
4713 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07004714 }
4715
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004716 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
4717 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
4718 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
4719 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
4720 return;
4721 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004722
4723 // Collect the logical cameras without holding mStatusLock in updateStatus
4724 // as that can lead to a deadlock(b/162192331).
4725 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08004726 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08004727 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07004728 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004729 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004730 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004731
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004732 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004733 // Update torch status if it has a flash unit.
4734 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004735 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004736 if (getTorchStatusLocked(cameraId, &torchStatus) !=
4737 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004738 TorchModeStatus newTorchStatus =
4739 status == StatusInternal::PRESENT ?
4740 TorchModeStatus::AVAILABLE_OFF :
4741 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004742 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07004743 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004744 }
4745 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004746 }
4747
4748 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004749 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
4750 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08004751
Ruben Brunkcc776712015-02-17 20:18:47 -08004752 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07004753 bool isVendorListener = listener->isVendorListener();
4754 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
4755 listener->getListenerPid(), listener->getListenerUid()) ||
Shuzhen Wangb8259792021-05-27 09:27:06 -07004756 isVendorListener) {
4757 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004758 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08004759 continue;
4760 }
Austin Borgere8e2c422022-05-12 13:45:24 -07004761 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08004762 String16(cameraId));
Austin Borgere8e2c422022-05-12 13:45:24 -07004763 listener->handleBinderStatus(ret,
4764 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
4765 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
4766 ret.exceptionCode());
Ruben Brunkcc776712015-02-17 20:18:47 -08004767 }
4768 });
Igor Murashkincba2c162013-03-20 15:56:31 -07004769}
4770
Shuzhen Wang695044d2020-03-06 09:02:23 -08004771void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
4772 const String16& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004773 auto state = getCameraState(cameraId);
4774 if (state == nullptr) {
4775 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4776 cameraId.string());
4777 return;
4778 }
4779 if (open) {
4780 state->setClientPackage(String8(clientPackageName));
4781 } else {
4782 state->setClientPackage(String8::empty());
4783 }
4784
Shuzhen Wang695044d2020-03-06 09:02:23 -08004785 Mutex::Autolock lock(mStatusListenerLock);
4786
4787 for (const auto& it : mListenerList) {
4788 if (!it->isOpenCloseCallbackAllowed()) {
4789 continue;
4790 }
4791
4792 binder::Status ret;
4793 String16 cameraId64(cameraId);
4794 if (open) {
4795 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
4796 } else {
4797 ret = it->getListener()->onCameraClosed(cameraId64);
4798 }
Austin Borgere8e2c422022-05-12 13:45:24 -07004799
4800 it->handleBinderStatus(ret,
4801 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
4802 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08004803 }
4804}
4805
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004806template<class Func>
4807void CameraService::CameraState::updateStatus(StatusInternal status,
4808 const String8& cameraId,
4809 std::initializer_list<StatusInternal> rejectSourceStates,
4810 Func onStatusUpdatedLocked) {
4811 Mutex::Autolock lock(mStatusLock);
4812 StatusInternal oldStatus = mStatus;
4813 mStatus = status;
4814
4815 if (oldStatus == status) {
4816 return;
4817 }
4818
4819 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
4820 cameraId.string(), oldStatus, status);
4821
4822 if (oldStatus == StatusInternal::NOT_PRESENT &&
4823 (status != StatusInternal::PRESENT &&
4824 status != StatusInternal::ENUMERATING)) {
4825
4826 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
4827 __FUNCTION__);
4828 mStatus = oldStatus;
4829 return;
4830 }
4831
4832 /**
4833 * Sometimes we want to conditionally do a transition.
4834 * For example if a client disconnects, we want to go to PRESENT
4835 * only if we weren't already in NOT_PRESENT or ENUMERATING.
4836 */
4837 for (auto& rejectStatus : rejectSourceStates) {
4838 if (oldStatus == rejectStatus) {
4839 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
4840 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
4841 mStatus = oldStatus;
4842 return;
4843 }
4844 }
4845
4846 onStatusUpdatedLocked(cameraId, status);
4847}
4848
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004849status_t CameraService::getTorchStatusLocked(
4850 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004851 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004852 if (!status) {
4853 return BAD_VALUE;
4854 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004855 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4856 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004857 // invalid camera ID or the camera doesn't have a flash unit
4858 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004859 }
4860
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004861 *status = mTorchStatusMap.valueAt(index);
4862 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004863}
4864
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004865status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004866 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004867 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4868 if (index == NAME_NOT_FOUND) {
4869 return BAD_VALUE;
4870 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004871 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004872
4873 return OK;
4874}
4875
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004876std::list<String16> CameraService::getLogicalCameras(
4877 const String8& physicalCameraId) {
4878 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08004879 Mutex::Autolock lock(mCameraStatesLock);
4880 for (const auto& state : mCameraStates) {
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004881 if (state.second->containsPhysicalCamera(physicalCameraId.c_str())) {
4882 retList.emplace_back(String16(state.first));
Shuzhen Wang43858162020-01-10 13:42:15 -08004883 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004884 }
4885 return retList;
4886}
4887
4888void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
4889 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
4890 SystemCameraKind deviceKind) {
4891 // mStatusListenerLock is expected to be locked
4892 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004893 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004894 // Note: we check only the deviceKind of the physical camera id
4895 // since, logical camera ids and their physical camera ids are
4896 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004897 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
4898 listener->getListenerPid(), listener->getListenerUid())) {
4899 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004900 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004901 continue;
4902 }
Austin Borgere8e2c422022-05-12 13:45:24 -07004903 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004904 logicalCameraId, physicalCameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07004905 listener->handleBinderStatus(ret,
4906 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
4907 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
4908 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08004909 }
4910 }
4911}
4912
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004913
Svet Ganova453d0d2018-01-11 15:37:58 -08004914void CameraService::blockClientsForUid(uid_t uid) {
4915 const auto clients = mActiveClientManager.getAll();
4916 for (auto& current : clients) {
4917 if (current != nullptr) {
4918 const auto basicClient = current->getValue();
4919 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
4920 basicClient->block();
4921 }
4922 }
4923 }
4924}
4925
Michael Grooverd1d435a2018-12-18 17:39:42 -08004926void CameraService::blockAllClients() {
4927 const auto clients = mActiveClientManager.getAll();
4928 for (auto& current : clients) {
4929 if (current != nullptr) {
4930 const auto basicClient = current->getValue();
4931 if (basicClient.get() != nullptr) {
4932 basicClient->block();
4933 }
4934 }
4935 }
4936}
4937
Svet Ganova453d0d2018-01-11 15:37:58 -08004938// NOTE: This is a remote API - make sure all args are validated
4939status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
4940 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
4941 return PERMISSION_DENIED;
4942 }
4943 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
4944 return BAD_VALUE;
4945 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004946 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004947 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004948 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004949 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004950 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004951 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004952 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
4953 return handleSetRotateAndCrop(args);
4954 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
4955 return handleGetRotateAndCrop(out);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004956 } else if (args.size() >= 2 && args[0] == String16("set-autoframing")) {
4957 return handleSetAutoframing(args);
4958 } else if (args.size() >= 1 && args[0] == String16("get-autoframing")) {
4959 return handleGetAutoframing(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004960 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
4961 return handleSetImageDumpMask(args);
4962 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
4963 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004964 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
4965 return handleSetCameraMute(args);
Shuzhen Wang16610a62022-12-15 22:38:07 -08004966 } else if (args.size() >= 2 && args[0] == String16("set-stream-use-case-override")) {
4967 return handleSetStreamUseCaseOverrides(args);
4968 } else if (args.size() >= 1 && args[0] == String16("clear-stream-use-case-override")) {
4969 handleClearStreamUseCaseOverrides();
4970 return OK;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004971 } else if (args.size() >= 2 && args[0] == String16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08004972 return handleWatchCommand(args, in, out);
Ravneetaeb20dc2022-03-30 05:33:03 +00004973 } else if (args.size() >= 2 && args[0] == String16("set-watchdog")) {
4974 return handleSetCameraServiceWatchdog(args);
Svet Ganova453d0d2018-01-11 15:37:58 -08004975 } else if (args.size() == 1 && args[0] == String16("help")) {
4976 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004977 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08004978 }
4979 printHelp(err);
4980 return BAD_VALUE;
4981}
4982
4983status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004984 String16 packageName = args[1];
4985
Svet Ganova453d0d2018-01-11 15:37:58 -08004986 bool active = false;
4987 if (args[2] == String16("active")) {
4988 active = true;
4989 } else if ((args[2] != String16("idle"))) {
4990 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
4991 return BAD_VALUE;
4992 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004993
4994 int userId = 0;
4995 if (args.size() >= 5 && args[3] == String16("--user")) {
4996 userId = atoi(String8(args[4]));
4997 }
4998
4999 uid_t uid;
5000 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5001 return BAD_VALUE;
5002 }
5003
5004 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005005 return NO_ERROR;
5006}
5007
5008status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07005009 String16 packageName = args[1];
5010
5011 int userId = 0;
5012 if (args.size() >= 4 && args[2] == String16("--user")) {
5013 userId = atoi(String8(args[3]));
5014 }
5015
5016 uid_t uid;
5017 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005018 return BAD_VALUE;
5019 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005020
5021 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005022 return NO_ERROR;
5023}
5024
5025status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07005026 String16 packageName = args[1];
5027
5028 int userId = 0;
5029 if (args.size() >= 4 && args[2] == String16("--user")) {
5030 userId = atoi(String8(args[3]));
5031 }
5032
5033 uid_t uid;
5034 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005035 return BAD_VALUE;
5036 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005037
5038 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005039 return dprintf(out, "active\n");
5040 } else {
5041 return dprintf(out, "idle\n");
5042 }
5043}
5044
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005045status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
5046 int rotateValue = atoi(String8(args[1]));
5047 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
5048 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
5049 Mutex::Autolock lock(mServiceLock);
5050
5051 mOverrideRotateAndCropMode = rotateValue;
5052
5053 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
5054
5055 const auto clients = mActiveClientManager.getAll();
5056 for (auto& current : clients) {
5057 if (current != nullptr) {
5058 const auto basicClient = current->getValue();
5059 if (basicClient.get() != nullptr) {
5060 basicClient->setRotateAndCropOverride(rotateValue);
5061 }
5062 }
5063 }
5064
5065 return OK;
5066}
5067
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005068status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
5069 char* end;
5070 int autoframingValue = (int) strtol(String8(args[1]), &end, /*base=*/10);
5071 if ((*end != '\0') ||
5072 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
5073 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
5074 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
5075 return BAD_VALUE;
5076 }
5077
5078 Mutex::Autolock lock(mServiceLock);
5079 mOverrideAutoframingMode = autoframingValue;
5080
5081 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
5082
5083 const auto clients = mActiveClientManager.getAll();
5084 for (auto& current : clients) {
5085 if (current != nullptr) {
5086 const auto basicClient = current->getValue();
5087 if (basicClient.get() != nullptr) {
5088 basicClient->setAutoframingOverride(autoframingValue);
5089 }
5090 }
5091 }
5092
5093 return OK;
5094}
5095
Ravneetaeb20dc2022-03-30 05:33:03 +00005096status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
5097 int enableWatchdog = atoi(String8(args[1]));
5098
5099 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
5100
5101 Mutex::Autolock lock(mServiceLock);
5102
5103 mCameraServiceWatchdogEnabled = enableWatchdog;
5104
5105 const auto clients = mActiveClientManager.getAll();
5106 for (auto& current : clients) {
5107 if (current != nullptr) {
5108 const auto basicClient = current->getValue();
5109 if (basicClient.get() != nullptr) {
5110 basicClient->setCameraServiceWatchdog(enableWatchdog);
5111 }
5112 }
5113 }
5114
5115 return OK;
5116}
5117
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005118status_t CameraService::handleGetRotateAndCrop(int out) {
5119 Mutex::Autolock lock(mServiceLock);
5120
5121 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
5122}
5123
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005124status_t CameraService::handleGetAutoframing(int out) {
5125 Mutex::Autolock lock(mServiceLock);
5126
5127 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
5128}
5129
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005130status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
5131 char *endPtr;
5132 errno = 0;
5133 String8 maskString8 = String8(args[1]);
5134 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
5135
5136 if (errno != 0) return BAD_VALUE;
5137 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
5138 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
5139
5140 Mutex::Autolock lock(mServiceLock);
5141
5142 mImageDumpMask = maskValue;
5143
5144 return OK;
5145}
5146
5147status_t CameraService::handleGetImageDumpMask(int out) {
5148 Mutex::Autolock lock(mServiceLock);
5149
5150 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
5151}
5152
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005153status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
5154 int muteValue = strtol(String8(args[1]), nullptr, 10);
5155 if (errno != 0) return BAD_VALUE;
5156
5157 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
5158 Mutex::Autolock lock(mServiceLock);
5159
5160 mOverrideCameraMuteMode = (muteValue == 1);
5161
5162 const auto clients = mActiveClientManager.getAll();
5163 for (auto& current : clients) {
5164 if (current != nullptr) {
5165 const auto basicClient = current->getValue();
5166 if (basicClient.get() != nullptr) {
5167 if (basicClient->supportsCameraMute()) {
5168 basicClient->setCameraMute(mOverrideCameraMuteMode);
5169 }
5170 }
5171 }
5172 }
5173
5174 return OK;
5175}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005176
Shuzhen Wang16610a62022-12-15 22:38:07 -08005177status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
5178 std::vector<int64_t> useCasesOverride;
5179 for (size_t i = 1; i < args.size(); i++) {
5180 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
5181 String8 arg8 = String8(args[i]);
5182 if (arg8 == "DEFAULT") {
5183 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
5184 } else if (arg8 == "PREVIEW") {
5185 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
5186 } else if (arg8 == "STILL_CAPTURE") {
5187 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
5188 } else if (arg8 == "VIDEO_RECORD") {
5189 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
5190 } else if (arg8 == "PREVIEW_VIDEO_STILL") {
5191 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
5192 } else if (arg8 == "VIDEO_CALL") {
5193 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
5194 } else if (arg8 == "CROPPED_RAW") {
5195 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
5196 } else {
5197 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg8.c_str());
5198 return BAD_VALUE;
5199 }
5200 useCasesOverride.push_back(useCase);
5201 }
5202
5203 Mutex::Autolock lock(mServiceLock);
5204 mStreamUseCaseOverrides = std::move(useCasesOverride);
5205
5206 return OK;
5207}
5208
5209void CameraService::handleClearStreamUseCaseOverrides() {
5210 Mutex::Autolock lock(mServiceLock);
5211 mStreamUseCaseOverrides.clear();
5212}
5213
Avichal Rakesh84147132021-11-11 17:47:11 -08005214status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005215 if (args.size() >= 3 && args[1] == String16("start")) {
5216 return startWatchingTags(args, outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005217 } else if (args.size() == 2 && args[1] == String16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005218 return stopWatchingTags(outFd);
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005219 } else if (args.size() == 2 && args[1] == String16("dump")) {
5220 return printWatchedTags(outFd);
5221 } else if (args.size() >= 2 && args[1] == String16("live")) {
5222 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005223 } else if (args.size() == 2 && args[1] == String16("clear")) {
5224 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005225 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005226 dprintf(outFd, "Camera service watch commands:\n"
5227 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
5228 " starts watching the provided tags for clients with provided package\n"
5229 " recognizes tag shorthands like '3a'\n"
5230 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005231 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005232 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005233 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005234 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08005235 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005236 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005237 return BAD_VALUE;
5238}
5239
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005240status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
5241 Mutex::Autolock lock(mLogLock);
5242 size_t tagsIdx; // index of '-m'
5243 String16 tags("");
5244 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != String16("-m"); tagsIdx++);
5245 if (tagsIdx < args.size() - 1) {
5246 tags = args[tagsIdx + 1];
5247 } else {
5248 dprintf(outFd, "No tags provided.\n");
5249 return BAD_VALUE;
5250 }
5251
5252 size_t clientsIdx; // index of '-c'
5253 String16 clients = kWatchAllClientsFlag; // watch all clients if no clients are provided
5254 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != String16("-c");
5255 clientsIdx++);
5256 if (clientsIdx < args.size() - 1) {
5257 clients = args[clientsIdx + 1];
5258 }
5259 parseClientsToWatchLocked(String8(clients));
5260
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005261 // track tags to initialize future clients with the monitoring information
5262 mMonitorTags = String8(tags);
5263
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005264 bool serviceLock = tryLock(mServiceLock);
5265 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005266 auto cameraClients = mActiveClientManager.getAll();
5267 for (const auto &clientDescriptor: cameraClients) {
5268 if (clientDescriptor == nullptr) { continue; }
5269 sp<BasicClient> client = clientDescriptor->getValue();
5270 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005271
5272 if (isClientWatchedLocked(client.get())) {
5273 client->startWatchingTags(mMonitorTags, outFd);
5274 numWatchedClients++;
5275 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005276 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005277 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
5278
5279 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005280 return OK;
5281}
5282
5283status_t CameraService::stopWatchingTags(int outFd) {
5284 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005285 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005286 mMonitorTags = String8::empty();
5287
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005288 mWatchedClientPackages.clear();
5289 mWatchedClientsDumpCache.clear();
5290
5291 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005292 auto cameraClients = mActiveClientManager.getAll();
5293 for (const auto &clientDescriptor : cameraClients) {
5294 if (clientDescriptor == nullptr) { continue; }
5295 sp<BasicClient> client = clientDescriptor->getValue();
5296 if (client.get() == nullptr) { continue; }
5297 client->stopWatchingTags(outFd);
5298 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005299 dprintf(outFd, "Stopped watching all clients.\n");
5300 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005301 return OK;
5302}
5303
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005304status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
5305 Mutex::Autolock lock(mLogLock);
5306 size_t clearedSize = mWatchedClientsDumpCache.size();
5307 mWatchedClientsDumpCache.clear();
5308 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
5309 return OK;
5310}
5311
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005312status_t CameraService::printWatchedTags(int outFd) {
5313 Mutex::Autolock logLock(mLogLock);
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08005314 std::set<String16> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005315
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005316 bool printedSomething = false; // tracks if any monitoring information was printed
5317 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005318
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005319 bool serviceLock = tryLock(mServiceLock);
5320 // get all watched clients that are currently connected
5321 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
5322 if (clientDescriptor == nullptr) { continue; }
5323
5324 sp<BasicClient> client = clientDescriptor->getValue();
5325 if (client.get() == nullptr) { continue; }
5326 if (!isClientWatchedLocked(client.get())) { continue; }
5327
5328 std::vector<std::string> dumpVector;
5329 client->dumpWatchedEventsToVector(dumpVector);
5330
5331 size_t printIdx = dumpVector.size();
5332 if (printIdx == 0) {
5333 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005334 }
5335
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005336 // Print tag dumps for active client
5337 const String8 &cameraId = clientDescriptor->getKey();
5338 String8 packageName8 = String8(client->getPackageName());
5339 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
5340 dprintf(outFd, "Client: %s (active)\n", printablePackageName);
5341 while(printIdx > 0) {
5342 printIdx--;
5343 dprintf(outFd, "%s:%s %s", cameraId.string(), printablePackageName,
5344 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005345 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005346 dprintf(outFd, "\n");
5347 packageName8.unlockBuffer();
5348 printedSomething = true;
5349
5350 connectedMonitoredClients.emplace(client->getPackageName());
5351 }
5352 if (serviceLock) { mServiceLock.unlock(); }
5353
5354 // Print entries in mWatchedClientsDumpCache for clients that are not connected
5355 for (const auto &kv: mWatchedClientsDumpCache) {
5356 const String16 &package = kv.first;
5357 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
5358 continue;
5359 }
5360
5361 dprintf(outFd, "Client: %s (cached)\n", String8(package).string());
5362 dprintf(outFd, "%s\n", kv.second.c_str());
5363 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005364 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005365
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005366 if (!printedSomething) {
5367 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005368 }
5369
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005370 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005371}
5372
Avichal Rakesh84147132021-11-11 17:47:11 -08005373// Print all events in vector `events' that came after lastPrintedEvent
5374void printNewWatchedEvents(int outFd,
5375 const char *cameraId,
5376 const String16 &packageName,
5377 const std::vector<std::string> &events,
5378 const std::string &lastPrintedEvent) {
5379 if (events.empty()) { return; }
5380
5381 // index of lastPrintedEvent in events.
5382 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
5383 size_t lastPrintedIdx;
5384 for (lastPrintedIdx = 0;
5385 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
5386 lastPrintedIdx++);
5387
5388 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
5389
5390 String8 packageName8(packageName);
5391 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
5392
5393 // print events in chronological order (latest event last)
5394 size_t idxToPrint = lastPrintedIdx;
5395 do {
5396 idxToPrint--;
5397 dprintf(outFd, "%s:%s %s", cameraId, printablePackageName, events[idxToPrint].c_str());
5398 } while (idxToPrint != 0);
5399
5400 packageName8.unlockBuffer();
5401}
5402
5403// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
5404// command should be interrupted if the user presses the return key, or if user loses any way to
5405// signal interrupt.
5406// If timeoutMs == 0, this function will always return false
5407bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
5408 struct timeval startTime;
5409 int startTimeError = gettimeofday(&startTime, nullptr);
5410 if (startTimeError) {
5411 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5412 return true;
5413 }
5414
5415 const nfds_t numFds = 1;
5416 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
5417
5418 struct timeval currTime;
5419 char buffer[2];
5420 while(true) {
5421 int currTimeError = gettimeofday(&currTime, nullptr);
5422 if (currTimeError) {
5423 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5424 return true;
5425 }
5426
5427 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
5428 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
5429 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
5430
5431 if (remainingTimeMs <= 0) {
5432 // No user interrupt within timeoutMs, don't interrupt watch command
5433 return false;
5434 }
5435
5436 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
5437 if (numFdsUpdated < 0) {
5438 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5439 return true;
5440 }
5441
5442 if (numFdsUpdated == 0) {
5443 // No user input within timeoutMs, don't interrupt watch command
5444 return false;
5445 }
5446
5447 if (!(pollFd.revents & POLLIN)) {
5448 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5449 return true;
5450 }
5451
5452 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
5453 if (sizeRead < 0) {
5454 dprintf(outFd, "Error reading user input. Exiting.\n");
5455 return true;
5456 }
5457
5458 if (sizeRead == 0) {
5459 // Reached end of input fd (can happen if input is piped)
5460 // User has no way to signal an interrupt, so interrupt here
5461 return true;
5462 }
5463
5464 if (buffer[0] == '\n') {
5465 // User pressed return, interrupt watch command.
5466 return true;
5467 }
5468 }
5469}
5470
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005471status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
5472 int inFd, int outFd) {
5473 // Figure out refresh interval, if present in args
5474 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005475 if (args.size() > 2) {
5476 size_t intervalIdx; // index of '-n'
5477 for (intervalIdx = 2; intervalIdx < args.size() && String16("-n") != args[intervalIdx];
5478 intervalIdx++);
5479
5480 size_t intervalValIdx = intervalIdx + 1;
5481 if (intervalValIdx < args.size()) {
5482 refreshTimeoutMs = strtol(String8(args[intervalValIdx].string()), nullptr, 10);
5483 if (errno) { return BAD_VALUE; }
5484 }
5485 }
5486
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005487 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
5488 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005489
Avichal Rakesh84147132021-11-11 17:47:11 -08005490 dprintf(outFd, "Press return to exit...\n\n");
Avichal Rakesha14d9832021-11-11 01:41:55 -08005491 std::map<String16, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005492
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005493 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005494 bool serviceLock = tryLock(mServiceLock);
5495 auto cameraClients = mActiveClientManager.getAll();
5496 if (serviceLock) { mServiceLock.unlock(); }
5497
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005498 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005499 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005500 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005501
5502 sp<BasicClient> client = clientDescriptor->getValue();
5503 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005504 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005505
Avichal Rakesha14d9832021-11-11 01:41:55 -08005506 const String16 &packageName = client->getPackageName();
5507 // This also initializes the map entries with an empty string
5508 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
5509
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005510 std::vector<std::string> latestEvents;
5511 client->dumpWatchedEventsToVector(latestEvents);
5512
5513 if (!latestEvents.empty()) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005514 String8 cameraId = clientDescriptor->getKey();
5515 const char *printableCameraId = cameraId.lockBuffer(cameraId.size());
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005516 printNewWatchedEvents(outFd,
Avichal Rakesha14d9832021-11-11 01:41:55 -08005517 printableCameraId,
5518 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005519 latestEvents,
5520 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08005521 packageNameToLastEvent[packageName] = latestEvents[0];
5522 cameraId.unlockBuffer();
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005523 }
5524 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005525 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005526 break;
5527 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005528 }
5529 return OK;
5530}
5531
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005532void CameraService::parseClientsToWatchLocked(String8 clients) {
5533 mWatchedClientPackages.clear();
5534
5535 const char *allSentinel = String8(kWatchAllClientsFlag).string();
5536
5537 char *tokenized = clients.lockBuffer(clients.size());
5538 char *savePtr;
5539 char *nextClient = strtok_r(tokenized, ",", &savePtr);
5540
5541 while (nextClient != nullptr) {
5542 if (strcmp(nextClient, allSentinel) == 0) {
5543 // Don't need to track any other package if 'all' is present
5544 mWatchedClientPackages.clear();
5545 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
5546 break;
5547 }
5548
5549 // track package names
5550 mWatchedClientPackages.emplace(nextClient);
5551 nextClient = strtok_r(nullptr, ",", &savePtr);
5552 }
5553 clients.unlockBuffer();
5554}
5555
Svet Ganova453d0d2018-01-11 15:37:58 -08005556status_t CameraService::printHelp(int out) {
5557 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07005558 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
5559 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
5560 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005561 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
5562 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
5563 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005564 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
5565 " Valid values 0=false, 1=true, 2=auto\n"
5566 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005567 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
5568 " Valid values 0=OFF, 1=ON for JPEG\n"
5569 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005570 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08005571 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
5572 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
5573 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
5574 " on. In case the number of usecases is smaller than the number of streams, the\n"
5575 " last use case is assigned to all the remaining streams. In case of multiple\n"
5576 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
5577 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
5578 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
5579 " clear-stream-use-case-override clear the stream use case override\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005580 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08005581 " help print this message\n");
5582}
5583
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005584bool CameraService::isClientWatched(const BasicClient *client) {
5585 Mutex::Autolock lock(mLogLock);
5586 return isClientWatchedLocked(client);
5587}
5588
5589bool CameraService::isClientWatchedLocked(const BasicClient *client) {
5590 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
5591 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
5592}
5593
Yin-Chia Yehdba03232019-08-19 15:54:28 -07005594int32_t CameraService::updateAudioRestriction() {
5595 Mutex::Autolock lock(mServiceLock);
5596 return updateAudioRestrictionLocked();
5597}
5598
5599int32_t CameraService::updateAudioRestrictionLocked() {
5600 int32_t mode = 0;
5601 // iterate through all active client
5602 for (const auto& i : mActiveClientManager.getAll()) {
5603 const auto clientSp = i->getValue();
5604 mode |= clientSp->getAudioRestriction();
5605 }
5606
5607 bool modeChanged = (mAudioRestriction != mode);
5608 mAudioRestriction = mode;
5609 if (modeChanged) {
5610 mAppOps.setCameraAudioRestriction(mode);
5611 }
5612 return mode;
5613}
5614
Cliff Wu646bd612021-11-23 23:21:29 +08005615status_t CameraService::checkIfInjectionCameraIsPresent(const String8& externalCamId,
5616 sp<BasicClient> clientSp) {
5617 std::unique_ptr<AutoConditionLock> lock =
5618 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
5619 status_t res = NO_ERROR;
5620 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
5621 ALOGW("Device %s is not usable!", externalCamId.string());
5622 mInjectionStatusListener->notifyInjectionError(
5623 externalCamId, UNKNOWN_TRANSACTION);
5624 clientSp->notifyError(
5625 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
5626 CaptureResultExtras());
5627
5628 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
5629 // other clients from connecting in mServiceLockWrapper if held
5630 mServiceLock.unlock();
5631
5632 // Clear caller identity temporarily so client disconnect PID checks work correctly
5633 int64_t token = CameraThreadState::clearCallingIdentity();
5634 clientSp->disconnect();
5635 CameraThreadState::restoreCallingIdentity(token);
5636
5637 // Reacquire mServiceLock
5638 mServiceLock.lock();
5639 }
5640
5641 return res;
5642}
5643
Cliff Wud3a05312021-04-26 23:07:31 +08005644void CameraService::clearInjectionParameters() {
5645 {
5646 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08005647 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08005648 mInjectionInternalCamId = "";
5649 }
5650 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08005651 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08005652}
5653
Mathias Agopian65ab4712010-07-14 17:59:35 -07005654}; // namespace android