blob: b179372ec8b20c2bdfd095978a7e3be9b645f654 [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();
Jyoti Bhayana8143e572023-01-09 08:46:49 -08003536 // We don't want to return EACCESS if the CameraPrivacy is enabled.
3537 // We prefer to successfully open the camera and perform camera muting
3538 // or blocking in connectHelper as handleAppOpMode can be called before the
3539 // connection has been fully established and at that time camera muting
3540 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003541 if (!isUidActive || !isCameraPrivacyEnabled) {
3542 ALOGI("Camera %s: Access for \"%s\" has been restricted",
3543 mCameraIdStr.string(), String8(mClientPackageName).string());
3544 // Return the same error as for device policy manager rejection
3545 return -EACCES;
3546 }
3547 }
3548 return OK;
3549}
3550
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003551status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003552 ATRACE_CALL();
3553
Igor Murashkine6800ce2013-03-04 17:25:57 -08003554 {
3555 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003556 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003557 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003558 if (mAppOpsManager != nullptr) {
3559 // Notify app ops that the camera is not available
3560 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003561 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
3562 mClientPackageName, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003563
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003564 // Just check for camera acccess here on open - delay startOp until
3565 // camera frames start streaming in startCameraStreamingOps
3566 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
3567 mClientPackageName);
3568 status_t res = handleAppOpMode(mode);
3569 if (res != OK) {
3570 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003571 }
Svetoslav28e8ef72015-05-11 19:21:31 -07003572 }
3573
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003574 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003575
3576 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003577 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003578
Emilian Peev53722fa2019-02-22 17:47:20 -08003579 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
3580
Shuzhen Wang695044d2020-03-06 09:02:23 -08003581 // Notify listeners of camera open/close status
3582 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
3583
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003584 return OK;
3585}
3586
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003587status_t CameraService::BasicClient::startCameraStreamingOps() {
3588 ATRACE_CALL();
3589
3590 if (!mOpsActive) {
3591 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3592 return INVALID_OPERATION;
3593 }
3594 if (mOpsStreaming) {
3595 ALOGV("%s: Streaming already active!", __FUNCTION__);
3596 return OK;
3597 }
3598
3599 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
3600 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3601
3602 if (mAppOpsManager != nullptr) {
3603 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
3604 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
3605 String16("start camera ") + String16(mCameraIdStr));
3606 status_t res = handleAppOpMode(mode);
3607 if (res != OK) {
3608 return res;
3609 }
3610 }
3611
3612 mOpsStreaming = true;
3613
3614 return OK;
3615}
3616
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003617status_t CameraService::BasicClient::noteAppOp() {
3618 ATRACE_CALL();
3619
3620 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
3621 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3622
3623 // noteAppOp is only used for when camera mute is not supported, in order
3624 // to trigger the sensor privacy "Unblock" dialog
3625 if (mAppOpsManager != nullptr) {
3626 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
3627 mClientPackageName, mClientFeatureId,
3628 String16("start camera ") + String16(mCameraIdStr));
3629 status_t res = handleAppOpMode(mode);
3630 if (res != OK) {
3631 return res;
3632 }
3633 }
3634
3635 return OK;
3636}
3637
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003638status_t CameraService::BasicClient::finishCameraStreamingOps() {
3639 ATRACE_CALL();
3640
3641 if (!mOpsActive) {
3642 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3643 return INVALID_OPERATION;
3644 }
3645 if (!mOpsStreaming) {
3646 ALOGV("%s: Streaming not active!", __FUNCTION__);
3647 return OK;
3648 }
3649
3650 if (mAppOpsManager != nullptr) {
3651 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
3652 mClientPackageName, mClientFeatureId);
3653 mOpsStreaming = false;
3654 }
3655
3656 return OK;
3657}
3658
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003659status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003660 ATRACE_CALL();
3661
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003662 if (mOpsStreaming) {
3663 // Make sure we've notified everyone about camera stopping
3664 finishCameraStreamingOps();
3665 }
3666
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003667 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003668 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003669 mOpsActive = false;
3670
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003671 // This function is called when a client disconnects. This should
3672 // release the camera, but actually only if it was in a proper
3673 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003674 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003675 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003676
Ruben Brunkcc776712015-02-17 20:18:47 -08003677 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003678 sCameraService->updateStatus(StatusInternal::PRESENT,
3679 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003680 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003681 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003682 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3683 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003684 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003685 mOpsCallback.clear();
3686
Emilian Peev53722fa2019-02-22 17:47:20 -08003687 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3688
Shuzhen Wang695044d2020-03-06 09:02:23 -08003689 // Notify listeners of camera open/close status
3690 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3691
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003692 return OK;
3693}
3694
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003695void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003696 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003697 if (mAppOpsManager == nullptr) {
3698 return;
3699 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003700 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003701 if (op != AppOpsManager::OP_CAMERA) {
3702 ALOGW("Unexpected app ops notification received: %d", op);
3703 return;
3704 }
3705
3706 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003707 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003708 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003709 ALOGV("checkOp returns: %d, %s ", res,
3710 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3711 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3712 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3713 "UNKNOWN");
3714
Shuzhen Wang64900852021-02-05 09:03:29 -08003715 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003716 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003717 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003718 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003719 } else if (res == AppOpsManager::MODE_IGNORED) {
3720 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08003721 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08003722 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Shuzhen Wang64900852021-02-05 09:03:29 -08003723 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3724 mCameraIdStr.string(), String8(mClientPackageName).string(),
3725 mUidIsTrusted, isUidActive);
3726 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3727 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3728 // error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003729 if (!mUidIsTrusted) {
3730 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
3731 setCameraMute(true);
3732 } else if (!isUidActive
3733 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
3734 block();
3735 }
Shuzhen Wang64900852021-02-05 09:03:29 -08003736 }
Evan Severson09ab4002021-02-10 14:15:19 -08003737 } else if (res == AppOpsManager::MODE_ALLOWED) {
3738 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003739 }
3740}
3741
Svet Ganova453d0d2018-01-11 15:37:58 -08003742void CameraService::BasicClient::block() {
3743 ATRACE_CALL();
3744
3745 // Reset the client PID to allow server-initiated disconnect,
3746 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003747 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003748 CaptureResultExtras resultExtras; // a dummy result (invalid)
3749 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3750 disconnect();
3751}
3752
Mathias Agopian65ab4712010-07-14 17:59:35 -07003753// ----------------------------------------------------------------------------
3754
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003755void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003756 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003757 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003758 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003759 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3760 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3761 api1ErrorCode = CAMERA_ERROR_DISABLED;
3762 }
3763 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003764 } else {
3765 ALOGE("mRemoteCallback is NULL!!");
3766 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003767}
3768
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003769// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003770binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003771 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003772 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003773}
3774
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003775bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3776 return level == API_1;
3777}
3778
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003779CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3780 mClient(client) {
3781}
3782
3783void CameraService::Client::OpsCallback::opChanged(int32_t op,
3784 const String16& packageName) {
3785 sp<BasicClient> client = mClient.promote();
3786 if (client != NULL) {
3787 client->opChanged(op, packageName);
3788 }
3789}
3790
Mathias Agopian65ab4712010-07-14 17:59:35 -07003791// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003792// UidPolicy
3793// ----------------------------------------------------------------------------
3794
3795void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003796 Mutex::Autolock _l(mUidLock);
3797
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003798 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003799 status_t res = mAm.linkToDeath(this);
3800 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003801 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00003802 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
3803 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08003804 ActivityManager::PROCESS_STATE_UNKNOWN,
3805 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003806 if (res == OK) {
3807 mRegistered = true;
3808 ALOGV("UidPolicy: Registered with ActivityManager");
3809 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003810}
3811
3812void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003813 Mutex::Autolock _l(mUidLock);
3814
Steven Moreland2f348142019-07-02 15:59:07 -07003815 mAm.unregisterUidObserver(this);
3816 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003817 mRegistered = false;
3818 mActiveUids.clear();
3819 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003820}
3821
3822void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3823 onUidIdle(uid, disabled);
3824}
3825
3826void CameraService::UidPolicy::onUidActive(uid_t uid) {
3827 Mutex::Autolock _l(mUidLock);
3828 mActiveUids.insert(uid);
3829}
3830
3831void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3832 bool deleted = false;
3833 {
3834 Mutex::Autolock _l(mUidLock);
3835 if (mActiveUids.erase(uid) > 0) {
3836 deleted = true;
3837 }
3838 }
3839 if (deleted) {
3840 sp<CameraService> service = mService.promote();
3841 if (service != nullptr) {
3842 service->blockClientsForUid(uid);
3843 }
3844 }
3845}
3846
Emilian Peev53722fa2019-02-22 17:47:20 -08003847void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003848 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00003849 bool procStateChange = false;
3850 {
3851 Mutex::Autolock _l(mUidLock);
3852 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
3853 mMonitoredUids[uid].procState != procState) {
3854 mMonitoredUids[uid].procState = procState;
3855 procStateChange = true;
3856 }
3857 }
3858
3859 if (procStateChange) {
3860 sp<CameraService> service = mService.promote();
3861 if (service != nullptr) {
3862 service->notifyMonitoredUids();
3863 }
Emilian Peev53722fa2019-02-22 17:47:20 -08003864 }
3865}
3866
Austin Borger65577682022-02-17 00:25:43 +00003867void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid) {
3868 bool procAdjChange = false;
3869 {
3870 Mutex::Autolock _l(mUidLock);
3871 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3872 procAdjChange = true;
3873 }
3874 }
3875
3876 if (procAdjChange) {
3877 sp<CameraService> service = mService.promote();
3878 if (service != nullptr) {
3879 service->notifyMonitoredUids();
3880 }
3881 }
3882}
3883
Emilian Peev53722fa2019-02-22 17:47:20 -08003884void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3885 Mutex::Autolock _l(mUidLock);
3886 auto it = mMonitoredUids.find(uid);
3887 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00003888 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08003889 } else {
Austin Borger65577682022-02-17 00:25:43 +00003890 MonitoredUid monitoredUid;
3891 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
3892 monitoredUid.refCount = 1;
3893 mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid));
Emilian Peev53722fa2019-02-22 17:47:20 -08003894 }
3895}
3896
3897void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3898 Mutex::Autolock _l(mUidLock);
3899 auto it = mMonitoredUids.find(uid);
3900 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00003901 it->second.refCount--;
3902 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003903 mMonitoredUids.erase(it);
3904 }
3905 } else {
3906 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3907 }
3908}
3909
Svet Ganov7b4ab782018-03-25 12:48:10 -07003910bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003911 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003912 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003913}
3914
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003915static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3916static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003917
Svet Ganov7b4ab782018-03-25 12:48:10 -07003918bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003919 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003920 // If activity manager is unreachable, assume everything is active
3921 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003922 return true;
3923 }
3924 auto it = mOverrideUids.find(uid);
3925 if (it != mOverrideUids.end()) {
3926 return it->second;
3927 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003928 bool active = mActiveUids.find(uid) != mActiveUids.end();
3929 if (!active) {
3930 // We want active UIDs to always access camera with their first attempt since
3931 // there is no guarantee the app is robustly written and would retry getting
3932 // the camera on failure. The inverse case is not a problem as we would take
3933 // camera away soon once we get the callback that the uid is no longer active.
3934 ActivityManager am;
3935 // Okay to access with a lock held as UID changes are dispatched without
3936 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003937 int64_t startTimeMillis = 0;
3938 do {
3939 // TODO: Fix this b/109950150!
3940 // Okay this is a hack. There is a race between the UID turning active and
3941 // activity being resumed. The proper fix is very risky, so we temporary add
3942 // some polling which should happen pretty rarely anyway as the race is hard
3943 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003944 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003945 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003946 if (active) {
3947 break;
3948 }
3949 if (startTimeMillis <= 0) {
3950 startTimeMillis = uptimeMillis();
3951 }
3952 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003953 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003954 if (remainingTimeMillis <= 0) {
3955 break;
3956 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003957 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3958
3959 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003960 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003961 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003962 } while (true);
3963
Svet Ganov7b4ab782018-03-25 12:48:10 -07003964 if (active) {
3965 // Now that we found out the UID is actually active, cache that
3966 mActiveUids.insert(uid);
3967 }
3968 }
3969 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003970}
3971
Varun Shahb42f1eb2019-04-16 14:45:13 -07003972int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3973 Mutex::Autolock _l(mUidLock);
3974 return getProcStateLocked(uid);
3975}
3976
3977int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3978 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3979 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00003980 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07003981 }
3982 return procState;
3983}
3984
Svet Ganov7b4ab782018-03-25 12:48:10 -07003985void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3986 String16 callingPackage, bool active) {
3987 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003988}
3989
Svet Ganov7b4ab782018-03-25 12:48:10 -07003990void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3991 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003992}
3993
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003994void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3995 Mutex::Autolock _l(mUidLock);
3996 ALOGV("UidPolicy: ActivityManager has died");
3997 mRegistered = false;
3998 mActiveUids.clear();
3999}
4000
Svet Ganov7b4ab782018-03-25 12:48:10 -07004001void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
4002 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004003 bool wasActive = false;
4004 bool isActive = false;
4005 {
4006 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004007 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004008 mOverrideUids.erase(uid);
4009 if (insert) {
4010 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4011 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004012 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004013 }
4014 if (wasActive != isActive && !isActive) {
4015 sp<CameraService> service = mService.promote();
4016 if (service != nullptr) {
4017 service->blockClientsForUid(uid);
4018 }
4019 }
4020}
4021
4022// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004023// SensorPrivacyPolicy
4024// ----------------------------------------------------------------------------
4025void CameraService::SensorPrivacyPolicy::registerSelf() {
4026 Mutex::Autolock _l(mSensorPrivacyLock);
4027 if (mRegistered) {
4028 return;
4029 }
Evan Severson09ab4002021-02-10 14:15:19 -08004030 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004031 mSpm.addSensorPrivacyListener(this);
4032 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
4033 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004034 if (res == OK) {
4035 mRegistered = true;
4036 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4037 }
4038}
4039
4040void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4041 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004042 mSpm.removeSensorPrivacyListener(this);
4043 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004044 mRegistered = false;
4045 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4046}
4047
4048bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
4049 Mutex::Autolock _l(mSensorPrivacyLock);
4050 return mSensorPrivacyEnabled;
4051}
4052
Evan Seversond0b69922022-01-27 10:47:34 -08004053bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004054 if (!hasCameraPrivacyFeature()) {
4055 return false;
4056 }
Evan Seversond0b69922022-01-27 10:47:34 -08004057 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004058}
4059
Evan Seversond0b69922022-01-27 10:47:34 -08004060binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
4061 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08004062 {
4063 Mutex::Autolock _l(mSensorPrivacyLock);
Kwangkyu Parke3af2992022-11-05 02:46:52 +09004064 mSensorPrivacyEnabled = enabled;
Michael Grooverd1d435a2018-12-18 17:39:42 -08004065 }
4066 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08004067 if (enabled) {
4068 sp<CameraService> service = mService.promote();
4069 if (service != nullptr) {
4070 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004071 }
4072 }
4073 return binder::Status::ok();
4074}
4075
4076void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4077 Mutex::Autolock _l(mSensorPrivacyLock);
4078 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
4079 mRegistered = false;
4080}
4081
Evan Severson09ab4002021-02-10 14:15:19 -08004082bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08004083 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
4084 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4085 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
4086 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4087 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08004088}
4089
Michael Grooverd1d435a2018-12-18 17:39:42 -08004090// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004091// CameraState
4092// ----------------------------------------------------------------------------
4093
4094CameraService::CameraState::CameraState(const String8& id, int cost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004095 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind,
4096 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004097 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004098 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08004099
4100CameraService::CameraState::~CameraState() {}
4101
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004102CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004103 Mutex::Autolock lock(mStatusLock);
4104 return mStatus;
4105}
4106
Shuzhen Wang43858162020-01-10 13:42:15 -08004107std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
4108 Mutex::Autolock lock(mStatusLock);
4109 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
4110 return res;
4111}
4112
Ruben Brunkcc776712015-02-17 20:18:47 -08004113CameraParameters CameraService::CameraState::getShimParams() const {
4114 return mShimParams;
4115}
4116
4117void CameraService::CameraState::setShimParams(const CameraParameters& params) {
4118 mShimParams = params;
4119}
4120
4121int CameraService::CameraState::getCost() const {
4122 return mCost;
4123}
4124
4125std::set<String8> CameraService::CameraState::getConflicting() const {
4126 return mConflicting;
4127}
4128
4129String8 CameraService::CameraState::getId() const {
4130 return mId;
4131}
4132
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004133SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
4134 return mSystemCameraKind;
4135}
4136
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004137bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
4138 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
4139 != mPhysicalCameras.end();
4140}
4141
Shuzhen Wang43858162020-01-10 13:42:15 -08004142bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
4143 Mutex::Autolock lock(mStatusLock);
4144 auto result = mUnavailablePhysicalIds.insert(physicalId);
4145 return result.second;
4146}
4147
4148bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
4149 Mutex::Autolock lock(mStatusLock);
4150 auto count = mUnavailablePhysicalIds.erase(physicalId);
4151 return count > 0;
4152}
4153
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004154void CameraService::CameraState::setClientPackage(const String8& clientPackage) {
4155 Mutex::Autolock lock(mStatusLock);
4156 mClientPackage = clientPackage;
4157}
4158
4159String8 CameraService::CameraState::getClientPackage() const {
4160 Mutex::Autolock lock(mStatusLock);
4161 return mClientPackage;
4162}
4163
Ruben Brunkcc776712015-02-17 20:18:47 -08004164// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07004165// ClientEventListener
4166// ----------------------------------------------------------------------------
4167
4168void CameraService::ClientEventListener::onClientAdded(
4169 const resource_policy::ClientDescriptor<String8,
4170 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004171 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004172 if (basicClient.get() != nullptr) {
4173 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4174 notifier.noteStartCamera(descriptor.getKey(),
4175 static_cast<int>(basicClient->getClientUid()));
4176 }
4177}
4178
4179void CameraService::ClientEventListener::onClientRemoved(
4180 const resource_policy::ClientDescriptor<String8,
4181 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004182 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004183 if (basicClient.get() != nullptr) {
4184 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4185 notifier.noteStopCamera(descriptor.getKey(),
4186 static_cast<int>(basicClient->getClientUid()));
4187 }
4188}
4189
4190
4191// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004192// CameraClientManager
4193// ----------------------------------------------------------------------------
4194
Ruben Brunk99e69712015-05-26 17:25:07 -07004195CameraService::CameraClientManager::CameraClientManager() {
4196 setListener(std::make_shared<ClientEventListener>());
4197}
4198
Ruben Brunkcc776712015-02-17 20:18:47 -08004199CameraService::CameraClientManager::~CameraClientManager() {}
4200
4201sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
4202 const String8& id) const {
4203 auto descriptor = get(id);
4204 if (descriptor == nullptr) {
4205 return sp<BasicClient>{nullptr};
4206 }
4207 return descriptor->getValue();
4208}
4209
4210String8 CameraService::CameraClientManager::toString() const {
4211 auto all = getAll();
4212 String8 ret("[");
4213 bool hasAny = false;
4214 for (auto& i : all) {
4215 hasAny = true;
4216 String8 key = i->getKey();
4217 int32_t cost = i->getCost();
4218 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00004219 int32_t score = i->getPriority().getScore();
4220 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08004221 auto conflicting = i->getConflicting();
4222 auto clientSp = i->getValue();
4223 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07004224 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08004225 if (clientSp.get() != nullptr) {
4226 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07004227 uid_t clientUid = clientSp->getClientUid();
4228 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004229 }
Emilian Peev8131a262017-02-01 12:33:43 +00004230 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
4231 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08004232
Ruben Brunk6267b532015-04-30 17:44:07 -07004233 if (clientSp.get() != nullptr) {
4234 ret.appendFormat("User Id: %d, ", clientUserId);
4235 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004236 if (packageName.size() != 0) {
4237 ret.appendFormat("Client Package Name: %s", packageName.string());
4238 }
4239
4240 ret.append(", Conflicting Client Devices: {");
4241 for (auto& j : conflicting) {
4242 ret.appendFormat("%s, ", j.string());
4243 }
4244 ret.append("})");
4245 }
4246 if (hasAny) ret.append("\n");
4247 ret.append("]\n");
4248 return ret;
4249}
4250
4251CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
4252 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00004253 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004254 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004255
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004256 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
4257 int32_t state_adj = systemNativeClient ? kSystemNativeClientState: state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07004258
Ruben Brunkcc776712015-02-17 20:18:47 -08004259 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004260 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
4261 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08004262}
4263
4264CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004265 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004266 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004267 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00004268 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004269 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
4270 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08004271}
4272
4273// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08004274// InjectionStatusListener
4275// ----------------------------------------------------------------------------
4276
4277void CameraService::InjectionStatusListener::addListener(
4278 const sp<ICameraInjectionCallback>& callback) {
4279 Mutex::Autolock lock(mListenerLock);
4280 if (mCameraInjectionCallback) return;
4281 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
4282 if (res == OK) {
4283 mCameraInjectionCallback = callback;
4284 }
4285}
4286
4287void CameraService::InjectionStatusListener::removeListener() {
4288 Mutex::Autolock lock(mListenerLock);
4289 if (mCameraInjectionCallback == nullptr) {
4290 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4291 return;
4292 }
4293 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
4294 mCameraInjectionCallback = nullptr;
4295}
4296
4297void CameraService::InjectionStatusListener::notifyInjectionError(
Cliff Wud3a05312021-04-26 23:07:31 +08004298 String8 injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08004299 if (mCameraInjectionCallback == nullptr) {
4300 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4301 return;
4302 }
Cliff Wud3a05312021-04-26 23:07:31 +08004303
4304 switch (err) {
4305 case -ENODEV:
4306 mCameraInjectionCallback->onInjectionError(
4307 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4308 ALOGE("No camera device with ID \"%s\" currently available!",
4309 injectedCamId.string());
4310 break;
4311 case -EBUSY:
4312 mCameraInjectionCallback->onInjectionError(
4313 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4314 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
4315 injectedCamId.string());
4316 break;
4317 case DEAD_OBJECT:
4318 mCameraInjectionCallback->onInjectionError(
4319 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4320 ALOGE("Camera ID \"%s\" object is dead!",
4321 injectedCamId.string());
4322 break;
4323 case INVALID_OPERATION:
4324 mCameraInjectionCallback->onInjectionError(
4325 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4326 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
4327 injectedCamId.string());
4328 break;
4329 case UNKNOWN_TRANSACTION:
4330 mCameraInjectionCallback->onInjectionError(
4331 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
4332 ALOGE("Camera ID \"%s\" method doesn't support!",
4333 injectedCamId.string());
4334 break;
4335 default:
4336 mCameraInjectionCallback->onInjectionError(
4337 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
4338 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
4339 strerror(-err), err, injectedCamId.string());
4340 }
Cliff Wud8cae102021-03-11 01:37:42 +08004341}
4342
4343void CameraService::InjectionStatusListener::binderDied(
4344 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08004345 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
4346 auto parent = mParent.promote();
4347 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08004348 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4349 if (clientDescriptor != nullptr) {
4350 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4351 baseClientPtr->stopInjection();
4352 }
Cliff Wu3b268182021-07-06 15:44:43 +08004353 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004354 }
4355}
4356
4357// ----------------------------------------------------------------------------
4358// CameraInjectionSession
4359// ----------------------------------------------------------------------------
4360
4361binder::Status CameraService::CameraInjectionSession::stopInjection() {
4362 Mutex::Autolock lock(mInjectionSessionLock);
4363 auto parent = mParent.promote();
4364 if (parent == nullptr) {
4365 ALOGE("CameraInjectionSession: Parent is gone");
4366 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
4367 "Camera service encountered error");
4368 }
Cliff Wud3a05312021-04-26 23:07:31 +08004369
4370 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08004371 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4372 if (clientDescriptor != nullptr) {
4373 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4374 res = baseClientPtr->stopInjection();
4375 if (res != OK) {
4376 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
4377 " ret != NO_ERROR: %d", res);
4378 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
4379 "Camera session encountered error");
4380 }
4381 }
Cliff Wu3b268182021-07-06 15:44:43 +08004382 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004383 return binder::Status::ok();
4384}
4385
4386// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07004387
4388static const int kDumpLockRetries = 50;
4389static const int kDumpLockSleep = 60000;
4390
4391static bool tryLock(Mutex& mutex)
4392{
4393 bool locked = false;
4394 for (int i = 0; i < kDumpLockRetries; ++i) {
4395 if (mutex.tryLock() == NO_ERROR) {
4396 locked = true;
4397 break;
4398 }
4399 usleep(kDumpLockSleep);
4400 }
4401 return locked;
4402}
4403
Rucha Katakwardf223072021-06-15 10:21:00 -07004404void CameraService::cacheDump() {
4405 if (mMemFd != -1) {
4406 const Vector<String16> args;
4407 ATRACE_CALL();
4408 // Acquiring service lock here will avoid the deadlock since
4409 // cacheDump will not be called during the second disconnect.
4410 Mutex::Autolock lock(mServiceLock);
4411
4412 Mutex::Autolock l(mCameraStatesLock);
4413 // Start collecting the info for open sessions and store it in temp file.
4414 for (const auto& state : mCameraStates) {
4415 String8 cameraId = state.first;
4416 auto clientDescriptor = mActiveClientManager.get(cameraId);
4417 if (clientDescriptor != nullptr) {
4418 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.string());
4419 // Log the current open session info before device is disconnected.
4420 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
4421 }
4422 }
4423 }
4424}
4425
Mathias Agopian65ab4712010-07-14 17:59:35 -07004426status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004427 ATRACE_CALL();
4428
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004429 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004430 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004431 CameraThreadState::getCallingPid(),
4432 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004433 return NO_ERROR;
4434 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004435 bool locked = tryLock(mServiceLock);
4436 // failed to lock - CameraService is probably deadlocked
4437 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004438 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004439 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004440
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004441 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004442 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07004443
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004444 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004445 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08004446
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004447 if (locked) mServiceLock.unlock();
4448 return NO_ERROR;
4449 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004450 dprintf(fd, "\n== Service global info: ==\n\n");
4451 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004452 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07004453 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
4454 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004455 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
4456 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
4457 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004458 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004459 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
4460 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Shuzhen Wang16610a62022-12-15 22:38:07 -08004461 if (mStreamUseCaseOverrides.size() > 0) {
4462 dprintf(fd, "Active stream use case overrides:");
4463 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
4464 dprintf(fd, " %" PRId64, useCaseOverride);
4465 }
4466 dprintf(fd, "\n");
4467 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004468
4469 dumpEventLog(fd);
4470
4471 bool stateLocked = tryLock(mCameraStatesLock);
4472 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004473 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004474 }
4475
Emilian Peevbd8c5032018-02-14 23:05:40 +00004476 int argSize = args.size();
4477 for (int i = 0; i < argSize; i++) {
4478 if (args[i] == TagMonitor::kMonitorOption) {
4479 if (i + 1 < argSize) {
4480 mMonitorTags = String8(args[i + 1]);
4481 }
4482 break;
4483 }
4484 }
4485
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004486 for (auto& state : mCameraStates) {
4487 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004488
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004489 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004490
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004491 CameraParameters p = state.second->getShimParams();
4492 if (!p.isEmpty()) {
4493 dprintf(fd, " Camera1 API shim is using parameters:\n ");
4494 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004495 }
4496
4497 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004498 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004499 // log the current open session info
4500 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004501 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07004502 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004503 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004504
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004505 }
4506
4507 if (stateLocked) mCameraStatesLock.unlock();
4508
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004509 if (locked) mServiceLock.unlock();
4510
Emilian Peevf53f66e2017-04-11 14:29:43 +01004511 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004512
4513 dprintf(fd, "\n== Vendor tags: ==\n\n");
4514
4515 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
4516 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00004517 sp<VendorTagDescriptorCache> cache =
4518 VendorTagDescriptorCache::getGlobalVendorTagCache();
4519 if (cache == NULL) {
4520 dprintf(fd, "No vendor tags.\n");
4521 } else {
4522 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
4523 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004524 } else {
4525 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
4526 }
4527
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004528 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004529 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004530 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004531
4532 // Process dump arguments, if any
4533 int n = args.size();
4534 String16 verboseOption("-v");
4535 String16 unreachableOption("--unreachable");
4536 for (int i = 0; i < n; i++) {
4537 if (args[i] == verboseOption) {
4538 // change logging level
4539 if (i + 1 >= n) continue;
4540 String8 levelStr(args[i+1]);
4541 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004542 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004543 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004544 } else if (args[i] == unreachableOption) {
4545 // Dump memory analysis
4546 // TODO - should limit be an argument parameter?
4547 UnreachableMemoryInfo info;
4548 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
4549 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004550 dprintf(fd, "\n== Unable to dump unreachable memory. "
4551 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004552 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004553 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004554 std::string s = info.ToString(/*log_contents*/ true);
4555 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004556 }
4557 }
4558 }
Rucha Katakwardf223072021-06-15 10:21:00 -07004559
4560 bool serviceLocked = tryLock(mServiceLock);
4561
4562 // Dump info from previous open sessions.
4563 // Reposition the offset to beginning of the file before reading
4564
4565 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
4566 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
4567 ssize_t size_read;
4568 char buf[4096];
4569 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
4570 // Read data from file to a small buffer and write it to fd.
4571 write(fd, buf, size_read);
4572 if (size_read == -1) {
4573 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4574 break;
4575 }
4576 }
4577 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
4578 } else {
4579 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4580 }
4581
4582 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004583 return NO_ERROR;
4584}
4585
Rucha Katakwardf223072021-06-15 10:21:00 -07004586void CameraService::dumpOpenSessionClientLogs(int fd,
4587 const Vector<String16>& args, const String8& cameraId) {
4588 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07004589 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
4590 getFormattedCurrentTime().string(),
4591 cameraId.string());
Rucha Katakwardf223072021-06-15 10:21:00 -07004592 dprintf(fd, " Client priority score: %d state: %d\n",
4593 clientDescriptor->getPriority().getScore(),
4594 clientDescriptor->getPriority().getState());
4595 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
4596
4597 auto client = clientDescriptor->getValue();
4598 dprintf(fd, " Client package: %s\n",
4599 String8(client->getPackageName()).string());
4600
4601 client->dumpClient(fd, args);
4602}
4603
4604void CameraService::dumpClosedSessionClientLogs(int fd, const String8& cameraId) {
4605 dprintf(fd, " Device %s is closed, no client instance\n",
4606 cameraId.string());
4607}
4608
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004609void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004610 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004611
4612 Mutex::Autolock l(mLogLock);
4613 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004614 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004615 }
4616
4617 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004618 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004619 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004620 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004621 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004622 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004623}
4624
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004625void CameraService::cacheClientTagDumpIfNeeded(const char *cameraId, BasicClient* client) {
4626 Mutex::Autolock lock(mLogLock);
4627 if (!isClientWatchedLocked(client)) { return; }
4628
4629 std::vector<std::string> dumpVector;
4630 client->dumpWatchedEventsToVector(dumpVector);
4631
4632 if (dumpVector.empty()) { return; }
4633
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004634 std::string dumpString;
4635
4636 String8 currentTime = getFormattedCurrentTime();
4637 dumpString += "Cached @ ";
4638 dumpString += currentTime.string();
4639 dumpString += "\n"; // First line is the timestamp of when client is cached.
4640
4641
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004642 const String16 &packageName = client->getPackageName();
4643
4644 String8 packageName8 = String8(packageName);
4645 const char *printablePackageName = packageName8.lockBuffer(packageName.size());
4646
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004647
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004648 size_t i = dumpVector.size();
4649
4650 // Store the string in reverse order (latest last)
4651 while (i > 0) {
4652 i--;
4653 dumpString += cameraId;
4654 dumpString += ":";
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004655 dumpString += printablePackageName;
4656 dumpString += " ";
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004657 dumpString += dumpVector[i]; // implicitly ends with '\n'
4658 }
4659
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004660 packageName8.unlockBuffer();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004661 mWatchedClientsDumpCache[packageName] = dumpString;
4662}
4663
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004664void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004665 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004666 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
4667 if (mTorchClientMap[i] == who) {
4668 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004669 String8 cameraId = mTorchClientMap.keyAt(i);
4670 status_t res = mFlashlight->setTorchMode(cameraId, false);
4671 if (res) {
4672 ALOGE("%s: torch client died but couldn't turn off torch: "
4673 "%s (%d)", __FUNCTION__, strerror(-res), res);
4674 return;
4675 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004676 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004677 break;
4678 }
4679 }
4680}
4681
Ruben Brunkcc776712015-02-17 20:18:47 -08004682/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07004683
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004684 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07004685 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
4686 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004687 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08004688 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004689 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004690
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004691 // check torch client
4692 handleTorchClientBinderDied(who);
4693
4694 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08004695 if(!evictClientIdByRemote(who)) {
4696 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004697 return;
4698 }
4699
Ruben Brunkcc776712015-02-17 20:18:47 -08004700 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
4701 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004702}
4703
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004704void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004705 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08004706}
4707
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004708void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
4709 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004710 // Do not lock mServiceLock here or can get into a deadlock from
4711 // connect() -> disconnect -> updateStatus
4712
4713 auto state = getCameraState(cameraId);
4714
4715 if (state == nullptr) {
4716 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4717 cameraId.string());
4718 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07004719 }
4720
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004721 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
4722 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
4723 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
4724 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
4725 return;
4726 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004727
4728 // Collect the logical cameras without holding mStatusLock in updateStatus
4729 // as that can lead to a deadlock(b/162192331).
4730 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08004731 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08004732 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07004733 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004734 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004735 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004736
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004737 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004738 // Update torch status if it has a flash unit.
4739 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004740 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004741 if (getTorchStatusLocked(cameraId, &torchStatus) !=
4742 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004743 TorchModeStatus newTorchStatus =
4744 status == StatusInternal::PRESENT ?
4745 TorchModeStatus::AVAILABLE_OFF :
4746 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004747 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07004748 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004749 }
4750 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004751 }
4752
4753 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004754 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
4755 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08004756
Ruben Brunkcc776712015-02-17 20:18:47 -08004757 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07004758 bool isVendorListener = listener->isVendorListener();
4759 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
4760 listener->getListenerPid(), listener->getListenerUid()) ||
Shuzhen Wangb8259792021-05-27 09:27:06 -07004761 isVendorListener) {
4762 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004763 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08004764 continue;
4765 }
Austin Borgere8e2c422022-05-12 13:45:24 -07004766 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08004767 String16(cameraId));
Austin Borgere8e2c422022-05-12 13:45:24 -07004768 listener->handleBinderStatus(ret,
4769 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
4770 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
4771 ret.exceptionCode());
Ruben Brunkcc776712015-02-17 20:18:47 -08004772 }
4773 });
Igor Murashkincba2c162013-03-20 15:56:31 -07004774}
4775
Shuzhen Wang695044d2020-03-06 09:02:23 -08004776void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
4777 const String16& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004778 auto state = getCameraState(cameraId);
4779 if (state == nullptr) {
4780 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4781 cameraId.string());
4782 return;
4783 }
4784 if (open) {
4785 state->setClientPackage(String8(clientPackageName));
4786 } else {
4787 state->setClientPackage(String8::empty());
4788 }
4789
Shuzhen Wang695044d2020-03-06 09:02:23 -08004790 Mutex::Autolock lock(mStatusListenerLock);
4791
4792 for (const auto& it : mListenerList) {
4793 if (!it->isOpenCloseCallbackAllowed()) {
4794 continue;
4795 }
4796
4797 binder::Status ret;
4798 String16 cameraId64(cameraId);
4799 if (open) {
4800 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
4801 } else {
4802 ret = it->getListener()->onCameraClosed(cameraId64);
4803 }
Austin Borgere8e2c422022-05-12 13:45:24 -07004804
4805 it->handleBinderStatus(ret,
4806 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
4807 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08004808 }
4809}
4810
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004811template<class Func>
4812void CameraService::CameraState::updateStatus(StatusInternal status,
4813 const String8& cameraId,
4814 std::initializer_list<StatusInternal> rejectSourceStates,
4815 Func onStatusUpdatedLocked) {
4816 Mutex::Autolock lock(mStatusLock);
4817 StatusInternal oldStatus = mStatus;
4818 mStatus = status;
4819
4820 if (oldStatus == status) {
4821 return;
4822 }
4823
4824 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
4825 cameraId.string(), oldStatus, status);
4826
4827 if (oldStatus == StatusInternal::NOT_PRESENT &&
4828 (status != StatusInternal::PRESENT &&
4829 status != StatusInternal::ENUMERATING)) {
4830
4831 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
4832 __FUNCTION__);
4833 mStatus = oldStatus;
4834 return;
4835 }
4836
4837 /**
4838 * Sometimes we want to conditionally do a transition.
4839 * For example if a client disconnects, we want to go to PRESENT
4840 * only if we weren't already in NOT_PRESENT or ENUMERATING.
4841 */
4842 for (auto& rejectStatus : rejectSourceStates) {
4843 if (oldStatus == rejectStatus) {
4844 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
4845 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
4846 mStatus = oldStatus;
4847 return;
4848 }
4849 }
4850
4851 onStatusUpdatedLocked(cameraId, status);
4852}
4853
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004854status_t CameraService::getTorchStatusLocked(
4855 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004856 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004857 if (!status) {
4858 return BAD_VALUE;
4859 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004860 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4861 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004862 // invalid camera ID or the camera doesn't have a flash unit
4863 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004864 }
4865
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004866 *status = mTorchStatusMap.valueAt(index);
4867 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004868}
4869
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004870status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004871 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004872 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4873 if (index == NAME_NOT_FOUND) {
4874 return BAD_VALUE;
4875 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004876 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004877
4878 return OK;
4879}
4880
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004881std::list<String16> CameraService::getLogicalCameras(
4882 const String8& physicalCameraId) {
4883 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08004884 Mutex::Autolock lock(mCameraStatesLock);
4885 for (const auto& state : mCameraStates) {
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004886 if (state.second->containsPhysicalCamera(physicalCameraId.c_str())) {
4887 retList.emplace_back(String16(state.first));
Shuzhen Wang43858162020-01-10 13:42:15 -08004888 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004889 }
4890 return retList;
4891}
4892
4893void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
4894 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
4895 SystemCameraKind deviceKind) {
4896 // mStatusListenerLock is expected to be locked
4897 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004898 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004899 // Note: we check only the deviceKind of the physical camera id
4900 // since, logical camera ids and their physical camera ids are
4901 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004902 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
4903 listener->getListenerPid(), listener->getListenerUid())) {
4904 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004905 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004906 continue;
4907 }
Austin Borgere8e2c422022-05-12 13:45:24 -07004908 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004909 logicalCameraId, physicalCameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07004910 listener->handleBinderStatus(ret,
4911 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
4912 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
4913 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08004914 }
4915 }
4916}
4917
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004918
Svet Ganova453d0d2018-01-11 15:37:58 -08004919void CameraService::blockClientsForUid(uid_t uid) {
4920 const auto clients = mActiveClientManager.getAll();
4921 for (auto& current : clients) {
4922 if (current != nullptr) {
4923 const auto basicClient = current->getValue();
4924 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
4925 basicClient->block();
4926 }
4927 }
4928 }
4929}
4930
Michael Grooverd1d435a2018-12-18 17:39:42 -08004931void CameraService::blockAllClients() {
4932 const auto clients = mActiveClientManager.getAll();
4933 for (auto& current : clients) {
4934 if (current != nullptr) {
4935 const auto basicClient = current->getValue();
4936 if (basicClient.get() != nullptr) {
4937 basicClient->block();
4938 }
4939 }
4940 }
4941}
4942
Svet Ganova453d0d2018-01-11 15:37:58 -08004943// NOTE: This is a remote API - make sure all args are validated
4944status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
4945 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
4946 return PERMISSION_DENIED;
4947 }
4948 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
4949 return BAD_VALUE;
4950 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004951 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004952 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004953 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004954 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004955 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004956 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004957 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
4958 return handleSetRotateAndCrop(args);
4959 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
4960 return handleGetRotateAndCrop(out);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00004961 } else if (args.size() >= 2 && args[0] == String16("set-autoframing")) {
4962 return handleSetAutoframing(args);
4963 } else if (args.size() >= 1 && args[0] == String16("get-autoframing")) {
4964 return handleGetAutoframing(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004965 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
4966 return handleSetImageDumpMask(args);
4967 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
4968 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004969 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
4970 return handleSetCameraMute(args);
Shuzhen Wang16610a62022-12-15 22:38:07 -08004971 } else if (args.size() >= 2 && args[0] == String16("set-stream-use-case-override")) {
4972 return handleSetStreamUseCaseOverrides(args);
4973 } else if (args.size() >= 1 && args[0] == String16("clear-stream-use-case-override")) {
4974 handleClearStreamUseCaseOverrides();
4975 return OK;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004976 } else if (args.size() >= 2 && args[0] == String16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08004977 return handleWatchCommand(args, in, out);
Ravneetaeb20dc2022-03-30 05:33:03 +00004978 } else if (args.size() >= 2 && args[0] == String16("set-watchdog")) {
4979 return handleSetCameraServiceWatchdog(args);
Svet Ganova453d0d2018-01-11 15:37:58 -08004980 } else if (args.size() == 1 && args[0] == String16("help")) {
4981 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004982 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08004983 }
4984 printHelp(err);
4985 return BAD_VALUE;
4986}
4987
4988status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004989 String16 packageName = args[1];
4990
Svet Ganova453d0d2018-01-11 15:37:58 -08004991 bool active = false;
4992 if (args[2] == String16("active")) {
4993 active = true;
4994 } else if ((args[2] != String16("idle"))) {
4995 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
4996 return BAD_VALUE;
4997 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004998
4999 int userId = 0;
5000 if (args.size() >= 5 && args[3] == String16("--user")) {
5001 userId = atoi(String8(args[4]));
5002 }
5003
5004 uid_t uid;
5005 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5006 return BAD_VALUE;
5007 }
5008
5009 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005010 return NO_ERROR;
5011}
5012
5013status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07005014 String16 packageName = args[1];
5015
5016 int userId = 0;
5017 if (args.size() >= 4 && args[2] == String16("--user")) {
5018 userId = atoi(String8(args[3]));
5019 }
5020
5021 uid_t uid;
5022 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005023 return BAD_VALUE;
5024 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005025
5026 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005027 return NO_ERROR;
5028}
5029
5030status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07005031 String16 packageName = args[1];
5032
5033 int userId = 0;
5034 if (args.size() >= 4 && args[2] == String16("--user")) {
5035 userId = atoi(String8(args[3]));
5036 }
5037
5038 uid_t uid;
5039 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005040 return BAD_VALUE;
5041 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005042
5043 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005044 return dprintf(out, "active\n");
5045 } else {
5046 return dprintf(out, "idle\n");
5047 }
5048}
5049
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005050status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
5051 int rotateValue = atoi(String8(args[1]));
5052 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
5053 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
5054 Mutex::Autolock lock(mServiceLock);
5055
5056 mOverrideRotateAndCropMode = rotateValue;
5057
5058 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
5059
5060 const auto clients = mActiveClientManager.getAll();
5061 for (auto& current : clients) {
5062 if (current != nullptr) {
5063 const auto basicClient = current->getValue();
5064 if (basicClient.get() != nullptr) {
5065 basicClient->setRotateAndCropOverride(rotateValue);
5066 }
5067 }
5068 }
5069
5070 return OK;
5071}
5072
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005073status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
5074 char* end;
5075 int autoframingValue = (int) strtol(String8(args[1]), &end, /*base=*/10);
5076 if ((*end != '\0') ||
5077 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
5078 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
5079 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
5080 return BAD_VALUE;
5081 }
5082
5083 Mutex::Autolock lock(mServiceLock);
5084 mOverrideAutoframingMode = autoframingValue;
5085
5086 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
5087
5088 const auto clients = mActiveClientManager.getAll();
5089 for (auto& current : clients) {
5090 if (current != nullptr) {
5091 const auto basicClient = current->getValue();
5092 if (basicClient.get() != nullptr) {
5093 basicClient->setAutoframingOverride(autoframingValue);
5094 }
5095 }
5096 }
5097
5098 return OK;
5099}
5100
Ravneetaeb20dc2022-03-30 05:33:03 +00005101status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
5102 int enableWatchdog = atoi(String8(args[1]));
5103
5104 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
5105
5106 Mutex::Autolock lock(mServiceLock);
5107
5108 mCameraServiceWatchdogEnabled = enableWatchdog;
5109
5110 const auto clients = mActiveClientManager.getAll();
5111 for (auto& current : clients) {
5112 if (current != nullptr) {
5113 const auto basicClient = current->getValue();
5114 if (basicClient.get() != nullptr) {
5115 basicClient->setCameraServiceWatchdog(enableWatchdog);
5116 }
5117 }
5118 }
5119
5120 return OK;
5121}
5122
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005123status_t CameraService::handleGetRotateAndCrop(int out) {
5124 Mutex::Autolock lock(mServiceLock);
5125
5126 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
5127}
5128
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005129status_t CameraService::handleGetAutoframing(int out) {
5130 Mutex::Autolock lock(mServiceLock);
5131
5132 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
5133}
5134
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005135status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
5136 char *endPtr;
5137 errno = 0;
5138 String8 maskString8 = String8(args[1]);
5139 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
5140
5141 if (errno != 0) return BAD_VALUE;
5142 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
5143 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
5144
5145 Mutex::Autolock lock(mServiceLock);
5146
5147 mImageDumpMask = maskValue;
5148
5149 return OK;
5150}
5151
5152status_t CameraService::handleGetImageDumpMask(int out) {
5153 Mutex::Autolock lock(mServiceLock);
5154
5155 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
5156}
5157
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005158status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
5159 int muteValue = strtol(String8(args[1]), nullptr, 10);
5160 if (errno != 0) return BAD_VALUE;
5161
5162 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
5163 Mutex::Autolock lock(mServiceLock);
5164
5165 mOverrideCameraMuteMode = (muteValue == 1);
5166
5167 const auto clients = mActiveClientManager.getAll();
5168 for (auto& current : clients) {
5169 if (current != nullptr) {
5170 const auto basicClient = current->getValue();
5171 if (basicClient.get() != nullptr) {
5172 if (basicClient->supportsCameraMute()) {
5173 basicClient->setCameraMute(mOverrideCameraMuteMode);
5174 }
5175 }
5176 }
5177 }
5178
5179 return OK;
5180}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005181
Shuzhen Wang16610a62022-12-15 22:38:07 -08005182status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
5183 std::vector<int64_t> useCasesOverride;
5184 for (size_t i = 1; i < args.size(); i++) {
5185 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
5186 String8 arg8 = String8(args[i]);
5187 if (arg8 == "DEFAULT") {
5188 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
5189 } else if (arg8 == "PREVIEW") {
5190 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
5191 } else if (arg8 == "STILL_CAPTURE") {
5192 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
5193 } else if (arg8 == "VIDEO_RECORD") {
5194 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
5195 } else if (arg8 == "PREVIEW_VIDEO_STILL") {
5196 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
5197 } else if (arg8 == "VIDEO_CALL") {
5198 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
5199 } else if (arg8 == "CROPPED_RAW") {
5200 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
5201 } else {
5202 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg8.c_str());
5203 return BAD_VALUE;
5204 }
5205 useCasesOverride.push_back(useCase);
5206 }
5207
5208 Mutex::Autolock lock(mServiceLock);
5209 mStreamUseCaseOverrides = std::move(useCasesOverride);
5210
5211 return OK;
5212}
5213
5214void CameraService::handleClearStreamUseCaseOverrides() {
5215 Mutex::Autolock lock(mServiceLock);
5216 mStreamUseCaseOverrides.clear();
5217}
5218
Avichal Rakesh84147132021-11-11 17:47:11 -08005219status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005220 if (args.size() >= 3 && args[1] == String16("start")) {
5221 return startWatchingTags(args, outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005222 } else if (args.size() == 2 && args[1] == String16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005223 return stopWatchingTags(outFd);
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005224 } else if (args.size() == 2 && args[1] == String16("dump")) {
5225 return printWatchedTags(outFd);
5226 } else if (args.size() >= 2 && args[1] == String16("live")) {
5227 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005228 } else if (args.size() == 2 && args[1] == String16("clear")) {
5229 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005230 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005231 dprintf(outFd, "Camera service watch commands:\n"
5232 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
5233 " starts watching the provided tags for clients with provided package\n"
5234 " recognizes tag shorthands like '3a'\n"
5235 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005236 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005237 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005238 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005239 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08005240 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005241 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005242 return BAD_VALUE;
5243}
5244
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005245status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
5246 Mutex::Autolock lock(mLogLock);
5247 size_t tagsIdx; // index of '-m'
5248 String16 tags("");
5249 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != String16("-m"); tagsIdx++);
5250 if (tagsIdx < args.size() - 1) {
5251 tags = args[tagsIdx + 1];
5252 } else {
5253 dprintf(outFd, "No tags provided.\n");
5254 return BAD_VALUE;
5255 }
5256
5257 size_t clientsIdx; // index of '-c'
5258 String16 clients = kWatchAllClientsFlag; // watch all clients if no clients are provided
5259 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != String16("-c");
5260 clientsIdx++);
5261 if (clientsIdx < args.size() - 1) {
5262 clients = args[clientsIdx + 1];
5263 }
5264 parseClientsToWatchLocked(String8(clients));
5265
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005266 // track tags to initialize future clients with the monitoring information
5267 mMonitorTags = String8(tags);
5268
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005269 bool serviceLock = tryLock(mServiceLock);
5270 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005271 auto cameraClients = mActiveClientManager.getAll();
5272 for (const auto &clientDescriptor: cameraClients) {
5273 if (clientDescriptor == nullptr) { continue; }
5274 sp<BasicClient> client = clientDescriptor->getValue();
5275 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005276
5277 if (isClientWatchedLocked(client.get())) {
5278 client->startWatchingTags(mMonitorTags, outFd);
5279 numWatchedClients++;
5280 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005281 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005282 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
5283
5284 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005285 return OK;
5286}
5287
5288status_t CameraService::stopWatchingTags(int outFd) {
5289 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005290 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005291 mMonitorTags = String8::empty();
5292
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005293 mWatchedClientPackages.clear();
5294 mWatchedClientsDumpCache.clear();
5295
5296 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005297 auto cameraClients = mActiveClientManager.getAll();
5298 for (const auto &clientDescriptor : cameraClients) {
5299 if (clientDescriptor == nullptr) { continue; }
5300 sp<BasicClient> client = clientDescriptor->getValue();
5301 if (client.get() == nullptr) { continue; }
5302 client->stopWatchingTags(outFd);
5303 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005304 dprintf(outFd, "Stopped watching all clients.\n");
5305 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005306 return OK;
5307}
5308
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005309status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
5310 Mutex::Autolock lock(mLogLock);
5311 size_t clearedSize = mWatchedClientsDumpCache.size();
5312 mWatchedClientsDumpCache.clear();
5313 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
5314 return OK;
5315}
5316
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005317status_t CameraService::printWatchedTags(int outFd) {
5318 Mutex::Autolock logLock(mLogLock);
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08005319 std::set<String16> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005320
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005321 bool printedSomething = false; // tracks if any monitoring information was printed
5322 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005323
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005324 bool serviceLock = tryLock(mServiceLock);
5325 // get all watched clients that are currently connected
5326 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
5327 if (clientDescriptor == nullptr) { continue; }
5328
5329 sp<BasicClient> client = clientDescriptor->getValue();
5330 if (client.get() == nullptr) { continue; }
5331 if (!isClientWatchedLocked(client.get())) { continue; }
5332
5333 std::vector<std::string> dumpVector;
5334 client->dumpWatchedEventsToVector(dumpVector);
5335
5336 size_t printIdx = dumpVector.size();
5337 if (printIdx == 0) {
5338 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005339 }
5340
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005341 // Print tag dumps for active client
5342 const String8 &cameraId = clientDescriptor->getKey();
5343 String8 packageName8 = String8(client->getPackageName());
5344 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
5345 dprintf(outFd, "Client: %s (active)\n", printablePackageName);
5346 while(printIdx > 0) {
5347 printIdx--;
5348 dprintf(outFd, "%s:%s %s", cameraId.string(), printablePackageName,
5349 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005350 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005351 dprintf(outFd, "\n");
5352 packageName8.unlockBuffer();
5353 printedSomething = true;
5354
5355 connectedMonitoredClients.emplace(client->getPackageName());
5356 }
5357 if (serviceLock) { mServiceLock.unlock(); }
5358
5359 // Print entries in mWatchedClientsDumpCache for clients that are not connected
5360 for (const auto &kv: mWatchedClientsDumpCache) {
5361 const String16 &package = kv.first;
5362 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
5363 continue;
5364 }
5365
5366 dprintf(outFd, "Client: %s (cached)\n", String8(package).string());
5367 dprintf(outFd, "%s\n", kv.second.c_str());
5368 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005369 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005370
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005371 if (!printedSomething) {
5372 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005373 }
5374
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005375 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005376}
5377
Avichal Rakesh84147132021-11-11 17:47:11 -08005378// Print all events in vector `events' that came after lastPrintedEvent
5379void printNewWatchedEvents(int outFd,
5380 const char *cameraId,
5381 const String16 &packageName,
5382 const std::vector<std::string> &events,
5383 const std::string &lastPrintedEvent) {
5384 if (events.empty()) { return; }
5385
5386 // index of lastPrintedEvent in events.
5387 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
5388 size_t lastPrintedIdx;
5389 for (lastPrintedIdx = 0;
5390 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
5391 lastPrintedIdx++);
5392
5393 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
5394
5395 String8 packageName8(packageName);
5396 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
5397
5398 // print events in chronological order (latest event last)
5399 size_t idxToPrint = lastPrintedIdx;
5400 do {
5401 idxToPrint--;
5402 dprintf(outFd, "%s:%s %s", cameraId, printablePackageName, events[idxToPrint].c_str());
5403 } while (idxToPrint != 0);
5404
5405 packageName8.unlockBuffer();
5406}
5407
5408// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
5409// command should be interrupted if the user presses the return key, or if user loses any way to
5410// signal interrupt.
5411// If timeoutMs == 0, this function will always return false
5412bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
5413 struct timeval startTime;
5414 int startTimeError = gettimeofday(&startTime, nullptr);
5415 if (startTimeError) {
5416 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5417 return true;
5418 }
5419
5420 const nfds_t numFds = 1;
5421 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
5422
5423 struct timeval currTime;
5424 char buffer[2];
5425 while(true) {
5426 int currTimeError = gettimeofday(&currTime, nullptr);
5427 if (currTimeError) {
5428 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5429 return true;
5430 }
5431
5432 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
5433 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
5434 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
5435
5436 if (remainingTimeMs <= 0) {
5437 // No user interrupt within timeoutMs, don't interrupt watch command
5438 return false;
5439 }
5440
5441 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
5442 if (numFdsUpdated < 0) {
5443 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5444 return true;
5445 }
5446
5447 if (numFdsUpdated == 0) {
5448 // No user input within timeoutMs, don't interrupt watch command
5449 return false;
5450 }
5451
5452 if (!(pollFd.revents & POLLIN)) {
5453 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5454 return true;
5455 }
5456
5457 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
5458 if (sizeRead < 0) {
5459 dprintf(outFd, "Error reading user input. Exiting.\n");
5460 return true;
5461 }
5462
5463 if (sizeRead == 0) {
5464 // Reached end of input fd (can happen if input is piped)
5465 // User has no way to signal an interrupt, so interrupt here
5466 return true;
5467 }
5468
5469 if (buffer[0] == '\n') {
5470 // User pressed return, interrupt watch command.
5471 return true;
5472 }
5473 }
5474}
5475
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005476status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
5477 int inFd, int outFd) {
5478 // Figure out refresh interval, if present in args
5479 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005480 if (args.size() > 2) {
5481 size_t intervalIdx; // index of '-n'
5482 for (intervalIdx = 2; intervalIdx < args.size() && String16("-n") != args[intervalIdx];
5483 intervalIdx++);
5484
5485 size_t intervalValIdx = intervalIdx + 1;
5486 if (intervalValIdx < args.size()) {
5487 refreshTimeoutMs = strtol(String8(args[intervalValIdx].string()), nullptr, 10);
5488 if (errno) { return BAD_VALUE; }
5489 }
5490 }
5491
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005492 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
5493 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005494
Avichal Rakesh84147132021-11-11 17:47:11 -08005495 dprintf(outFd, "Press return to exit...\n\n");
Avichal Rakesha14d9832021-11-11 01:41:55 -08005496 std::map<String16, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005497
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005498 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005499 bool serviceLock = tryLock(mServiceLock);
5500 auto cameraClients = mActiveClientManager.getAll();
5501 if (serviceLock) { mServiceLock.unlock(); }
5502
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005503 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005504 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005505 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005506
5507 sp<BasicClient> client = clientDescriptor->getValue();
5508 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005509 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005510
Avichal Rakesha14d9832021-11-11 01:41:55 -08005511 const String16 &packageName = client->getPackageName();
5512 // This also initializes the map entries with an empty string
5513 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
5514
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005515 std::vector<std::string> latestEvents;
5516 client->dumpWatchedEventsToVector(latestEvents);
5517
5518 if (!latestEvents.empty()) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005519 String8 cameraId = clientDescriptor->getKey();
5520 const char *printableCameraId = cameraId.lockBuffer(cameraId.size());
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005521 printNewWatchedEvents(outFd,
Avichal Rakesha14d9832021-11-11 01:41:55 -08005522 printableCameraId,
5523 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005524 latestEvents,
5525 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08005526 packageNameToLastEvent[packageName] = latestEvents[0];
5527 cameraId.unlockBuffer();
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005528 }
5529 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005530 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005531 break;
5532 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005533 }
5534 return OK;
5535}
5536
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005537void CameraService::parseClientsToWatchLocked(String8 clients) {
5538 mWatchedClientPackages.clear();
5539
5540 const char *allSentinel = String8(kWatchAllClientsFlag).string();
5541
5542 char *tokenized = clients.lockBuffer(clients.size());
5543 char *savePtr;
5544 char *nextClient = strtok_r(tokenized, ",", &savePtr);
5545
5546 while (nextClient != nullptr) {
5547 if (strcmp(nextClient, allSentinel) == 0) {
5548 // Don't need to track any other package if 'all' is present
5549 mWatchedClientPackages.clear();
5550 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
5551 break;
5552 }
5553
5554 // track package names
5555 mWatchedClientPackages.emplace(nextClient);
5556 nextClient = strtok_r(nullptr, ",", &savePtr);
5557 }
5558 clients.unlockBuffer();
5559}
5560
Svet Ganova453d0d2018-01-11 15:37:58 -08005561status_t CameraService::printHelp(int out) {
5562 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07005563 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
5564 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
5565 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005566 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
5567 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
5568 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005569 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
5570 " Valid values 0=false, 1=true, 2=auto\n"
5571 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005572 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
5573 " Valid values 0=OFF, 1=ON for JPEG\n"
5574 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005575 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08005576 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
5577 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
5578 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
5579 " on. In case the number of usecases is smaller than the number of streams, the\n"
5580 " last use case is assigned to all the remaining streams. In case of multiple\n"
5581 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
5582 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
5583 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
5584 " clear-stream-use-case-override clear the stream use case override\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005585 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08005586 " help print this message\n");
5587}
5588
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005589bool CameraService::isClientWatched(const BasicClient *client) {
5590 Mutex::Autolock lock(mLogLock);
5591 return isClientWatchedLocked(client);
5592}
5593
5594bool CameraService::isClientWatchedLocked(const BasicClient *client) {
5595 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
5596 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
5597}
5598
Yin-Chia Yehdba03232019-08-19 15:54:28 -07005599int32_t CameraService::updateAudioRestriction() {
5600 Mutex::Autolock lock(mServiceLock);
5601 return updateAudioRestrictionLocked();
5602}
5603
5604int32_t CameraService::updateAudioRestrictionLocked() {
5605 int32_t mode = 0;
5606 // iterate through all active client
5607 for (const auto& i : mActiveClientManager.getAll()) {
5608 const auto clientSp = i->getValue();
5609 mode |= clientSp->getAudioRestriction();
5610 }
5611
5612 bool modeChanged = (mAudioRestriction != mode);
5613 mAudioRestriction = mode;
5614 if (modeChanged) {
5615 mAppOps.setCameraAudioRestriction(mode);
5616 }
5617 return mode;
5618}
5619
Cliff Wu646bd612021-11-23 23:21:29 +08005620status_t CameraService::checkIfInjectionCameraIsPresent(const String8& externalCamId,
5621 sp<BasicClient> clientSp) {
5622 std::unique_ptr<AutoConditionLock> lock =
5623 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
5624 status_t res = NO_ERROR;
5625 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
5626 ALOGW("Device %s is not usable!", externalCamId.string());
5627 mInjectionStatusListener->notifyInjectionError(
5628 externalCamId, UNKNOWN_TRANSACTION);
5629 clientSp->notifyError(
5630 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
5631 CaptureResultExtras());
5632
5633 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
5634 // other clients from connecting in mServiceLockWrapper if held
5635 mServiceLock.unlock();
5636
5637 // Clear caller identity temporarily so client disconnect PID checks work correctly
5638 int64_t token = CameraThreadState::clearCallingIdentity();
5639 clientSp->disconnect();
5640 CameraThreadState::restoreCallingIdentity(token);
5641
5642 // Reacquire mServiceLock
5643 mServiceLock.lock();
5644 }
5645
5646 return res;
5647}
5648
Cliff Wud3a05312021-04-26 23:07:31 +08005649void CameraService::clearInjectionParameters() {
5650 {
5651 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08005652 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08005653 mInjectionInternalCamId = "";
5654 }
5655 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08005656 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08005657}
5658
Mathias Agopian65ab4712010-07-14 17:59:35 -07005659}; // namespace android