blob: 8221a838659dc5d397d9823018efd8e9b657c2a0 [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";
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080084 const char* kActivityServiceName = "activity";
85 const char* kSensorPrivacyServiceName = "sensor_privacy";
86 const char* kAppopsServiceName = "appops";
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080087}; // namespace anonymous
88
Mathias Agopian65ab4712010-07-14 17:59:35 -070089namespace android {
90
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070091using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080092using binder::Status;
Austin Borgerea931242021-12-13 23:10:41 +000093using namespace camera3;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070094using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -070095using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080096using hardware::ICamera;
97using hardware::ICameraClient;
98using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +080099using hardware::camera2::ICameraInjectionCallback;
100using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800101using hardware::camera2::utils::CameraIdAndSessionConfiguration;
102using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800103
Mathias Agopian65ab4712010-07-14 17:59:35 -0700104// ----------------------------------------------------------------------------
105// Logging support -- this is for debugging only
106// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700107volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108
Steve Blockb8a80522011-12-20 16:23:08 +0000109#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
110#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700111
112static void setLogLevel(int level) {
113 android_atomic_write(level, &gLogLevel);
114}
115
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800116// Convenience methods for constructing binder::Status objects for error returns
117
118#define STATUS_ERROR(errorCode, errorString) \
119 binder::Status::fromServiceSpecificError(errorCode, \
120 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
121
122#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
123 binder::Status::fromServiceSpecificError(errorCode, \
124 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
125 __VA_ARGS__))
126
Mathias Agopian65ab4712010-07-14 17:59:35 -0700127// ----------------------------------------------------------------------------
128
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700129static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800130static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700131static const String16 sCameraPermission("android.permission.CAMERA");
132static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
133static const String16
134 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Shuzhen Wang695044d2020-03-06 09:02:23 -0800135static const String16 sCameraOpenCloseListenerPermission(
136 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Cliff Wud8cae102021-03-11 01:37:42 +0800137static const String16
138 sCameraInjectExternalCameraPermission("android.permission.CAMERA_INJECT_EXTERNAL_CAMERA");
Rucha Katakwardf223072021-06-15 10:21:00 -0700139const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800140static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
141static constexpr int32_t kSystemNativeClientState =
142 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700143
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800144const String8 CameraService::kOfflineDevice("offline-");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -0700145const String16 CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700146
Rucha Katakward9ea6452021-05-06 11:57:16 -0700147// Set to keep track of logged service error events.
148static std::set<String8> sServiceErrorEventSet;
149
Austin Borger74fca042022-05-23 12:41:21 -0700150CameraService::CameraService(
151 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper) :
152 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
153 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800154 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800155 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700156 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700157 mSoundRef(0), mInitialized(false),
158 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000159 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800160 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700161 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
162 if (mMemFd == -1) {
163 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
164 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700165}
166
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800167// The word 'System' here does not refer to clients only on the system
168// partition. They just need to have a android system uid.
169static bool doesClientHaveSystemUid() {
170 return (CameraThreadState::getCallingUid() < AID_APP_START);
171}
172
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800173void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
174 if (name != String16(kAppopsServiceName)) {
175 return;
176 }
177
178 ALOGV("appops service registered. setting camera audio restriction");
179 mAppOps.setCameraAudioRestriction(mAudioRestriction);
180}
181
Iliyan Malchev8951a972011-04-14 16:55:59 -0700182void CameraService::onFirstRef()
183{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700184
Ruben Brunkcc776712015-02-17 20:18:47 -0800185 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800186
Iliyan Malchev8951a972011-04-14 16:55:59 -0700187 BnCameraService::onFirstRef();
188
Ruben Brunk99e69712015-05-26 17:25:07 -0700189 // Update battery life tracking if service is restarting
190 BatteryNotifier& notifier(BatteryNotifier::getInstance());
191 notifier.noteResetCamera();
192 notifier.noteResetFlashlight();
193
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800194 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800195
Emilian Peevf53f66e2017-04-11 14:29:43 +0100196 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800197 if (res == OK) {
198 mInitialized = true;
199 }
200
Svet Ganova453d0d2018-01-11 15:37:58 -0800201 mUidPolicy = new UidPolicy(this);
202 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800203 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
204 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800205 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800206
207 // appops function setCamerAudioRestriction uses getService which
208 // is blocking till the appops service is ready. To enable early
209 // boot availability for cameraservice, use checkService which is
210 // non blocking and register for notifications
211 sp<IServiceManager> sm = defaultServiceManager();
212 sp<IBinder> binder = sm->checkService(String16(kAppopsServiceName));
213 if (!binder) {
214 sm->registerForNotifications(String16(kAppopsServiceName), this);
215 } else {
216 mAppOps.setCameraAudioRestriction(mAudioRestriction);
217 }
218
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700219 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
220 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000221 // Deprecated, so it will fail to register on newer devices
222 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700223 __FUNCTION__);
224 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700225
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700226 if (!AidlCameraService::registerService(this)) {
227 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
228 }
229
Shuzhen Wang24b44152019-09-20 10:38:11 -0700230 // This needs to be last call in this function, so that it's as close to
231 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700232 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700233 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800234}
235
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800236status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800237 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100238
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800239 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000240 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800241 {
242 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800243
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800244 if (nullptr == mCameraProviderManager.get()) {
245 mCameraProviderManager = new CameraProviderManager();
246 res = mCameraProviderManager->initialize(this);
247 if (res != OK) {
248 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
249 __FUNCTION__, strerror(-res), res);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700250 logServiceError(String8::format("Unable to initialize camera provider manager"),
251 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800252 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100253 }
254 }
255
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800256
257 // Setup vendor tags before we call get_camera_info the first time
258 // because HAL might need to setup static vendor keys in get_camera_info
259 // TODO: maybe put this into CameraProviderManager::initialize()?
260 mCameraProviderManager->setUpVendorTags();
261
262 if (nullptr == mFlashlight.get()) {
263 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700264 }
265
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800266 res = mFlashlight->findFlashUnits();
267 if (res != OK) {
268 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
269 }
270
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000271 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800272 }
273
274
275 for (auto& cameraId : deviceIds) {
276 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800277 if (getCameraState(id8) == nullptr) {
278 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
279 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000280 if (unavailPhysicalIds.count(cameraId) > 0) {
281 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
282 String8 physicalId8 = String8(physicalId.c_str());
283 onDeviceStatusChanged(id8, physicalId8, CameraDeviceStatus::NOT_PRESENT);
284 }
285 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800286 }
287
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700288 // Derive primary rear/front cameras, and filter their charactierstics.
289 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700290 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700291 // Assume internal cameras are advertised from the same
292 // provider. If multiple providers are registered at different time,
293 // and each provider contains multiple internal color cameras, the current
294 // logic may filter the characteristics of more than one front/rear color
295 // cameras.
296 Mutex::Autolock l(mServiceLock);
297 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700298 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700299
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800300 return OK;
301}
302
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700303void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status,
304 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800305 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800306 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700307 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
308 i->getListenerUid())) {
309 ALOGV("Skipping torch callback for system-only camera device %s",
310 cameraId.c_str());
311 continue;
312 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700313 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
314 String16{cameraId});
315 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
316 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800317 }
318}
319
Mathias Agopian65ab4712010-07-14 17:59:35 -0700320CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800321 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800322 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800323 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800324 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700325}
326
Emilian Peevaee727d2017-05-04 16:35:48 +0100327void CameraService::onNewProviderRegistered() {
328 enumerateProviders();
329}
330
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700331void CameraService::filterAPI1SystemCameraLocked(
332 const std::vector<std::string> &normalDeviceIds) {
333 mNormalDeviceIdsWithoutSystemCamera.clear();
334 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700335 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
336 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
337 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
338 continue;
339 }
340 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700341 // All system camera ids will necessarily come after public camera
342 // device ids as per the HAL interface contract.
343 break;
344 }
345 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
346 }
347 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
348 mNormalDeviceIdsWithoutSystemCamera.size());
349}
350
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700351status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
352 auto state = getCameraState(cameraId);
353 if (state != nullptr) {
354 *kind = state->getSystemCameraKind();
355 return OK;
356 }
357 // Hidden physical camera ids won't have CameraState
358 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
359}
360
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800361void CameraService::updateCameraNumAndIds() {
362 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700363 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
364 // Excludes hidden secure cameras
365 mNumberOfCameras =
366 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
367 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800368 mNormalDeviceIds =
369 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700370 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800371}
372
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700373void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700374 // To claim to be S Performance primary cameras, the cameras must be
375 // backward compatible. So performance class primary camera Ids must be API1
376 // compatible.
377 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
378 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
379 int facing = -1;
380 int orientation = 0;
381 String8 cameraId8(cameraId.c_str());
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800382 int portraitRotation;
383 getDeviceVersion(cameraId8, /*overrideToPortrait*/false, /*out*/&portraitRotation,
384 /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700385 if (facing == -1) {
386 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
387 return;
388 }
389
390 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
391 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700392 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
393 if (res == OK) {
394 mPerfClassPrimaryCameraIds.insert(cameraId);
395 } else {
396 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
397 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
398 break;
399 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700400
401 if (facing == hardware::CAMERA_FACING_BACK) {
402 firstRearCameraSeen = true;
403 }
404 if (facing == hardware::CAMERA_FACING_FRONT) {
405 firstFrontCameraSeen = true;
406 }
407 }
408
409 if (firstRearCameraSeen && firstFrontCameraSeen) {
410 break;
411 }
412 }
413}
414
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100415void CameraService::addStates(const String8 id) {
416 std::string cameraId(id.c_str());
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700417 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100418 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
419 if (res != OK) {
420 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
421 return;
422 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000423 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700424 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
425 if (res != OK) {
426 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
427 return;
428 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000429 std::vector<std::string> physicalCameraIds;
430 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100431 std::set<String8> conflicting;
432 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
433 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
434 }
435
436 {
437 Mutex::Autolock lock(mCameraStatesLock);
438 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000439 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100440 }
441
442 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100443 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100444 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800445
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700446 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100447 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800448
449 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100450 logDeviceAdded(id, "Device added");
451}
452
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100453void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800454 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100455 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100456 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100457 mTorchStatusMap.removeItem(id);
458 }
459
460 {
461 Mutex::Autolock lock(mCameraStatesLock);
462 mCameraStates.erase(id);
463 }
464}
465
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800466void CameraService::onDeviceStatusChanged(const String8& id,
467 CameraDeviceStatus newHalStatus) {
468 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
469 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700470
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800471 StatusInternal newStatus = mapToInternal(newHalStatus);
472
Ruben Brunkcc776712015-02-17 20:18:47 -0800473 std::shared_ptr<CameraState> state = getCameraState(id);
474
475 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700476 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100477 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700478 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100479
480 // First add as absent to make sure clients are notified below
481 addStates(id);
482
483 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700484 } else {
485 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
486 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700487 return;
488 }
489
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800490 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800491
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800492 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800493 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700494 return;
495 }
496
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800497 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700498 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
499 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800500
501 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
502 // to this device until the status changes
503 updateStatus(StatusInternal::NOT_PRESENT, id);
504
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800505 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700506 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800507 // Don't do this in updateStatus to avoid deadlock over mServiceLock
508 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700509
Ruben Brunkcc776712015-02-17 20:18:47 -0800510 // Remove cached shim parameters
511 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700512
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800513 // Remove online as well as offline client from the list of active clients,
514 // if they are present
515 clientToDisconnectOnline = removeClientLocked(id);
516 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700517 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800518
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800519 disconnectClient(id, clientToDisconnectOnline);
520 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700521
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100522 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800523 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800524 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700525 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
526 newStatus));
527 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800528 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700529 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800530}
Igor Murashkincba2c162013-03-20 15:56:31 -0700531
Shuzhen Wang43858162020-01-10 13:42:15 -0800532void CameraService::onDeviceStatusChanged(const String8& id,
533 const String8& physicalId,
534 CameraDeviceStatus newHalStatus) {
535 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
536 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
537
538 StatusInternal newStatus = mapToInternal(newHalStatus);
539
540 std::shared_ptr<CameraState> state = getCameraState(id);
541
542 if (state == nullptr) {
543 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000544 __FUNCTION__, physicalId.string(), id.string());
Shuzhen Wang43858162020-01-10 13:42:15 -0800545 return;
546 }
547
548 StatusInternal logicalCameraStatus = state->getStatus();
549 if (logicalCameraStatus != StatusInternal::PRESENT &&
550 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
551 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
552 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
553 return;
554 }
555
556 bool updated = false;
557 if (newStatus == StatusInternal::PRESENT) {
558 updated = state->removeUnavailablePhysicalId(physicalId);
559 } else {
560 updated = state->addUnavailablePhysicalId(physicalId);
561 }
562
563 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800564 String8 idCombo = id + " : " + physicalId;
565 if (newStatus == StatusInternal::PRESENT) {
566 logDeviceAdded(idCombo,
567 String8::format("Device status changed to %d", newStatus));
568 } else {
569 logDeviceRemoved(idCombo,
570 String8::format("Device status changed to %d", newStatus));
571 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700572 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
573 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
574 if (getSystemCameraKind(id, &deviceKind) != OK) {
575 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
576 return;
577 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800578 String16 id16(id), physicalId16(physicalId);
579 Mutex::Autolock lock(mStatusListenerLock);
580 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700581 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
582 listener->getListenerPid(), listener->getListenerUid())) {
583 ALOGV("Skipping discovery callback for system-only camera device %s",
584 id.c_str());
585 continue;
586 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700587 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
588 mapToInterface(newStatus), id16, physicalId16);
589 listener->handleBinderStatus(ret,
590 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
591 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
592 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800593 }
594 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700595}
596
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800597void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
598 if (clientToDisconnect.get() != nullptr) {
599 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
600 __FUNCTION__, id.string());
601 // Notify the client of disconnection
602 clientToDisconnect->notifyError(
603 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
604 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800605 clientToDisconnect->disconnect();
606 }
607}
608
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800609void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800610 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700611 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
612 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
613 if (res != OK) {
614 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
615 cameraId.string());
616 return;
617 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800618 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700619 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800620}
621
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700622
623void CameraService::onTorchStatusChanged(const String8& cameraId,
624 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
625 Mutex::Autolock al(mTorchStatusMutex);
626 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
627}
628
Rucha Katakwar38284522021-11-10 11:25:21 -0800629void CameraService::broadcastTorchStrengthLevel(const String8& cameraId,
630 int32_t newStrengthLevel) {
631 Mutex::Autolock lock(mStatusListenerLock);
632 for (auto& i : mListenerList) {
Austin Borgere8e2c422022-05-12 13:45:24 -0700633 auto ret = i->getListener()->onTorchStrengthLevelChanged(String16{cameraId},
Rucha Katakwar38284522021-11-10 11:25:21 -0800634 newStrengthLevel);
Austin Borgere8e2c422022-05-12 13:45:24 -0700635 i->handleBinderStatus(ret,
636 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
637 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800638 }
639}
640
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800641void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700642 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800643 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
644 __FUNCTION__, cameraId.string(), newStatus);
645
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800646 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800647 status_t res = getTorchStatusLocked(cameraId, &status);
648 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700649 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
650 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800651 return;
652 }
653 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800654 return;
655 }
656
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800657 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800658 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800659 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
660 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800661 return;
662 }
663
Ruben Brunkcc776712015-02-17 20:18:47 -0800664 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700665 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700666 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700667 auto iter = mTorchUidMap.find(cameraId);
668 if (iter != mTorchUidMap.end()) {
669 int oldUid = iter->second.second;
670 int newUid = iter->second.first;
671 BatteryNotifier& notifier(BatteryNotifier::getInstance());
672 if (oldUid != newUid) {
673 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800674 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700675 notifier.noteFlashlightOff(cameraId, oldUid);
676 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800677 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700678 notifier.noteFlashlightOn(cameraId, newUid);
679 }
680 iter->second.second = newUid;
681 } else {
682 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800683 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700684 notifier.noteFlashlightOn(cameraId, oldUid);
685 } else {
686 notifier.noteFlashlightOff(cameraId, oldUid);
687 }
688 }
689 }
690 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700691 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800692}
693
Jayant Chowdharyc3198c32021-07-28 20:59:14 +0000694static bool hasPermissionsForSystemCamera(int callingPid, int callingUid,
695 bool logPermissionFailure = false) {
696 return checkPermission(sSystemCameraPermission, callingPid, callingUid,
697 logPermissionFailure) &&
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700698 checkPermission(sCameraPermission, callingPid, callingUid);
699}
700
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800701Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700702 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100703 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700704 bool hasSystemCameraPermissions =
705 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
706 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700707 switch (type) {
708 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700709 if (hasSystemCameraPermissions) {
710 *numCameras = static_cast<int>(mNormalDeviceIds.size());
711 } else {
712 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
713 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800714 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700715 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700716 if (hasSystemCameraPermissions) {
717 *numCameras = mNumberOfCameras;
718 } else {
719 *numCameras = mNumberOfCamerasWithoutSystemCamera;
720 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800721 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700722 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800723 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700724 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800725 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
726 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700727 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800728 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700729}
730
Austin Borger18b30a72022-10-27 12:20:29 -0700731Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800732 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700733 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100734 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700735 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
736 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
737 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
738 "characteristics for system only device %s: ", cameraIdStr.c_str());
739 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100740
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800741 if (!mInitialized) {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700742 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800743 return STATUS_ERROR(ERROR_DISCONNECTED,
744 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700745 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700746 bool hasSystemCameraPermissions =
747 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
748 CameraThreadState::getCallingUid());
749 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
750 if (hasSystemCameraPermissions) {
751 cameraIdBound = mNumberOfCameras;
752 }
753 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800754 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
755 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700756 }
757
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800758 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -0700759 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800760 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borger18b30a72022-10-27 12:20:29 -0700761 cameraIdStr.c_str(), overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100762 if (err != OK) {
763 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
764 "Error retrieving camera info from device %d: %s (%d)", cameraId,
765 strerror(-err), err);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700766 logServiceError(String8::format("Error retrieving camera info from device %d",cameraId),
767 ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -0800768 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100769
Ruben Brunkcc776712015-02-17 20:18:47 -0800770 return ret;
771}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700772
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800773std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700774 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
775 auto callingPid = CameraThreadState::getCallingPid();
776 auto callingUid = CameraThreadState::getCallingUid();
Jayant Chowdharyc3198c32021-07-28 20:59:14 +0000777 if (checkPermission(sSystemCameraPermission, callingPid, callingUid,
778 /*logPermissionFailure*/false) || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700779 deviceIds = &mNormalDeviceIds;
780 }
781 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800782 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700783 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800784 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800785 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800786
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700787 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800788}
789
790String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
791 Mutex::Autolock lock(mServiceLock);
792 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800793}
794
795Status CameraService::getCameraCharacteristics(const String16& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -0700796 int targetSdkVersion, bool overrideToPortrait, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700797 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700798 if (!cameraInfo) {
799 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800800 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700801 }
802
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800803 if (!mInitialized) {
804 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700805 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800806 return STATUS_ERROR(ERROR_DISCONNECTED,
807 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700808 }
809
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700810 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
811 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
812 "characteristics for system only device %s: ", String8(cameraId).string());
813 }
814
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800815 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800816
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700817
818 std::string cameraIdStr = String8(cameraId).string();
819 bool overrideForPerfClass =
820 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
821 cameraIdStr, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100822 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borger18b30a72022-10-27 12:20:29 -0700823 cameraIdStr, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100824 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700825 if (res == NAME_NOT_FOUND) {
826 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
827 "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
828 strerror(-res), res);
829 } else {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700830 logServiceError(String8::format("Unable to retrieve camera characteristics for "
831 "device %s.", String8(cameraId).string()),ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700832 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
833 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
834 strerror(-res), res);
835 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700836 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700837 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
838 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
839 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
840 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
841 "for device %s", String8(cameraId).string());
842 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700843 int callingPid = CameraThreadState::getCallingPid();
844 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100845 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700846 // If it's not calling from cameraserver, check the permission only if
847 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
848 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100849 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700850 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700851 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100852 res = cameraInfo->removePermissionEntries(
853 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
854 &tagsRemoved);
855 if (res != OK) {
856 cameraInfo->clear();
857 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
858 " characteristics needing camera permission for device %s: %s (%d)",
859 String8(cameraId).string(), strerror(-res), res);
860 }
861 }
862
863 if (!tagsRemoved.empty()) {
864 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
865 tagsRemoved.data(), tagsRemoved.size());
866 if (res != OK) {
867 cameraInfo->clear();
868 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
869 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
870 strerror(-res), res);
871 }
872 }
873
Zhijun He2b59be82013-09-25 10:14:30 -0700874 return ret;
875}
876
Rucha Katakwar38284522021-11-10 11:25:21 -0800877Status CameraService::getTorchStrengthLevel(const String16& cameraId,
878 int32_t* torchStrength) {
879 ATRACE_CALL();
880 Mutex::Autolock l(mServiceLock);
881 if (!mInitialized) {
882 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
883 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
884 }
885
886 if(torchStrength == NULL) {
887 ALOGE("%s: strength level must not be null.", __FUNCTION__);
888 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
889 }
890
891 status_t res = mCameraProviderManager->getTorchStrengthLevel(String8(cameraId).string(),
892 torchStrength);
893 if (res != OK) {
894 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
895 "strength level for device %s: %s (%d)", String8(cameraId).string(),
896 strerror(-res), res);
897 }
898 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
899 return Status::ok();
900}
901
Ruben Brunkcc776712015-02-17 20:18:47 -0800902String8 CameraService::getFormattedCurrentTime() {
903 time_t now = time(nullptr);
904 char formattedTime[64];
905 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
906 return String8(formattedTime);
907}
908
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800909Status CameraService::getCameraVendorTagDescriptor(
910 /*out*/
911 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700912 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800913 if (!mInitialized) {
914 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800915 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800916 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800917 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
918 if (globalDescriptor != nullptr) {
919 *desc = *(globalDescriptor.get());
920 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800921 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800922}
923
Emilian Peev71c73a22017-03-21 16:35:51 +0000924Status CameraService::getCameraVendorTagCache(
925 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
926 ATRACE_CALL();
927 if (!mInitialized) {
928 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
929 return STATUS_ERROR(ERROR_DISCONNECTED,
930 "Camera subsystem not available");
931 }
932 sp<VendorTagDescriptorCache> globalCache =
933 VendorTagDescriptorCache::getGlobalVendorTagCache();
934 if (globalCache != nullptr) {
935 *cache = *(globalCache.get());
936 }
937 return Status::ok();
938}
939
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700940void CameraService::clearCachedVariables() {
941 BasicClient::BasicClient::sCameraService = nullptr;
942}
943
Austin Borger18b30a72022-10-27 12:20:29 -0700944std::pair<int, IPCTransport> CameraService::getDeviceVersion(const String8& cameraId,
945 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700946 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800947
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800948 int deviceVersion = 0;
949
Emilian Peevf53f66e2017-04-11 14:29:43 +0100950 status_t res;
951 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +0000952 IPCTransport transport = IPCTransport::INVALID;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100953 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +0000954 &maxVersion, &transport);
955 if (res != OK || transport == IPCTransport::INVALID) {
956 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
957 cameraId.string());
958 return std::make_pair(-1, IPCTransport::INVALID) ;
959 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100960 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800961
Emilian Peevf53f66e2017-04-11 14:29:43 +0100962 hardware::CameraInfo info;
963 if (facing) {
Austin Borger18b30a72022-10-27 12:20:29 -0700964 res = mCameraProviderManager->getCameraInfo(cameraId.string(), overrideToPortrait,
965 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +0000966 if (res != OK) {
967 return std::make_pair(-1, IPCTransport::INVALID);
968 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100969 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -0700970 if (orientation) {
971 *orientation = info.orientation;
972 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800973 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100974
Jayant Chowdharyffc5d682022-05-12 18:34:34 +0000975 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -0800976}
977
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800978Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700979 switch(err) {
980 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800981 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800982 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800983 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
984 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800985 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800986 return STATUS_ERROR(ERROR_DISCONNECTED,
987 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700988 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800989 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
990 "Camera HAL encountered error %d: %s",
991 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700992 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800993}
994
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800995Status CameraService::makeClient(const sp<CameraService>& cameraService,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800996 const sp<IInterface>& cameraCb, const String16& packageName, bool systemNativeClient,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700997 const std::optional<String16>& featureId, const String8& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700998 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +0000999 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001000 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
1001 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001002 // For HIDL devices
1003 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1004 // Create CameraClient based on device version reported by the HAL.
1005 int deviceVersion = deviceVersionAndTransport.first;
1006 switch(deviceVersion) {
1007 case CAMERA_DEVICE_API_VERSION_1_0:
1008 ALOGE("Camera using old HAL version: %d", deviceVersion);
1009 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1010 "Camera device \"%s\" HAL version %d no longer supported",
1011 cameraId.string(), deviceVersion);
1012 break;
1013 case CAMERA_DEVICE_API_VERSION_3_0:
1014 case CAMERA_DEVICE_API_VERSION_3_1:
1015 case CAMERA_DEVICE_API_VERSION_3_2:
1016 case CAMERA_DEVICE_API_VERSION_3_3:
1017 case CAMERA_DEVICE_API_VERSION_3_4:
1018 case CAMERA_DEVICE_API_VERSION_3_5:
1019 case CAMERA_DEVICE_API_VERSION_3_6:
1020 case CAMERA_DEVICE_API_VERSION_3_7:
1021 break;
1022 default:
1023 // Should not be reachable
1024 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1025 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1026 "Camera device \"%s\" has unknown HAL version %d",
1027 cameraId.string(), deviceVersion);
1028 }
1029 }
1030 if (effectiveApiLevel == API_1) { // Camera1 API route
1031 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001032 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
1033 packageName, featureId, cameraId, api1CameraId, facing, sensorOrientation,
Austin Borger18b30a72022-10-27 12:20:29 -07001034 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait);
1035 ALOGI("%s: Camera1 API (legacy), override to portrait %d", __FUNCTION__,
1036 overrideToPortrait);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001037 } else { // Camera2 API route
1038 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1039 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001040 *client = new CameraDeviceClient(cameraService, tmp,
1041 cameraService->mCameraServiceProxyWrapper, packageName, systemNativeClient,
1042 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
Austin Borger18b30a72022-10-27 12:20:29 -07001043 overrideForPerfClass, overrideToPortrait);
1044 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001045 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001046 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001047}
1048
Ruben Brunk6267b532015-04-30 17:44:07 -07001049String8 CameraService::toString(std::set<userid_t> intSet) {
1050 String8 s("");
1051 bool first = true;
1052 for (userid_t i : intSet) {
1053 if (first) {
1054 s.appendFormat("%d", i);
1055 first = false;
1056 } else {
1057 s.appendFormat(", %d", i);
1058 }
1059 }
1060 return s;
1061}
1062
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001063int32_t CameraService::mapToInterface(TorchModeStatus status) {
1064 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1065 switch (status) {
1066 case TorchModeStatus::NOT_AVAILABLE:
1067 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1068 break;
1069 case TorchModeStatus::AVAILABLE_OFF:
1070 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1071 break;
1072 case TorchModeStatus::AVAILABLE_ON:
1073 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1074 break;
1075 default:
1076 ALOGW("Unknown new flash status: %d", status);
1077 }
1078 return serviceStatus;
1079}
1080
1081CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1082 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1083 switch (status) {
1084 case CameraDeviceStatus::NOT_PRESENT:
1085 serviceStatus = StatusInternal::NOT_PRESENT;
1086 break;
1087 case CameraDeviceStatus::PRESENT:
1088 serviceStatus = StatusInternal::PRESENT;
1089 break;
1090 case CameraDeviceStatus::ENUMERATING:
1091 serviceStatus = StatusInternal::ENUMERATING;
1092 break;
1093 default:
1094 ALOGW("Unknown new HAL device status: %d", status);
1095 }
1096 return serviceStatus;
1097}
1098
1099int32_t CameraService::mapToInterface(StatusInternal status) {
1100 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1101 switch (status) {
1102 case StatusInternal::NOT_PRESENT:
1103 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1104 break;
1105 case StatusInternal::PRESENT:
1106 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1107 break;
1108 case StatusInternal::ENUMERATING:
1109 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1110 break;
1111 case StatusInternal::NOT_AVAILABLE:
1112 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1113 break;
1114 case StatusInternal::UNKNOWN:
1115 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1116 break;
1117 default:
1118 ALOGW("Unknown new internal device status: %d", status);
1119 }
1120 return serviceStatus;
1121}
1122
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001123Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001124 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001125
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001126 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -08001127 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001128 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001129 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001130 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001131 sp<ICameraClient>{nullptr}, id, cameraId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001132 internalPackageName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001133 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Austin Borger18b30a72022-10-27 12:20:29 -07001134 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001135 ).isOk()) {
1136 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001137 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001138 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001139}
1140
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001141Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001142 /*out*/
1143 CameraParameters* parameters) {
1144
1145 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1146
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001147 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001148
1149 if (parameters == NULL) {
1150 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001151 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001152 }
1153
Ruben Brunkcc776712015-02-17 20:18:47 -08001154 String8 id = String8::format("%d", cameraId);
1155
1156 // Check if we already have parameters
1157 {
1158 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001159 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001160 auto cameraState = getCameraState(id);
1161 if (cameraState == nullptr) {
1162 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001163 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1164 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001165 }
1166 CameraParameters p = cameraState->getShimParams();
1167 if (!p.isEmpty()) {
1168 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001169 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001170 }
1171 }
1172
Jayant Chowdhary12361932018-08-27 14:46:13 -07001173 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001174 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001175 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001176 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001177 // Error already logged by callee
1178 return ret;
1179 }
1180
1181 // Check for parameters again
1182 {
1183 // Scope for service lock
1184 Mutex::Autolock lock(mServiceLock);
1185 auto cameraState = getCameraState(id);
1186 if (cameraState == nullptr) {
1187 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001188 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1189 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001190 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001191 CameraParameters p = cameraState->getShimParams();
1192 if (!p.isEmpty()) {
1193 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001194 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001195 }
1196 }
1197
Ruben Brunkcc776712015-02-17 20:18:47 -08001198 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1199 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001200 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001201}
1202
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001203// Can camera service trust the caller based on the calling UID?
1204static bool isTrustedCallingUid(uid_t uid) {
1205 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001206 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001207 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001208 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001209 return true;
1210 default:
1211 return false;
1212 }
1213}
1214
Nicholas Sauera3620332019-04-03 14:05:17 -07001215static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1216 PermissionController pc;
1217 uid = pc.getPackageUid(packageName, 0);
1218 if (uid <= 0) {
1219 ALOGE("Unknown package: '%s'", String8(packageName).string());
1220 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1221 return BAD_VALUE;
1222 }
1223
1224 if (userId < 0) {
1225 ALOGE("Invalid user: %d", userId);
1226 dprintf(err, "Invalid user: %d\n", userId);
1227 return BAD_VALUE;
1228 }
1229
1230 uid = multiuser_get_uid(userId, uid);
1231 return NO_ERROR;
1232}
1233
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001234Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001235 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1236 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001237
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001238#ifdef __BRILLO__
1239 UNUSED(clientName8);
1240 UNUSED(clientUid);
1241 UNUSED(clientPid);
1242 UNUSED(originalClientPid);
1243#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001244 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1245 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001246 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001247 return allowed;
1248 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001249#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001250
Jayant Chowdhary12361932018-08-27 14:46:13 -07001251 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001252
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001253 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001254 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1255 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001256 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1257 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001258 }
1259
Ruben Brunkcc776712015-02-17 20:18:47 -08001260 if (getCameraState(cameraId) == nullptr) {
1261 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1262 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001263 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1264 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001265 }
1266
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001267 status_t err = checkIfDeviceIsUsable(cameraId);
1268 if (err != NO_ERROR) {
1269 switch(err) {
1270 case -ENODEV:
1271 case -EBUSY:
1272 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1273 "No camera device with ID \"%s\" currently available", cameraId.string());
1274 default:
1275 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1276 "Unknown error connecting to ID \"%s\"", cameraId.string());
1277 }
1278 }
1279 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001280}
1281
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001282Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001283 const String8& clientName8, int& clientUid, int& clientPid,
1284 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001285 int callingPid = CameraThreadState::getCallingPid();
1286 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001287
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001288 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001289 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001290 clientUid = callingUid;
1291 } else if (!isTrustedCallingUid(callingUid)) {
1292 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1293 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001294 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1295 "Untrusted caller (calling PID %d, UID %d) trying to "
1296 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1297 callingPid, callingUid, cameraId.string(),
1298 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001299 }
1300
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001301 // Check if we can trust clientPid
1302 if (clientPid == USE_CALLING_PID) {
1303 clientPid = callingPid;
1304 } else if (!isTrustedCallingUid(callingUid)) {
1305 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1306 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001307 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1308 "Untrusted caller (calling PID %d, UID %d) trying to "
1309 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1310 callingPid, callingUid, cameraId.string(),
1311 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001312 }
1313
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001314 if (shouldRejectSystemCameraConnection(cameraId)) {
1315 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1316 cameraId.c_str());
1317 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1318 "available", cameraId.string());
1319 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001320 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1321 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1322 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1323 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1324 "found while trying to query device kind", cameraId.string());
1325
1326 }
1327
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001328 // If it's not calling from cameraserver, check the permission if the
1329 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1330 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001331 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001332 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001333 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001334 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001335 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1336 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1337 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001338 }
1339
Svet Ganova453d0d2018-01-11 15:37:58 -08001340 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001341 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001342 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001343 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1344 clientPid, clientUid);
1345 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001346 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1347 "calling UID %d proc state %" PRId32 ")",
1348 clientName8.string(), clientUid, clientPid, cameraId.string(),
1349 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001350 }
1351
Michael Grooverd1d435a2018-12-18 17:39:42 -08001352 // If sensor privacy is enabled then prevent access to the camera
1353 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1354 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1355 return STATUS_ERROR_FMT(ERROR_DISABLED,
1356 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1357 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1358 }
1359
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001360 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1361 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001362 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001363 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001364
Ruben Brunk6267b532015-04-30 17:44:07 -07001365 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001366
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001367 // For non-system clients : Only allow clients who are being used by the current foreground
1368 // device user, unless calling from our own process.
1369 if (!doesClientHaveSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001370 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001371 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1372 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1373 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001374 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1375 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1376 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001377 }
1378
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001379 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001380}
1381
1382status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1383 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001384 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001385 if (cameraState == nullptr) {
1386 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1387 cameraId.string());
1388 return -ENODEV;
1389 }
1390
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001391 StatusInternal currentStatus = cameraState->getStatus();
1392 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001393 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1394 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001395 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001396 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001397 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1398 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001399 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001400 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001401
Ruben Brunkcc776712015-02-17 20:18:47 -08001402 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001403}
1404
Ruben Brunkcc776712015-02-17 20:18:47 -08001405void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001406 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001407
Ruben Brunkcc776712015-02-17 20:18:47 -08001408 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001409 auto clientDescriptor =
1410 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001411 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001412 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1413
1414 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1415 String8(client->getPackageName()));
1416
1417 if (evicted.size() > 0) {
1418 // This should never happen - clients should already have been removed in disconnect
1419 for (auto& i : evicted) {
1420 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1421 __FUNCTION__, i->getKey().string());
1422 }
1423
1424 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1425 __FUNCTION__);
1426 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001427
1428 // And register a death notification for the client callback. Do
1429 // this last to avoid Binder policy where a nested Binder
1430 // transaction might be pre-empted to service the client death
1431 // notification if the client process dies before linkToDeath is
1432 // invoked.
1433 sp<IBinder> remoteCallback = client->getRemote();
1434 if (remoteCallback != nullptr) {
1435 remoteCallback->linkToDeath(this);
1436 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001437}
1438
1439status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1440 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001441 int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001442 /*out*/
1443 sp<BasicClient>* client,
1444 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001445 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001446 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001447 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001448 DescriptorPtr clientDescriptor;
1449 {
1450 if (effectiveApiLevel == API_1) {
1451 // If we are using API1, any existing client for this camera ID with the same remote
1452 // should be returned rather than evicted to allow MediaRecorder to work properly.
1453
1454 auto current = mActiveClientManager.get(cameraId);
1455 if (current != nullptr) {
1456 auto clientSp = current->getValue();
1457 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001458 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001459 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001460 " API level, evicting prior client...");
1461 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001462 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001463 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001464 *client = clientSp;
1465 return NO_ERROR;
1466 }
1467 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001468 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001469 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001470
Ruben Brunkcc776712015-02-17 20:18:47 -08001471 // Get current active client PIDs
1472 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1473 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001474
Emilian Peev8131a262017-02-01 12:33:43 +00001475 std::vector<int> priorityScores(ownerPids.size());
1476 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001477
Emilian Peev8131a262017-02-01 12:33:43 +00001478 // Get priority scores of all active PIDs
1479 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1480 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1481 /*out*/&priorityScores[0]);
1482 if (err != OK) {
1483 ALOGE("%s: Priority score query failed: %d",
1484 __FUNCTION__, err);
1485 return err;
1486 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001487
Ruben Brunkcc776712015-02-17 20:18:47 -08001488 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001489 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001490 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001491 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001492 resource_policy::ClientPriority(priorityScores[i], states[i],
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001493 /* isVendorClient won't get copied over*/ false,
1494 /* oomScoreOffset won't get copied over*/ 0));
Ruben Brunkcc776712015-02-17 20:18:47 -08001495 }
1496 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001497
Ruben Brunkcc776712015-02-17 20:18:47 -08001498 // Get state for the given cameraId
1499 auto state = getCameraState(cameraId);
1500 if (state == nullptr) {
1501 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1502 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001503 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001504 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001505 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001506
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001507 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1508 int32_t actualState = states[states.size() - 1];
1509
1510 // Make descriptor for incoming client. We store the oomScoreOffset
1511 // since we might need it later on new handleEvictionsLocked and
1512 // ProcessInfoService would not take that into account.
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001513 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001514 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001515 state->getConflicting(), actualScore, clientPid, actualState,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001516 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001517
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001518 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1519
Ruben Brunkcc776712015-02-17 20:18:47 -08001520 // Find clients that would be evicted
1521 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1522
1523 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1524 // background, so we cannot do evictions
1525 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1526 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1527 " priority).", clientPid);
1528
1529 sp<BasicClient> clientSp = clientDescriptor->getValue();
1530 String8 curTime = getFormattedCurrentTime();
1531 auto incompatibleClients =
1532 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1533
1534 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001535 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001536 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001537 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001538
1539 for (auto& i : incompatibleClients) {
1540 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001541 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1542 i->getKey().string(),
1543 String8{i->getValue()->getPackageName()}.string(),
1544 i->getOwnerId(), i->getPriority().getScore(),
1545 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001546 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001547 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001548 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001549 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001550 }
1551
1552 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001553 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001554 mEventLog.add(msg);
1555
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001556 auto current = mActiveClientManager.get(cameraId);
1557 if (current != nullptr) {
1558 return -EBUSY; // CAMERA_IN_USE
1559 } else {
1560 return -EUSERS; // MAX_CAMERAS_IN_USE
1561 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001562 }
1563
1564 for (auto& i : evicted) {
1565 sp<BasicClient> clientSp = i->getValue();
1566 if (clientSp.get() == nullptr) {
1567 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1568
1569 // TODO: Remove this
1570 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1571 __FUNCTION__);
1572 mActiveClientManager.remove(i);
1573 continue;
1574 }
1575
1576 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1577 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001578 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001579
Ruben Brunkcc776712015-02-17 20:18:47 -08001580 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001581 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001582 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1583 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001584 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001585 i->getOwnerId(), i->getPriority().getScore(),
1586 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001587 packageName.string(), clientPid, clientPriority.getScore(),
1588 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001589
1590 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001591 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001592 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001593 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001594 }
1595
Ruben Brunkcc776712015-02-17 20:18:47 -08001596 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1597 // other clients from connecting in mServiceLockWrapper if held
1598 mServiceLock.unlock();
1599
1600 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001601 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001602
1603 // Destroy evicted clients
1604 for (auto& i : evictedClients) {
1605 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001606 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001607 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001608
Jayant Chowdhary12361932018-08-27 14:46:13 -07001609 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001610
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001611 for (const auto& i : evictedClients) {
1612 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1613 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1614 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1615 if (ret == TIMED_OUT) {
1616 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1617 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1618 mActiveClientManager.toString().string());
1619 return -EBUSY;
1620 }
1621 if (ret != NO_ERROR) {
1622 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1623 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1624 ret, mActiveClientManager.toString().string());
1625 return ret;
1626 }
1627 }
1628
1629 evictedClients.clear();
1630
Ruben Brunkcc776712015-02-17 20:18:47 -08001631 // Once clients have been disconnected, relock
1632 mServiceLock.lock();
1633
1634 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1635 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1636 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001637 }
1638
Ruben Brunkcc776712015-02-17 20:18:47 -08001639 *partial = clientDescriptor;
1640 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001641}
1642
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001643Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001644 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001645 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001646 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001647 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001648 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001649 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001650 bool overrideToPortrait,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001651 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001652 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001653
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001654 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001655 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001656
1657 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001658 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001659 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001660 clientPackageName,/*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07001661 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
1662 overrideToPortrait, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001663
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001664 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001665 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001666 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001667 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001668 }
1669
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001670 *device = client;
1671 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001672}
1673
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001674bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1675 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001676 // If the client is not a vendor client, don't add listener if
1677 // a) the camera is a publicly hidden secure camera OR
1678 // b) the camera is a system only camera and the client doesn't
1679 // have android.permission.SYSTEM_CAMERA permissions.
1680 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1681 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1682 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001683 return true;
1684 }
1685 return false;
1686}
1687
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001688bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1689 // Rules for rejection:
1690 // 1) If cameraserver tries to access this camera device, accept the
1691 // connection.
1692 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001693 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001694 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1695 // and the serving thread is a non hwbinder thread, the client must have
1696 // android.permission.SYSTEM_CAMERA permissions to connect.
1697
1698 int cPid = CameraThreadState::getCallingPid();
1699 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001700 bool systemClient = doesClientHaveSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001701 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1702 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001703 // This isn't a known camera ID, so it's not a system camera
1704 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1705 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001706 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001707
1708 // (1) Cameraserver trying to connect, accept.
1709 if (CameraThreadState::getCallingPid() == getpid()) {
1710 return false;
1711 }
1712 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001713 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001714 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1715 return true;
1716 }
1717 // (3) Here we only check for permissions if it is a system only camera device. This is since
1718 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1719 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1720 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001721 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jayant Chowdharyc3198c32021-07-28 20:59:14 +00001722 !hasPermissionsForSystemCamera(cPid, cUid, /*logPermissionFailure*/true)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001723 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1724 cameraId.c_str());
1725 return true;
1726 }
1727
1728 return false;
1729}
1730
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001731Status CameraService::connectDevice(
1732 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001733 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001734 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001735 const std::optional<String16>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001736 int clientUid, int oomScoreOffset, int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001737 bool overrideToPortrait,
Ruben Brunkcc776712015-02-17 20:18:47 -08001738 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001739 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001740
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001741 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001742 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001743 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001744 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001745 String16 clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001746 int callingPid = CameraThreadState::getCallingPid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001747 bool systemNativeClient = false;
1748 if (doesClientHaveSystemUid() && (clientPackageNameAdj.size() == 0)) {
1749 std::string systemClient =
1750 StringPrintf("client.pid<%d>", CameraThreadState::getCallingPid());
1751 clientPackageNameAdj = String16(systemClient.c_str());
1752 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001753 }
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001754
1755 if (oomScoreOffset < 0) {
1756 String8 msg =
1757 String8::format("Cannot increase the priority of a client %s pid %d for "
1758 "camera id %s", String8(clientPackageNameAdj).string(), callingPid,
1759 id.string());
1760 ALOGE("%s: %s", __FUNCTION__, msg.string());
1761 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1762 }
1763
Austin Borger9bfa0a72022-08-03 17:50:40 -07001764 userid_t clientUserId = multiuser_get_user_id(clientUid);
1765 int callingUid = CameraThreadState::getCallingUid();
1766 if (clientUid == USE_CALLING_UID) {
1767 clientUserId = multiuser_get_user_id(callingUid);
1768 }
1769
1770 if (mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borger5f7abe22022-04-26 15:55:10 -07001771 String8 msg =
1772 String8::format("Camera disabled by device policy");
1773 ALOGE("%s: %s", __FUNCTION__, msg.string());
1774 return STATUS_ERROR(ERROR_DISABLED, msg.string());
1775 }
1776
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001777 // enforce system camera permissions
1778 if (oomScoreOffset > 0 &&
Austin Borger86a588e2022-05-23 12:41:58 -07001779 !hasPermissionsForSystemCamera(callingPid, CameraThreadState::getCallingUid()) &&
1780 !isTrustedCallingUid(CameraThreadState::getCallingUid())) {
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001781 String8 msg =
1782 String8::format("Cannot change the priority of a client %s pid %d for "
1783 "camera id %s without SYSTEM_CAMERA permissions",
1784 String8(clientPackageNameAdj).string(), callingPid, id.string());
1785 ALOGE("%s: %s", __FUNCTION__, msg.string());
1786 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.string());
1787 }
1788
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001789 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001790 /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient,clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001791 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
Austin Borger18b30a72022-10-27 12:20:29 -07001792 targetSdkVersion, overrideToPortrait, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001793
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001794 if(!ret.isOk()) {
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001795 logRejected(id, callingPid, String8(clientPackageNameAdj), ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001796 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001797 }
1798
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001799 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07001800 Mutex::Autolock lock(mServiceLock);
1801
1802 // Clear the previous cached logs and reposition the
1803 // file offset to beginning of the file to log new data.
1804 // If either truncate or lseek fails, close the previous file and create a new one.
1805 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
1806 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
1807 // Close the previous memfd.
1808 close(mMemFd);
1809 // If failure to wipe the data, then create a new file and
1810 // assign the new value to mMemFd.
1811 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
1812 if (mMemFd == -1) {
1813 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
1814 }
1815 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001816 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001817}
1818
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001819String16 CameraService::getPackageNameFromUid(int clientUid) {
1820 String16 packageName("");
1821
1822 sp<IServiceManager> sm = defaultServiceManager();
1823 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
1824 if (binder == 0) {
1825 ALOGE("Cannot get permission service");
1826 // Return empty package name and the further interaction
1827 // with camera will likely fail
1828 return packageName;
1829 }
1830
1831 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
1832 Vector<String16> packages;
1833
1834 permCtrl->getPackagesForUid(clientUid, packages);
1835
1836 if (packages.isEmpty()) {
1837 ALOGE("No packages for calling UID %d", clientUid);
1838 // Return empty package name and the further interaction
1839 // with camera will likely fail
1840 return packageName;
1841 }
1842
1843 // Arbitrarily pick the first name in the list
1844 packageName = packages[0];
1845
1846 return packageName;
1847}
1848
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001849template<class CALLBACK, class CLIENT>
1850Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001851 int api1CameraId, const String16& clientPackageNameMaybe, bool systemNativeClient,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001852 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001853 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001854 bool overrideToPortrait, /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001855 binder::Status ret = binder::Status::ok();
1856
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001857 bool isNonSystemNdk = false;
1858 String16 clientPackageName;
1859 if (clientPackageNameMaybe.size() <= 0) {
1860 // NDK calls don't come with package names, but we need one for various cases.
1861 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
1862 // do exist. For all authentication cases, all packages under the same UID get the
1863 // same permissions, so picking any associated package name is sufficient. For some
1864 // other cases, this may give inaccurate names for clients in logs.
1865 isNonSystemNdk = true;
1866 int packageUid = (clientUid == USE_CALLING_UID) ?
1867 CameraThreadState::getCallingUid() : clientUid;
1868 clientPackageName = getPackageNameFromUid(packageUid);
1869 } else {
1870 clientPackageName = clientPackageNameMaybe;
1871 }
1872
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001873 String8 clientName8(clientPackageName);
1874
1875 int originalClientPid = 0;
1876
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001877 int packagePid = (clientPid == USE_CALLING_PID) ?
1878 CameraThreadState::getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001879 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001880 "Camera API version %d", packagePid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001881 static_cast<int>(effectiveApiLevel));
1882
Shuzhen Wang316781a2020-08-18 18:11:01 -07001883 nsecs_t openTimeNs = systemTime();
1884
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001885 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001886 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07001887 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001888
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001889 {
1890 // Acquire mServiceLock and prevent other clients from connecting
1891 std::unique_ptr<AutoConditionLock> lock =
1892 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1893
1894 if (lock == nullptr) {
1895 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1896 , clientPid);
1897 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1898 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1899 cameraId.string(), clientName8.string(), clientPid);
1900 }
1901
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001902 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001903 if(!(ret = validateConnectLocked(cameraId, clientName8,
1904 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1905 return ret;
1906 }
1907
1908 // Check the shim parameters after acquiring lock, if they have already been updated and
1909 // we were doing a shim update, return immediately
1910 if (shimUpdateOnly) {
1911 auto cameraState = getCameraState(cameraId);
1912 if (cameraState != nullptr) {
1913 if (!cameraState->getShimParams().isEmpty()) return ret;
1914 }
1915 }
1916
1917 status_t err;
1918
1919 sp<BasicClient> clientTmp = nullptr;
1920 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1921 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001922 IInterface::asBinder(cameraCb), clientName8, oomScoreOffset, systemNativeClient,
1923 /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001924 switch (err) {
1925 case -ENODEV:
1926 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1927 "No camera device with ID \"%s\" currently available",
1928 cameraId.string());
1929 case -EBUSY:
1930 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1931 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1932 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001933 case -EUSERS:
1934 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1935 "Too many cameras already open, cannot open camera \"%s\"",
1936 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001937 default:
1938 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1939 "Unexpected error %s (%d) opening camera \"%s\"",
1940 strerror(-err), err, cameraId.string());
1941 }
1942 }
1943
1944 if (clientTmp.get() != nullptr) {
1945 // Handle special case for API1 MediaRecorder where the existing client is returned
1946 device = static_cast<CLIENT*>(clientTmp.get());
1947 return ret;
1948 }
1949
1950 // give flashlight a chance to close devices if necessary.
1951 mFlashlight->prepareDeviceOpen(cameraId);
1952
Austin Borger18b30a72022-10-27 12:20:29 -07001953 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001954 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07001955 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
1956 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001957 if (facing == -1) {
1958 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1959 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1960 "Unable to get camera device \"%s\" facing", cameraId.string());
1961 }
1962
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001963 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001964 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1965 mPerfClassPrimaryCameraIds, cameraId.string(), targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001966 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
1967 clientFeatureId, cameraId, api1CameraId, facing, orientation,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001968 clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001969 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
Austin Borger18b30a72022-10-27 12:20:29 -07001970 overrideToPortrait, /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001971 return ret;
1972 }
1973 client = static_cast<CLIENT*>(tmp.get());
1974
1975 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1976 __FUNCTION__);
1977
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07001978 String8 monitorTags = isClientWatched(client.get()) ? mMonitorTags : String8("");
1979 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001980 if (err != OK) {
1981 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001982 // Errors could be from the HAL module open call or from AppOpsManager
1983 switch(err) {
1984 case BAD_VALUE:
1985 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1986 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1987 case -EBUSY:
1988 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1989 "Camera \"%s\" is already open", cameraId.string());
1990 case -EUSERS:
1991 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1992 "Too many cameras already open, cannot open camera \"%s\"",
1993 cameraId.string());
1994 case PERMISSION_DENIED:
1995 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1996 "No permission to open camera \"%s\"", cameraId.string());
1997 case -EACCES:
1998 return STATUS_ERROR_FMT(ERROR_DISABLED,
1999 "Camera \"%s\" disabled by policy", cameraId.string());
2000 case -ENODEV:
2001 default:
2002 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2003 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
2004 strerror(-err), err);
2005 }
2006 }
2007
2008 // Update shim paremeters for legacy clients
2009 if (effectiveApiLevel == API_1) {
2010 // Assume we have always received a Client subclass for API1
2011 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2012 String8 rawParams = shimClient->getParameters();
2013 CameraParameters params(rawParams);
2014
2015 auto cameraState = getCameraState(cameraId);
2016 if (cameraState != nullptr) {
2017 cameraState->setShimParams(params);
2018 } else {
2019 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
2020 __FUNCTION__, cameraId.string());
2021 }
2022 }
2023
Ravneetaeb20dc2022-03-30 05:33:03 +00002024 // Enable/disable camera service watchdog
2025 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2026
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002027 // Set rotate-and-crop override behavior
2028 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2029 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Austin Borger18b30a72022-10-27 12:20:29 -07002030 } else if (overrideToPortrait && portraitRotation != 0) {
2031 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2032 switch (portraitRotation) {
2033 case 90:
2034 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2035 break;
2036 case 180:
2037 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2038 break;
2039 case 270:
2040 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2041 break;
2042 default:
2043 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2044 break;
2045 }
2046 client->setRotateAndCropOverride(rotateAndCropMode);
Emilian Peev13f35ad2022-04-27 11:28:48 -07002047 } else {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002048 client->setRotateAndCropOverride(
2049 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2050 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2051 }
2052
2053 // Set autoframing override behaviour
2054 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2055 client->setAutoframingOverride(mOverrideAutoframingMode);
2056 } else {
2057 client->setAutoframingOverride(
2058 mCameraServiceProxyWrapper->getAutoframingOverride(
2059 clientPackageName));
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002060 }
2061
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002062 // Set camera muting behavior
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002063 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08002064 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002065 if (client->supportsCameraMute()) {
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002066 client->setCameraMute(
2067 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2068 } else if (isCameraPrivacyEnabled) {
2069 // no camera mute supported, but privacy is on! => disconnect
2070 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2071 String8(client->getPackageName()).string(), cameraId.string());
2072 // Do not hold mServiceLock while disconnecting clients, but
2073 // retain the condition blocking other clients from connecting
2074 // in mServiceLockWrapper if held.
2075 mServiceLock.unlock();
2076 // Clear caller identity temporarily so client disconnect PID
2077 // checks work correctly
2078 int64_t token = CameraThreadState::clearCallingIdentity();
2079 // Note AppOp to trigger the "Unblock" dialog
2080 client->noteAppOp();
2081 client->disconnect();
2082 CameraThreadState::restoreCallingIdentity(token);
2083 // Reacquire mServiceLock
2084 mServiceLock.lock();
2085
2086 return STATUS_ERROR_FMT(ERROR_DISABLED,
2087 "Camera \"%s\" disabled due to camera mute", cameraId.string());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002088 }
2089
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002090 if (shimUpdateOnly) {
2091 // If only updating legacy shim parameters, immediately disconnect client
2092 mServiceLock.unlock();
2093 client->disconnect();
2094 mServiceLock.lock();
2095 } else {
2096 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002097 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002098 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002099
2100 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002101 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002102 } // lock is destroyed, allow further connect calls
2103
2104 // Important: release the mutex here so the client can call back into the service from its
2105 // destructor (can be at the end of the call)
2106 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002107
2108 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002109 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002110 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002111
Cliff Wud3a05312021-04-26 23:07:31 +08002112 {
2113 Mutex::Autolock lock(mInjectionParametersLock);
2114 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2115 mInjectionInitPending = false;
2116 status_t res = NO_ERROR;
2117 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2118 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002119 sp<BasicClient> clientSp = clientDescriptor->getValue();
2120 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2121 if(res != OK) {
2122 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2123 "No camera device with ID \"%s\" currently available",
2124 mInjectionExternalCamId.string());
2125 }
2126 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002127 if (res != OK) {
2128 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2129 }
2130 } else {
2131 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
2132 __FUNCTION__, mInjectionInternalCamId.string());
2133 res = NO_INIT;
2134 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2135 }
2136 }
2137 }
2138
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002139 return ret;
2140}
2141
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002142status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
2143 if (offlineClient.get() == nullptr) {
2144 return BAD_VALUE;
2145 }
2146
2147 {
2148 // Acquire mServiceLock and prevent other clients from connecting
2149 std::unique_ptr<AutoConditionLock> lock =
2150 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2151
2152 if (lock == nullptr) {
2153 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2154 , __FUNCTION__, offlineClient->getClientPid());
2155 return TIMED_OUT;
2156 }
2157
2158 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2159 if (onlineClientDesc.get() == nullptr) {
2160 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2161 cameraId.c_str());
2162 return BAD_VALUE;
2163 }
2164
2165 // Offline clients do not evict or conflict with other online devices. Resource sharing
2166 // conflicts are handled by the camera provider which will either succeed or fail before
2167 // reaching this method.
2168 const auto& onlinePriority = onlineClientDesc->getPriority();
2169 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2170 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
2171 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002172 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002173 // native clients don't have offline processing support.
2174 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002175 if (offlineClientDesc == nullptr) {
2176 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2177 return BAD_VALUE;
2178 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002179
2180 // Allow only one offline device per camera
2181 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2182 if (!incompatibleClients.empty()) {
2183 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2184 return BAD_VALUE;
2185 }
2186
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002187 String8 monitorTags = isClientWatched(offlineClient.get()) ? mMonitorTags : String8("");
2188 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002189 if (err != OK) {
2190 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2191 return err;
2192 }
2193
2194 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2195 if (evicted.size() > 0) {
2196 for (auto& i : evicted) {
2197 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
2198 __FUNCTION__, i->getKey().string());
2199 }
2200
2201 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2202 "properly", __FUNCTION__);
2203
2204 return BAD_VALUE;
2205 }
2206
2207 logConnectedOffline(offlineClientDesc->getKey(),
2208 static_cast<int>(offlineClientDesc->getOwnerId()),
2209 String8(offlineClient->getPackageName()));
2210
2211 sp<IBinder> remoteCallback = offlineClient->getRemote();
2212 if (remoteCallback != nullptr) {
2213 remoteCallback->linkToDeath(this);
2214 }
2215 } // lock is destroyed, allow further connect calls
2216
2217 return OK;
2218}
2219
Rucha Katakwar38284522021-11-10 11:25:21 -08002220Status CameraService::turnOnTorchWithStrengthLevel(const String16& cameraId, int32_t torchStrength,
2221 const sp<IBinder>& clientBinder) {
2222 Mutex::Autolock lock(mServiceLock);
2223
2224 ATRACE_CALL();
2225 if (clientBinder == nullptr) {
2226 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2227 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2228 "Torch client binder in null.");
2229 }
2230
2231 String8 id = String8(cameraId.string());
2232 int uid = CameraThreadState::getCallingUid();
2233
2234 if (shouldRejectSystemCameraConnection(id)) {
2235 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
2236 "for system only device %s: ", id.string());
2237 }
2238
2239 // verify id is valid
2240 auto state = getCameraState(id);
2241 if (state == nullptr) {
2242 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
2243 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2244 "Camera ID \"%s\" is a not valid camera ID", id.string());
2245 }
2246
2247 StatusInternal cameraStatus = state->getStatus();
2248 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2249 cameraStatus != StatusInternal::PRESENT) {
2250 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(),
2251 (int)cameraStatus);
2252 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2253 "Camera ID \"%s\" is a not valid camera ID", id.string());
2254 }
2255
2256 {
2257 Mutex::Autolock al(mTorchStatusMutex);
2258 TorchModeStatus status;
2259 status_t err = getTorchStatusLocked(id, &status);
2260 if (err != OK) {
2261 if (err == NAME_NOT_FOUND) {
2262 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2263 "Camera \"%s\" does not have a flash unit", id.string());
2264 }
2265 ALOGE("%s: getting current torch status failed for camera %s",
2266 __FUNCTION__, id.string());
2267 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2268 "Error changing torch strength level for camera \"%s\": %s (%d)",
2269 id.string(), strerror(-err), err);
2270 }
2271
2272 if (status == TorchModeStatus::NOT_AVAILABLE) {
2273 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2274 ALOGE("%s: torch mode of camera %s is not available because "
2275 "camera is in use.", __FUNCTION__, id.string());
2276 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2277 "Torch for camera \"%s\" is not available due to an existing camera user",
2278 id.string());
2279 } else {
2280 ALOGE("%s: torch mode of camera %s is not available due to "
2281 "insufficient resources", __FUNCTION__, id.string());
2282 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2283 "Torch for camera \"%s\" is not available due to insufficient resources",
2284 id.string());
2285 }
2286 }
2287 }
2288
2289 {
2290 Mutex::Autolock al(mTorchUidMapMutex);
2291 updateTorchUidMapLocked(cameraId, uid);
2292 }
2293 // Check if the current torch strength level is same as the new one.
2294 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
2295 id.string(), torchStrength);
2296
2297 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(id, torchStrength);
2298
2299 if (err != OK) {
2300 int32_t errorCode;
2301 String8 msg;
2302 switch (err) {
2303 case -ENOSYS:
2304 msg = String8::format("Camera \"%s\" has no flashlight.",
2305 id.string());
2306 errorCode = ERROR_ILLEGAL_ARGUMENT;
2307 break;
2308 case -EBUSY:
2309 msg = String8::format("Camera \"%s\" is in use",
2310 id.string());
2311 errorCode = ERROR_CAMERA_IN_USE;
2312 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002313 case -EINVAL:
2314 msg = String8::format("Torch strength level %d is not within the "
2315 "valid range.", torchStrength);
2316 errorCode = ERROR_ILLEGAL_ARGUMENT;
2317 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002318 default:
2319 msg = String8::format("Changing torch strength level failed.");
2320 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002321 }
2322 ALOGE("%s: %s", __FUNCTION__, msg.string());
2323 return STATUS_ERROR(errorCode, msg.string());
2324 }
2325
2326 {
2327 // update the link to client's death
2328 // Store the last client that turns on each camera's torch mode.
2329 Mutex::Autolock al(mTorchClientMapMutex);
2330 ssize_t index = mTorchClientMap.indexOfKey(id);
2331 if (index == NAME_NOT_FOUND) {
2332 mTorchClientMap.add(id, clientBinder);
2333 } else {
2334 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2335 mTorchClientMap.replaceValueAt(index, clientBinder);
2336 }
2337 clientBinder->linkToDeath(this);
2338 }
2339
2340 int clientPid = CameraThreadState::getCallingPid();
2341 const char *id_cstr = id.c_str();
2342 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
2343 __FUNCTION__, id_cstr, torchStrength, clientPid);
2344 if (!shouldSkipTorchStrengthUpdates) {
2345 broadcastTorchStrengthLevel(id, torchStrength);
2346 }
2347 return Status::ok();
2348}
2349
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002350Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002351 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002352 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002353
2354 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002355 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002356 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002357 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2358 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002359 }
2360
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002361 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07002362 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002363
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002364 if (shouldRejectSystemCameraConnection(id)) {
2365 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
2366 " for system only device %s: ", id.string());
2367 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002368 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08002369 auto state = getCameraState(id);
2370 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002371 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002372 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2373 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002374 }
2375
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002376 StatusInternal cameraStatus = state->getStatus();
2377 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002378 cameraStatus != StatusInternal::NOT_AVAILABLE) {
2379 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002380 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2381 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002382 }
2383
2384 {
2385 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002386 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002387 status_t err = getTorchStatusLocked(id, &status);
2388 if (err != OK) {
2389 if (err == NAME_NOT_FOUND) {
2390 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2391 "Camera \"%s\" does not have a flash unit", id.string());
2392 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002393 ALOGE("%s: getting current torch status failed for camera %s",
2394 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002395 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2396 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
2397 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002398 }
2399
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002400 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002401 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002402 ALOGE("%s: torch mode of camera %s is not available because "
2403 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002404 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2405 "Torch for camera \"%s\" is not available due to an existing camera user",
2406 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002407 } else {
2408 ALOGE("%s: torch mode of camera %s is not available due to "
2409 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002410 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2411 "Torch for camera \"%s\" is not available due to insufficient resources",
2412 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002413 }
2414 }
2415 }
2416
Ruben Brunk99e69712015-05-26 17:25:07 -07002417 {
2418 // Update UID map - this is used in the torch status changed callbacks, so must be done
2419 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002420 Mutex::Autolock al(mTorchUidMapMutex);
Rucha Katakwar38284522021-11-10 11:25:21 -08002421 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07002422 }
2423
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002424 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002425
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002426 if (err != OK) {
2427 int32_t errorCode;
2428 String8 msg;
2429 switch (err) {
2430 case -ENOSYS:
2431 msg = String8::format("Camera \"%s\" has no flashlight",
2432 id.string());
2433 errorCode = ERROR_ILLEGAL_ARGUMENT;
2434 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08002435 case -EBUSY:
2436 msg = String8::format("Camera \"%s\" is in use",
2437 id.string());
2438 errorCode = ERROR_CAMERA_IN_USE;
2439 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002440 default:
2441 msg = String8::format(
2442 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
2443 id.string(), enabled, strerror(-err), err);
2444 errorCode = ERROR_INVALID_OPERATION;
2445 }
2446 ALOGE("%s: %s", __FUNCTION__, msg.string());
Rucha Katakward9ea6452021-05-06 11:57:16 -07002447 logServiceError(msg,errorCode);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002448 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002449 }
2450
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002451 {
2452 // update the link to client's death
2453 Mutex::Autolock al(mTorchClientMapMutex);
2454 ssize_t index = mTorchClientMap.indexOfKey(id);
2455 if (enabled) {
2456 if (index == NAME_NOT_FOUND) {
2457 mTorchClientMap.add(id, clientBinder);
2458 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07002459 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002460 mTorchClientMap.replaceValueAt(index, clientBinder);
2461 }
2462 clientBinder->linkToDeath(this);
2463 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07002464 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002465 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002466 }
2467
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002468 int clientPid = CameraThreadState::getCallingPid();
2469 const char *id_cstr = id.c_str();
2470 const char *torchState = enabled ? "on" : "off";
2471 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
2472 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002473 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002474}
2475
Rucha Katakwar38284522021-11-10 11:25:21 -08002476void CameraService::updateTorchUidMapLocked(const String16& cameraId, int uid) {
2477 String8 id = String8(cameraId.string());
2478 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
2479 mTorchUidMap[id].first = uid;
2480 mTorchUidMap[id].second = uid;
2481 } else {
2482 // Set the pending UID
2483 mTorchUidMap[id].first = uid;
2484 }
2485}
2486
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002487Status CameraService::notifySystemEvent(int32_t eventId,
2488 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002489 const int pid = CameraThreadState::getCallingPid();
2490 const int selfPid = getpid();
2491
2492 // Permission checks
2493 if (pid != selfPid) {
2494 // Ensure we're being called by system_server, or similar process with
2495 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002496 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002497 const int uid = CameraThreadState::getCallingUid();
2498 ALOGE("Permission Denial: cannot send updates to camera service about system"
2499 " events from pid=%d, uid=%d", pid, uid);
2500 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09002501 "No permission to send updates to camera service about system events"
2502 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002503 }
2504 }
2505
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002506 ATRACE_CALL();
2507
Ruben Brunk36597b22015-03-20 22:15:57 -07002508 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002509 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002510 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002511 // from a system server crash
2512 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002513 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002514 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002515 break;
2516 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02002517 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
2518 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
2519 // Notify CameraProviderManager for lazy HALs
2520 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
2521 std::to_string(args[0]));
2522 break;
2523 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002524 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002525 default: {
2526 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2527 eventId);
2528 break;
2529 }
2530 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002531 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002532}
2533
Emilian Peev53722fa2019-02-22 17:47:20 -08002534void CameraService::notifyMonitoredUids() {
2535 Mutex::Autolock lock(mStatusListenerLock);
2536
2537 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002538 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07002539 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
2540 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08002541 }
2542}
2543
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002544Status CameraService::notifyDeviceStateChange(int64_t newState) {
2545 const int pid = CameraThreadState::getCallingPid();
2546 const int selfPid = getpid();
2547
2548 // Permission checks
2549 if (pid != selfPid) {
2550 // Ensure we're being called by system_server, or similar process with
2551 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002552 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002553 const int uid = CameraThreadState::getCallingUid();
2554 ALOGE("Permission Denial: cannot send updates to camera service about device"
2555 " state changes from pid=%d, uid=%d", pid, uid);
2556 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2557 "No permission to send updates to camera service about device state"
2558 " changes from pid=%d, uid=%d", pid, uid);
2559 }
2560 }
2561
2562 ATRACE_CALL();
2563
Austin Borger18b30a72022-10-27 12:20:29 -07002564 {
2565 Mutex::Autolock lock(mServiceLock);
2566 mDeviceState = newState;
2567 }
2568
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07002569 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002570
2571 return Status::ok();
2572}
2573
Emilian Peev8b64f282021-03-25 16:49:57 -07002574Status CameraService::notifyDisplayConfigurationChange() {
2575 ATRACE_CALL();
2576 const int callingPid = CameraThreadState::getCallingPid();
2577 const int selfPid = getpid();
2578
2579 // Permission checks
2580 if (callingPid != selfPid) {
2581 // Ensure we're being called by system_server, or similar process with
2582 // permissions to notify the camera service about system events
2583 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2584 const int uid = CameraThreadState::getCallingUid();
2585 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2586 " changes from pid=%d, uid=%d", callingPid, uid);
2587 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2588 "No permission to send updates to camera service about orientation"
2589 " changes from pid=%d, uid=%d", callingPid, uid);
2590 }
2591 }
2592
2593 Mutex::Autolock lock(mServiceLock);
2594
2595 // Don't do anything if rotate-and-crop override via cmd is active
2596 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2597
2598 const auto clients = mActiveClientManager.getAll();
2599 for (auto& current : clients) {
2600 if (current != nullptr) {
2601 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07002602 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
2603 basicClient->setRotateAndCropOverride(
2604 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2605 basicClient->getPackageName(),
2606 basicClient->getCameraFacing(),
2607 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07002608 }
2609 }
2610 }
2611
2612 return Status::ok();
2613}
2614
2615Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002616 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2617 ATRACE_CALL();
2618 if (!concurrentCameraIds) {
2619 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2620 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2621 }
2622
2623 if (!mInitialized) {
2624 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002625 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002626 return STATUS_ERROR(ERROR_DISCONNECTED,
2627 "Camera subsystem is not available");
2628 }
2629 // First call into the provider and get the set of concurrent camera
2630 // combinations
2631 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002632 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002633 for (auto &combination : concurrentCameraCombinations) {
2634 std::vector<std::string> validCombination;
2635 for (auto &cameraId : combination) {
2636 // if the camera state is not present, skip
2637 String8 cameraIdStr(cameraId.c_str());
2638 auto state = getCameraState(cameraIdStr);
2639 if (state == nullptr) {
2640 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2641 continue;
2642 }
2643 StatusInternal status = state->getStatus();
2644 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2645 continue;
2646 }
2647 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2648 continue;
2649 }
2650 validCombination.push_back(cameraId);
2651 }
2652 if (validCombination.size() != 0) {
2653 concurrentCameraIds->push_back(std::move(validCombination));
2654 }
2655 }
2656 return Status::ok();
2657}
2658
2659Status CameraService::isConcurrentSessionConfigurationSupported(
2660 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002661 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002662 if (!isSupported) {
2663 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2664 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2665 }
2666
2667 if (!mInitialized) {
2668 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2669 return STATUS_ERROR(ERROR_DISCONNECTED,
2670 "Camera subsystem is not available");
2671 }
2672
2673 // Check for camera permissions
2674 int callingPid = CameraThreadState::getCallingPid();
2675 int callingUid = CameraThreadState::getCallingUid();
2676 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2677 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2678 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2679 "android.permission.CAMERA needed to call"
2680 "isConcurrentSessionConfigurationSupported");
2681 }
2682
2683 status_t res =
2684 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002685 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
2686 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002687 if (res != OK) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07002688 logServiceError(String8::format("Unable to query session configuration support"),
2689 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002690 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2691 "support %s (%d)", strerror(-res), res);
2692 }
2693 return Status::ok();
2694}
2695
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002696Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2697 /*out*/
2698 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002699 return addListenerHelper(listener, cameraStatuses);
2700}
2701
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002702binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2703 std::vector<hardware::CameraStatus>* cameraStatuses) {
2704 return addListenerHelper(listener, cameraStatuses, false, true);
2705}
2706
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002707Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2708 /*out*/
2709 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002710 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002711
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002712 ATRACE_CALL();
2713
Igor Murashkinbfc99152013-02-27 12:55:20 -08002714 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002715
Ruben Brunk3450ba72015-06-16 11:00:37 -07002716 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002717 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002718 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002719 }
2720
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002721 auto clientUid = CameraThreadState::getCallingUid();
2722 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002723 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
Jayant Chowdharyc3198c32021-07-28 20:59:14 +00002724 clientPid, clientUid, /*logPermissionFailure*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002725
Igor Murashkinbfc99152013-02-27 12:55:20 -08002726 Mutex::Autolock lock(mServiceLock);
2727
Ruben Brunkcc776712015-02-17 20:18:47 -08002728 {
2729 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002730 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002731 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002732 ALOGW("%s: Tried to add listener %p which was already subscribed",
2733 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002734 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002735 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002736 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002737
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002738 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002739 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2740 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002741 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08002742 if (ret != NO_ERROR) {
2743 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2744 strerror(-ret), ret);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002745 logServiceError(msg,ERROR_ILLEGAL_ARGUMENT);
Emilian Peev53722fa2019-02-22 17:47:20 -08002746 ALOGE("%s: %s", __FUNCTION__, msg.string());
2747 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2748 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002749 // The listener still needs to be added to the list of listeners, regardless of what
2750 // permissions the listener process has / whether it is a vendor listener. Since it might be
2751 // eligible to listen to other camera ids.
2752 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002753 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002754 }
2755
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002756 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002757 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002758 Mutex::Autolock lock(mCameraStatesLock);
2759 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002760 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07002761 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
2762 openCloseCallbackAllowed ? i.second->getClientPackage() : String8::empty());
Igor Murashkincba2c162013-03-20 15:56:31 -07002763 }
2764 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002765 // Remove the camera statuses that should be hidden from the client, we do
2766 // this after collecting the states in order to avoid holding
2767 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2768 // the same time.
2769 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2770 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2771 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2772 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2773 ALOGE("%s: Invalid camera id %s, skipping status update",
2774 __FUNCTION__, s.cameraId.c_str());
2775 return true;
2776 }
2777 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2778 clientUid);}), cameraStatuses->end());
2779
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002780 //cameraStatuses will have non-eligible camera ids removed.
2781 std::set<String16> idsChosenForCallback;
2782 for (const auto &s : *cameraStatuses) {
2783 idsChosenForCallback.insert(String16(s.cameraId));
2784 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002785
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002786 /*
2787 * Immediately signal current torch status to this listener only
2788 * This may be a subset of all the devices, so don't include it in the response directly
2789 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002790 {
2791 Mutex::Autolock al(mTorchStatusMutex);
2792 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002793 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002794 // The camera id is visible to the client. Fine to send torch
2795 // callback.
2796 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2797 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2798 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002799 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002800 }
2801
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002802 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002803}
Ruben Brunkcc776712015-02-17 20:18:47 -08002804
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002805Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002806 ATRACE_CALL();
2807
Igor Murashkinbfc99152013-02-27 12:55:20 -08002808 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2809
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002810 if (listener == 0) {
2811 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002812 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002813 }
2814
Igor Murashkinbfc99152013-02-27 12:55:20 -08002815 Mutex::Autolock lock(mServiceLock);
2816
Ruben Brunkcc776712015-02-17 20:18:47 -08002817 {
2818 Mutex::Autolock lock(mStatusListenerLock);
2819 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002820 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2821 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2822 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002823 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002824 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002825 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002826 }
2827 }
2828
2829 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2830 __FUNCTION__, listener.get());
2831
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002832 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002833}
2834
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002835Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002836
2837 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002838 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2839
2840 if (parameters == NULL) {
2841 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002842 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002843 }
2844
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002845 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002846
2847 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002848 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002849 // Error logged by caller
2850 return ret;
2851 }
2852
2853 String8 shimParamsString8 = shimParams.flatten();
2854 String16 shimParamsString16 = String16(shimParamsString8);
2855
2856 *parameters = shimParamsString16;
2857
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002858 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002859}
2860
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002861Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2862 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002863 ATRACE_CALL();
2864
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002865 const String8 id = String8(cameraId);
2866
2867 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002868
2869 switch (apiVersion) {
2870 case API_VERSION_1:
2871 case API_VERSION_2:
2872 break;
2873 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002874 String8 msg = String8::format("Unknown API version %d", apiVersion);
2875 ALOGE("%s: %s", __FUNCTION__, msg.string());
2876 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002877 }
2878
Austin Borger18b30a72022-10-27 12:20:29 -07002879 int portraitRotation;
2880 auto deviceVersionAndTransport = getDeviceVersion(id, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002881 if (deviceVersionAndTransport.first == -1) {
2882 String8 msg = String8::format("Unknown camera ID %s", id.string());
2883 ALOGE("%s: %s", __FUNCTION__, msg.string());
2884 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2885 }
2886 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
2887 int deviceVersion = deviceVersionAndTransport.first;
2888 switch (deviceVersion) {
2889 case CAMERA_DEVICE_API_VERSION_1_0:
2890 case CAMERA_DEVICE_API_VERSION_3_0:
2891 case CAMERA_DEVICE_API_VERSION_3_1:
2892 if (apiVersion == API_VERSION_2) {
2893 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
2894 "shim", __FUNCTION__, id.string(), deviceVersion);
2895 *isSupported = false;
2896 } else { // if (apiVersion == API_VERSION_1) {
2897 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
2898 "supported", __FUNCTION__, id.string());
2899 *isSupported = true;
2900 }
2901 break;
2902 case CAMERA_DEVICE_API_VERSION_3_2:
2903 case CAMERA_DEVICE_API_VERSION_3_3:
2904 case CAMERA_DEVICE_API_VERSION_3_4:
2905 case CAMERA_DEVICE_API_VERSION_3_5:
2906 case CAMERA_DEVICE_API_VERSION_3_6:
2907 case CAMERA_DEVICE_API_VERSION_3_7:
2908 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002909 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002910 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002911 break;
2912 default: {
2913 String8 msg = String8::format("Unknown device version %x for device %s",
2914 deviceVersion, id.string());
2915 ALOGE("%s: %s", __FUNCTION__, msg.string());
2916 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002917 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002918 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002919 } else {
2920 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002921 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002922 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002923}
2924
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002925Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2926 /*out*/ bool *isSupported) {
2927 ATRACE_CALL();
2928
2929 const String8 id = String8(cameraId);
2930
2931 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2932 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2933
2934 return Status::ok();
2935}
2936
Cliff Wud8cae102021-03-11 01:37:42 +08002937Status CameraService::injectCamera(
2938 const String16& packageName, const String16& internalCamId,
2939 const String16& externalCamId,
2940 const sp<ICameraInjectionCallback>& callback,
2941 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08002942 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08002943 ATRACE_CALL();
2944
2945 if (!checkCallingPermission(sCameraInjectExternalCameraPermission)) {
2946 const int pid = CameraThreadState::getCallingPid();
2947 const int uid = CameraThreadState::getCallingUid();
2948 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
2949 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2950 "Permission Denial: no permission to inject camera");
2951 }
2952
2953 ALOGV(
2954 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
2955 "%s",
2956 __FUNCTION__, String8(packageName).string(),
2957 String8(internalCamId).string(), String8(externalCamId).string());
2958
Cliff Wud3a05312021-04-26 23:07:31 +08002959 {
2960 Mutex::Autolock lock(mInjectionParametersLock);
2961 mInjectionInternalCamId = String8(internalCamId);
2962 mInjectionExternalCamId = String8(externalCamId);
Cliff Wu646bd612021-11-23 23:21:29 +08002963 mInjectionStatusListener->addListener(callback);
2964 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08002965 status_t res = NO_ERROR;
2966 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2967 // If the client already exists, we can directly connect to the camera device through the
2968 // client's injectCamera(), otherwise we need to wait until the client is established
2969 // (execute connectHelper()) before injecting the camera to the camera device.
2970 if (clientDescriptor != nullptr) {
2971 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08002972 sp<BasicClient> clientSp = clientDescriptor->getValue();
2973 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2974 if(res != OK) {
2975 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2976 "No camera device with ID \"%s\" currently available",
2977 mInjectionExternalCamId.string());
2978 }
2979 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002980 if(res != OK) {
2981 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2982 }
2983 } else {
2984 mInjectionInitPending = true;
2985 }
2986 }
Cliff Wud8cae102021-03-11 01:37:42 +08002987
Cliff Wud3a05312021-04-26 23:07:31 +08002988 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08002989}
2990
Ruben Brunkcc776712015-02-17 20:18:47 -08002991void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002992 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002993 for (auto& i : mActiveClientManager.getAll()) {
2994 auto clientSp = i->getValue();
2995 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002996 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08002997 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002998 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002999 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003000 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003001}
3002
Ruben Brunkcc776712015-02-17 20:18:47 -08003003bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003004 bool ret = false;
3005 {
3006 // Acquire mServiceLock and prevent other clients from connecting
3007 std::unique_ptr<AutoConditionLock> lock =
3008 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003009
Igor Murashkin634a5152013-02-20 17:15:11 -08003010
Ruben Brunkcc776712015-02-17 20:18:47 -08003011 std::vector<sp<BasicClient>> evicted;
3012 for (auto& i : mActiveClientManager.getAll()) {
3013 auto clientSp = i->getValue();
3014 if (clientSp.get() == nullptr) {
3015 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3016 mActiveClientManager.remove(i);
3017 continue;
3018 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003019 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003020 mActiveClientManager.remove(i);
3021 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003022
Ruben Brunkcc776712015-02-17 20:18:47 -08003023 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003024 clientSp->notifyError(
3025 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003026 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003027 }
3028 }
3029
Ruben Brunkcc776712015-02-17 20:18:47 -08003030 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3031 // other clients from connecting in mServiceLockWrapper if held
3032 mServiceLock.unlock();
3033
Ruben Brunk36597b22015-03-20 22:15:57 -07003034 // Do not clear caller identity, remote caller should be client proccess
3035
Ruben Brunkcc776712015-02-17 20:18:47 -08003036 for (auto& i : evicted) {
3037 if (i.get() != nullptr) {
3038 i->disconnect();
3039 ret = true;
3040 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003041 }
3042
Ruben Brunkcc776712015-02-17 20:18:47 -08003043 // Reacquire mServiceLock
3044 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003045
Ruben Brunkcc776712015-02-17 20:18:47 -08003046 } // lock is destroyed, allow further connect calls
3047
3048 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003049}
3050
Ruben Brunkcc776712015-02-17 20:18:47 -08003051std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
3052 const String8& cameraId) const {
3053 std::shared_ptr<CameraState> state;
3054 {
3055 Mutex::Autolock lock(mCameraStatesLock);
3056 auto iter = mCameraStates.find(cameraId);
3057 if (iter != mCameraStates.end()) {
3058 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003059 }
3060 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003061 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003062}
3063
Ruben Brunkcc776712015-02-17 20:18:47 -08003064sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
3065 // Remove from active clients list
3066 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3067 if (clientDescriptorPtr == nullptr) {
3068 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
3069 cameraId.string());
3070 return sp<BasicClient>{nullptr};
3071 }
3072
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003073 sp<BasicClient> client = clientDescriptorPtr->getValue();
3074 if (client.get() != nullptr) {
3075 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3076 }
3077 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003078}
3079
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003080void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003081 // Acquire mServiceLock and prevent other clients from connecting
3082 std::unique_ptr<AutoConditionLock> lock =
3083 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3084
Ruben Brunk6267b532015-04-30 17:44:07 -07003085 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003086 for (size_t i = 0; i < newUserIds.size(); i++) {
3087 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003088 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003089 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003090 return;
3091 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003092 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003093 }
3094
Ruben Brunka8ca9152015-04-07 14:23:40 -07003095
Ruben Brunk6267b532015-04-30 17:44:07 -07003096 if (newAllowedUsers == mAllowedUsers) {
3097 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3098 return;
3099 }
3100
3101 logUserSwitch(mAllowedUsers, newAllowedUsers);
3102
3103 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003104
3105 // Current user has switched, evict all current clients.
3106 std::vector<sp<BasicClient>> evicted;
3107 for (auto& i : mActiveClientManager.getAll()) {
3108 auto clientSp = i->getValue();
3109
3110 if (clientSp.get() == nullptr) {
3111 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3112 continue;
3113 }
3114
Ruben Brunk6267b532015-04-30 17:44:07 -07003115 // Don't evict clients that are still allowed.
3116 uid_t clientUid = clientSp->getClientUid();
3117 userid_t clientUserId = multiuser_get_user_id(clientUid);
3118 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3119 continue;
3120 }
3121
Ruben Brunk36597b22015-03-20 22:15:57 -07003122 evicted.push_back(clientSp);
3123
3124 String8 curTime = getFormattedCurrentTime();
3125
3126 ALOGE("Evicting conflicting client for camera ID %s due to user change",
3127 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003128
Ruben Brunk36597b22015-03-20 22:15:57 -07003129 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07003130 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003131 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
3132 " to user switch.", i->getKey().string(),
3133 String8{clientSp->getPackageName()}.string(),
3134 i->getOwnerId(), i->getPriority().getScore(),
3135 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003136
3137 }
3138
3139 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3140 // blocking other clients from connecting in mServiceLockWrapper if held.
3141 mServiceLock.unlock();
3142
3143 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07003144 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003145
3146 for (auto& i : evicted) {
3147 i->disconnect();
3148 }
3149
Jayant Chowdhary12361932018-08-27 14:46:13 -07003150 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003151
3152 // Reacquire mServiceLock
3153 mServiceLock.lock();
3154}
Ruben Brunkcc776712015-02-17 20:18:47 -08003155
Ruben Brunka8ca9152015-04-07 14:23:40 -07003156void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003157 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003158 Mutex::Autolock l(mLogLock);
Rucha Katakward9ea6452021-05-06 11:57:16 -07003159 String8 msg = String8::format("%s : %s", curTime.string(), event);
3160 // For service error events, print the msg only once.
3161 if(!msg.contains("SERVICE ERROR")) {
3162 mEventLog.add(msg);
3163 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3164 // Error event not added to the dumpsys log before
3165 mEventLog.add(msg);
3166 sServiceErrorEventSet.insert(msg);
3167 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003168}
3169
Ruben Brunka8ca9152015-04-07 14:23:40 -07003170void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003171 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003172 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07003173 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003174 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003175}
3176
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003177void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
3178 const char* clientPackage) {
3179 // Log the clients evicted
3180 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
3181 cameraId, clientPackage, clientPid));
3182}
3183
Ruben Brunka8ca9152015-04-07 14:23:40 -07003184void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003185 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003186 // Log the clients evicted
3187 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003188 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003189}
3190
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003191void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
3192 const char* clientPackage) {
3193 // Log the clients evicted
3194 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
3195 clientPackage, clientPid));
3196}
3197
Ruben Brunka8ca9152015-04-07 14:23:40 -07003198void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003199 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003200 // Log the client rejected
3201 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003202 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003203}
3204
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003205void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
3206 // Log torch event
3207 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
3208 torchState, clientPid));
3209}
3210
Ruben Brunk6267b532015-04-30 17:44:07 -07003211void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3212 const std::set<userid_t>& newUserIds) {
3213 String8 newUsers = toString(newUserIds);
3214 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003215 if (oldUsers.size() == 0) {
3216 oldUsers = "<None>";
3217 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003218 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003219 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07003220 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003221}
3222
3223void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
3224 // Log the device removal
3225 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
3226}
3227
3228void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
3229 // Log the device removal
3230 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
3231}
3232
3233void CameraService::logClientDied(int clientPid, const char* reason) {
3234 // Log the device removal
3235 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003236}
3237
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003238void CameraService::logServiceError(const char* msg, int errorCode) {
3239 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003240 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003241}
3242
Ruben Brunk36597b22015-03-20 22:15:57 -07003243status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3244 uint32_t flags) {
3245
Mathias Agopian65ab4712010-07-14 17:59:35 -07003246 // Permission checks
3247 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003248 case SHELL_COMMAND_TRANSACTION: {
3249 int in = data.readFileDescriptor();
3250 int out = data.readFileDescriptor();
3251 int err = data.readFileDescriptor();
3252 int argc = data.readInt32();
3253 Vector<String16> args;
3254 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3255 args.add(data.readString16());
3256 }
3257 sp<IBinder> unusedCallback;
3258 sp<IResultReceiver> resultReceiver;
3259 status_t status;
3260 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3261 return status;
3262 }
3263 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3264 return status;
3265 }
3266 status = shellCommand(in, out, err, args);
3267 if (resultReceiver != nullptr) {
3268 resultReceiver->send(status);
3269 }
3270 return NO_ERROR;
3271 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003272 }
3273
3274 return BnCameraService::onTransact(code, data, reply, flags);
3275}
3276
Mathias Agopian65ab4712010-07-14 17:59:35 -07003277// We share the media players for shutter and recording sound for all clients.
3278// A reference count is kept to determine when we will actually release the
3279// media players.
3280
Jaekyun Seokef498052018-03-23 13:09:44 +09003281sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3282 sp<MediaPlayer> mp = new MediaPlayer();
3283 status_t error;
3284 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003285 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003286 error = mp->prepare();
3287 }
3288 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003289 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003290 mp->disconnect();
3291 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003292 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003293 }
3294 return mp;
3295}
3296
username5755fea2018-12-27 09:48:08 +08003297void CameraService::increaseSoundRef() {
3298 Mutex::Autolock lock(mSoundLock);
3299 mSoundRef++;
3300}
3301
3302void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003303 ATRACE_CALL();
3304
username5755fea2018-12-27 09:48:08 +08003305 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3306 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3307 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3308 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3309 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3310 }
3311 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3312 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3313 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3314 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003315 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003316 }
3317 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3318 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3319 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3320 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3321 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003322 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003323}
3324
username5755fea2018-12-27 09:48:08 +08003325void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003326 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003327 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003328 if (--mSoundRef) return;
3329
3330 for (int i = 0; i < NUM_SOUNDS; i++) {
3331 if (mSoundPlayer[i] != 0) {
3332 mSoundPlayer[i]->disconnect();
3333 mSoundPlayer[i].clear();
3334 }
3335 }
3336}
3337
3338void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003339 ATRACE_CALL();
3340
Mathias Agopian65ab4712010-07-14 17:59:35 -07003341 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07003342 if (kind < 0 || kind >= NUM_SOUNDS) {
3343 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
3344 return;
3345 }
3346
Mathias Agopian65ab4712010-07-14 17:59:35 -07003347 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003348 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003349 sp<MediaPlayer> player = mSoundPlayer[kind];
3350 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08003351 player->seekTo(0);
3352 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003353 }
3354}
3355
3356// ----------------------------------------------------------------------------
3357
3358CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07003359 const sp<ICameraClient>& cameraClient,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003360 const String16& clientPackageName, bool systemNativeClient,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003361 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003362 const String8& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003363 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003364 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003365 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003366 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003367 IInterface::asBinder(cameraClient),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003368 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003369 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003370 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003371 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003372 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003373{
Jayant Chowdhary12361932018-08-27 14:46:13 -07003374 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003375 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003376
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003377 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003378
username5755fea2018-12-27 09:48:08 +08003379 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003380
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003381 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003382}
3383
Mathias Agopian65ab4712010-07-14 17:59:35 -07003384// tear down the client
3385CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003386 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08003387 mDestructionStarted = true;
3388
username5755fea2018-12-27 09:48:08 +08003389 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003390 // unconditionally disconnect. function is idempotent
3391 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003392}
3393
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003394sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
3395
Igor Murashkin634a5152013-02-20 17:15:11 -08003396CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003397 const sp<IBinder>& remoteCallback,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003398 const String16& clientPackageName, bool nativeClient,
3399 const std::optional<String16>& clientFeatureId, const String8& cameraIdStr,
3400 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003401 int servicePid, bool overrideToPortrait):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003402 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07003403 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003404 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
3405 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003406 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003407 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07003408 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07003409 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003410 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003411 mRemoteBinder(remoteCallback),
3412 mOpsActive(false),
3413 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08003414{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003415 if (sCameraService == nullptr) {
3416 sCameraService = cameraService;
3417 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08003418
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003419 // There are 2 scenarios in which a client won't have AppOps operations
3420 // (both scenarios : native clients)
3421 // 1) It's an system native client*, the package name will be empty
3422 // and it will return from this function in the previous if condition
3423 // (This is the same as the previously existing behavior).
3424 // 2) It is a system native client, but its package name has been
3425 // modified for debugging, however it still must not use AppOps since
3426 // the package name is not a real one.
3427 //
3428 // * system native client - native client with UID < AID_APP_START. It
3429 // doesn't exclude clients not on the system partition.
3430 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003431 mAppOpsManager = std::make_unique<AppOpsManager>();
3432 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07003433
3434 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08003435}
3436
3437CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003438 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08003439 mDestructionStarted = true;
3440}
3441
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003442binder::Status CameraService::BasicClient::disconnect() {
3443 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003444 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003445 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07003446 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07003447 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08003448
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003449 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003450 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07003451 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
3452 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003453
3454 sp<IBinder> remote = getRemote();
3455 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003456 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08003457 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003458
3459 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07003460 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003461 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
3462 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
3463 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003464
Igor Murashkincba2c162013-03-20 15:56:31 -07003465 // client shouldn't be able to call into us anymore
3466 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003467
3468 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08003469}
3470
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003471status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
3472 // No dumping of clients directly over Binder,
3473 // must go through CameraService::dump
3474 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003475 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003476 return OK;
3477}
3478
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07003479status_t CameraService::BasicClient::startWatchingTags(const String8&, int) {
3480 // Can't watch tags directly, must go through CameraService::startWatchingTags
3481 return OK;
3482}
3483
3484status_t CameraService::BasicClient::stopWatchingTags(int) {
3485 // Can't watch tags directly, must go through CameraService::stopWatchingTags
3486 return OK;
3487}
3488
3489status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
3490 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
3491 return OK;
3492}
3493
Ruben Brunkcc776712015-02-17 20:18:47 -08003494String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003495 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08003496}
3497
Emilian Peev8b64f282021-03-25 16:49:57 -07003498int CameraService::BasicClient::getCameraFacing() const {
3499 return mCameraFacing;
3500}
3501
3502int CameraService::BasicClient::getCameraOrientation() const {
3503 return mOrientation;
3504}
Ruben Brunkcc776712015-02-17 20:18:47 -08003505
3506int CameraService::BasicClient::getClientPid() const {
3507 return mClientPid;
3508}
3509
Ruben Brunk6267b532015-04-30 17:44:07 -07003510uid_t CameraService::BasicClient::getClientUid() const {
3511 return mClientUid;
3512}
3513
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003514bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
3515 // Defaults to API2.
3516 return level == API_2;
3517}
3518
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003519status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003520 {
3521 Mutex::Autolock l(mAudioRestrictionLock);
3522 mAudioRestriction = mode;
3523 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003524 sCameraService->updateAudioRestriction();
3525 return OK;
3526}
3527
3528int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003529 return sCameraService->updateAudioRestriction();
3530}
3531
3532int32_t CameraService::BasicClient::getAudioRestriction() const {
3533 Mutex::Autolock l(mAudioRestrictionLock);
3534 return mAudioRestriction;
3535}
3536
3537bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
3538 switch (mode) {
3539 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
3540 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
3541 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
3542 return true;
3543 default:
3544 return false;
3545 }
3546}
3547
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003548status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
3549 if (mode == AppOpsManager::MODE_ERRORED) {
3550 ALOGI("Camera %s: Access for \"%s\" has been revoked",
3551 mCameraIdStr.string(), String8(mClientPackageName).string());
3552 return PERMISSION_DENIED;
3553 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
3554 // If the calling Uid is trusted (a native service), the AppOpsManager could
3555 // return MODE_IGNORED. Do not treat such case as error.
3556 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
3557 mClientPackageName);
3558 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08003559 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayana8143e572023-01-09 08:46:49 -08003560 // We don't want to return EACCESS if the CameraPrivacy is enabled.
3561 // We prefer to successfully open the camera and perform camera muting
3562 // or blocking in connectHelper as handleAppOpMode can be called before the
3563 // connection has been fully established and at that time camera muting
3564 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003565 if (!isUidActive || !isCameraPrivacyEnabled) {
3566 ALOGI("Camera %s: Access for \"%s\" has been restricted",
3567 mCameraIdStr.string(), String8(mClientPackageName).string());
3568 // Return the same error as for device policy manager rejection
3569 return -EACCES;
3570 }
3571 }
3572 return OK;
3573}
3574
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003575status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003576 ATRACE_CALL();
3577
Igor Murashkine6800ce2013-03-04 17:25:57 -08003578 {
3579 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003580 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003581 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003582 if (mAppOpsManager != nullptr) {
3583 // Notify app ops that the camera is not available
3584 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003585 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
3586 mClientPackageName, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003587
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003588 // Just check for camera acccess here on open - delay startOp until
3589 // camera frames start streaming in startCameraStreamingOps
3590 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
3591 mClientPackageName);
3592 status_t res = handleAppOpMode(mode);
3593 if (res != OK) {
3594 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003595 }
Svetoslav28e8ef72015-05-11 19:21:31 -07003596 }
3597
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003598 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003599
3600 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003601 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003602
Emilian Peev53722fa2019-02-22 17:47:20 -08003603 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
3604
Shuzhen Wang695044d2020-03-06 09:02:23 -08003605 // Notify listeners of camera open/close status
3606 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
3607
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003608 return OK;
3609}
3610
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003611status_t CameraService::BasicClient::startCameraStreamingOps() {
3612 ATRACE_CALL();
3613
3614 if (!mOpsActive) {
3615 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3616 return INVALID_OPERATION;
3617 }
3618 if (mOpsStreaming) {
3619 ALOGV("%s: Streaming already active!", __FUNCTION__);
3620 return OK;
3621 }
3622
3623 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
3624 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3625
3626 if (mAppOpsManager != nullptr) {
3627 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
3628 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
3629 String16("start camera ") + String16(mCameraIdStr));
3630 status_t res = handleAppOpMode(mode);
3631 if (res != OK) {
3632 return res;
3633 }
3634 }
3635
3636 mOpsStreaming = true;
3637
3638 return OK;
3639}
3640
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003641status_t CameraService::BasicClient::noteAppOp() {
3642 ATRACE_CALL();
3643
3644 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
3645 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3646
3647 // noteAppOp is only used for when camera mute is not supported, in order
3648 // to trigger the sensor privacy "Unblock" dialog
3649 if (mAppOpsManager != nullptr) {
3650 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
3651 mClientPackageName, mClientFeatureId,
3652 String16("start camera ") + String16(mCameraIdStr));
3653 status_t res = handleAppOpMode(mode);
3654 if (res != OK) {
3655 return res;
3656 }
3657 }
3658
3659 return OK;
3660}
3661
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003662status_t CameraService::BasicClient::finishCameraStreamingOps() {
3663 ATRACE_CALL();
3664
3665 if (!mOpsActive) {
3666 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3667 return INVALID_OPERATION;
3668 }
3669 if (!mOpsStreaming) {
3670 ALOGV("%s: Streaming not active!", __FUNCTION__);
3671 return OK;
3672 }
3673
3674 if (mAppOpsManager != nullptr) {
3675 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
3676 mClientPackageName, mClientFeatureId);
3677 mOpsStreaming = false;
3678 }
3679
3680 return OK;
3681}
3682
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003683status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003684 ATRACE_CALL();
3685
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003686 if (mOpsStreaming) {
3687 // Make sure we've notified everyone about camera stopping
3688 finishCameraStreamingOps();
3689 }
3690
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003691 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003692 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003693 mOpsActive = false;
3694
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003695 // This function is called when a client disconnects. This should
3696 // release the camera, but actually only if it was in a proper
3697 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003698 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003699 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003700
Ruben Brunkcc776712015-02-17 20:18:47 -08003701 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003702 sCameraService->updateStatus(StatusInternal::PRESENT,
3703 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003704 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003705 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003706 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3707 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003708 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003709 mOpsCallback.clear();
3710
Emilian Peev53722fa2019-02-22 17:47:20 -08003711 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3712
Shuzhen Wang695044d2020-03-06 09:02:23 -08003713 // Notify listeners of camera open/close status
3714 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3715
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003716 return OK;
3717}
3718
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003719void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003720 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003721 if (mAppOpsManager == nullptr) {
3722 return;
3723 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003724 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003725 if (op != AppOpsManager::OP_CAMERA) {
3726 ALOGW("Unexpected app ops notification received: %d", op);
3727 return;
3728 }
3729
3730 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003731 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003732 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003733 ALOGV("checkOp returns: %d, %s ", res,
3734 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3735 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3736 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3737 "UNKNOWN");
3738
Shuzhen Wang64900852021-02-05 09:03:29 -08003739 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003740 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003741 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003742 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003743 } else if (res == AppOpsManager::MODE_IGNORED) {
3744 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08003745 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08003746 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Shuzhen Wang64900852021-02-05 09:03:29 -08003747 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3748 mCameraIdStr.string(), String8(mClientPackageName).string(),
3749 mUidIsTrusted, isUidActive);
3750 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3751 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3752 // error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003753 if (!mUidIsTrusted) {
3754 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
3755 setCameraMute(true);
3756 } else if (!isUidActive
3757 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
3758 block();
3759 }
Shuzhen Wang64900852021-02-05 09:03:29 -08003760 }
Evan Severson09ab4002021-02-10 14:15:19 -08003761 } else if (res == AppOpsManager::MODE_ALLOWED) {
3762 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003763 }
3764}
3765
Svet Ganova453d0d2018-01-11 15:37:58 -08003766void CameraService::BasicClient::block() {
3767 ATRACE_CALL();
3768
3769 // Reset the client PID to allow server-initiated disconnect,
3770 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003771 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003772 CaptureResultExtras resultExtras; // a dummy result (invalid)
3773 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3774 disconnect();
3775}
3776
Mathias Agopian65ab4712010-07-14 17:59:35 -07003777// ----------------------------------------------------------------------------
3778
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003779void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003780 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003781 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003782 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003783 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3784 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3785 api1ErrorCode = CAMERA_ERROR_DISABLED;
3786 }
3787 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003788 } else {
3789 ALOGE("mRemoteCallback is NULL!!");
3790 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003791}
3792
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003793// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003794binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003795 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003796 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003797}
3798
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003799bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3800 return level == API_1;
3801}
3802
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003803CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3804 mClient(client) {
3805}
3806
3807void CameraService::Client::OpsCallback::opChanged(int32_t op,
3808 const String16& packageName) {
3809 sp<BasicClient> client = mClient.promote();
3810 if (client != NULL) {
3811 client->opChanged(op, packageName);
3812 }
3813}
3814
Mathias Agopian65ab4712010-07-14 17:59:35 -07003815// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003816// UidPolicy
3817// ----------------------------------------------------------------------------
3818
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08003819void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003820 Mutex::Autolock _l(mUidLock);
3821
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003822 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003823 status_t res = mAm.linkToDeath(this);
3824 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003825 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00003826 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
3827 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08003828 ActivityManager::PROCESS_STATE_UNKNOWN,
3829 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003830 if (res == OK) {
3831 mRegistered = true;
3832 ALOGV("UidPolicy: Registered with ActivityManager");
3833 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003834}
3835
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08003836void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
3837 if (name != String16(kActivityServiceName)) {
3838 return;
3839 }
3840
3841 registerWithActivityManager();
3842}
3843
3844void CameraService::UidPolicy::registerSelf() {
3845 // Use check service to see if the activity service is available
3846 // If not available then register for notifications, instead of blocking
3847 // till the service is ready
3848 sp<IServiceManager> sm = defaultServiceManager();
3849 sp<IBinder> binder = sm->checkService(String16(kActivityServiceName));
3850 if (!binder) {
3851 sm->registerForNotifications(String16(kActivityServiceName), this);
3852 } else {
3853 registerWithActivityManager();
3854 }
3855}
3856
Svet Ganova453d0d2018-01-11 15:37:58 -08003857void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003858 Mutex::Autolock _l(mUidLock);
3859
Steven Moreland2f348142019-07-02 15:59:07 -07003860 mAm.unregisterUidObserver(this);
3861 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003862 mRegistered = false;
3863 mActiveUids.clear();
3864 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003865}
3866
3867void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3868 onUidIdle(uid, disabled);
3869}
3870
3871void CameraService::UidPolicy::onUidActive(uid_t uid) {
3872 Mutex::Autolock _l(mUidLock);
3873 mActiveUids.insert(uid);
3874}
3875
3876void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3877 bool deleted = false;
3878 {
3879 Mutex::Autolock _l(mUidLock);
3880 if (mActiveUids.erase(uid) > 0) {
3881 deleted = true;
3882 }
3883 }
3884 if (deleted) {
3885 sp<CameraService> service = mService.promote();
3886 if (service != nullptr) {
3887 service->blockClientsForUid(uid);
3888 }
3889 }
3890}
3891
Emilian Peev53722fa2019-02-22 17:47:20 -08003892void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003893 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00003894 bool procStateChange = false;
3895 {
3896 Mutex::Autolock _l(mUidLock);
3897 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
3898 mMonitoredUids[uid].procState != procState) {
3899 mMonitoredUids[uid].procState = procState;
3900 procStateChange = true;
3901 }
3902 }
3903
3904 if (procStateChange) {
3905 sp<CameraService> service = mService.promote();
3906 if (service != nullptr) {
3907 service->notifyMonitoredUids();
3908 }
Emilian Peev53722fa2019-02-22 17:47:20 -08003909 }
3910}
3911
Austin Borger65577682022-02-17 00:25:43 +00003912void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid) {
3913 bool procAdjChange = false;
3914 {
3915 Mutex::Autolock _l(mUidLock);
3916 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3917 procAdjChange = true;
3918 }
3919 }
3920
3921 if (procAdjChange) {
3922 sp<CameraService> service = mService.promote();
3923 if (service != nullptr) {
3924 service->notifyMonitoredUids();
3925 }
3926 }
3927}
3928
Emilian Peev53722fa2019-02-22 17:47:20 -08003929void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3930 Mutex::Autolock _l(mUidLock);
3931 auto it = mMonitoredUids.find(uid);
3932 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00003933 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08003934 } else {
Austin Borger65577682022-02-17 00:25:43 +00003935 MonitoredUid monitoredUid;
3936 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
3937 monitoredUid.refCount = 1;
3938 mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid));
Emilian Peev53722fa2019-02-22 17:47:20 -08003939 }
3940}
3941
3942void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3943 Mutex::Autolock _l(mUidLock);
3944 auto it = mMonitoredUids.find(uid);
3945 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00003946 it->second.refCount--;
3947 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003948 mMonitoredUids.erase(it);
3949 }
3950 } else {
3951 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3952 }
3953}
3954
Svet Ganov7b4ab782018-03-25 12:48:10 -07003955bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003956 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003957 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003958}
3959
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003960static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3961static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003962
Svet Ganov7b4ab782018-03-25 12:48:10 -07003963bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003964 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003965 // If activity manager is unreachable, assume everything is active
3966 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003967 return true;
3968 }
3969 auto it = mOverrideUids.find(uid);
3970 if (it != mOverrideUids.end()) {
3971 return it->second;
3972 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003973 bool active = mActiveUids.find(uid) != mActiveUids.end();
3974 if (!active) {
3975 // We want active UIDs to always access camera with their first attempt since
3976 // there is no guarantee the app is robustly written and would retry getting
3977 // the camera on failure. The inverse case is not a problem as we would take
3978 // camera away soon once we get the callback that the uid is no longer active.
3979 ActivityManager am;
3980 // Okay to access with a lock held as UID changes are dispatched without
3981 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003982 int64_t startTimeMillis = 0;
3983 do {
3984 // TODO: Fix this b/109950150!
3985 // Okay this is a hack. There is a race between the UID turning active and
3986 // activity being resumed. The proper fix is very risky, so we temporary add
3987 // some polling which should happen pretty rarely anyway as the race is hard
3988 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003989 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003990 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003991 if (active) {
3992 break;
3993 }
3994 if (startTimeMillis <= 0) {
3995 startTimeMillis = uptimeMillis();
3996 }
3997 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003998 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003999 if (remainingTimeMillis <= 0) {
4000 break;
4001 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004002 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4003
4004 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004005 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004006 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004007 } while (true);
4008
Svet Ganov7b4ab782018-03-25 12:48:10 -07004009 if (active) {
4010 // Now that we found out the UID is actually active, cache that
4011 mActiveUids.insert(uid);
4012 }
4013 }
4014 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004015}
4016
Varun Shahb42f1eb2019-04-16 14:45:13 -07004017int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4018 Mutex::Autolock _l(mUidLock);
4019 return getProcStateLocked(uid);
4020}
4021
4022int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4023 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4024 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004025 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004026 }
4027 return procState;
4028}
4029
Svet Ganov7b4ab782018-03-25 12:48:10 -07004030void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
4031 String16 callingPackage, bool active) {
4032 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004033}
4034
Svet Ganov7b4ab782018-03-25 12:48:10 -07004035void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
4036 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004037}
4038
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004039void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4040 Mutex::Autolock _l(mUidLock);
4041 ALOGV("UidPolicy: ActivityManager has died");
4042 mRegistered = false;
4043 mActiveUids.clear();
4044}
4045
Svet Ganov7b4ab782018-03-25 12:48:10 -07004046void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
4047 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004048 bool wasActive = false;
4049 bool isActive = false;
4050 {
4051 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004052 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004053 mOverrideUids.erase(uid);
4054 if (insert) {
4055 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4056 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004057 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004058 }
4059 if (wasActive != isActive && !isActive) {
4060 sp<CameraService> service = mService.promote();
4061 if (service != nullptr) {
4062 service->blockClientsForUid(uid);
4063 }
4064 }
4065}
4066
4067// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004068// SensorPrivacyPolicy
4069// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004070
4071void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4072{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004073 Mutex::Autolock _l(mSensorPrivacyLock);
4074 if (mRegistered) {
4075 return;
4076 }
Evan Severson09ab4002021-02-10 14:15:19 -08004077 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004078 mSpm.addSensorPrivacyListener(this);
4079 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
4080 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004081 if (res == OK) {
4082 mRegistered = true;
4083 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4084 }
4085}
4086
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004087void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4088 const sp<IBinder>&) {
4089 if (name != String16(kSensorPrivacyServiceName)) {
4090 return;
4091 }
4092
4093 registerWithSensorPrivacyManager();
4094}
4095
4096void CameraService::SensorPrivacyPolicy::registerSelf() {
4097 // Use checkservice to see if the sensor_privacy service is available
4098 // If service is not available then register for notification
4099 sp<IServiceManager> sm = defaultServiceManager();
4100 sp<IBinder> binder = sm->checkService(String16(kSensorPrivacyServiceName));
4101 if (!binder) {
4102 sm->registerForNotifications(String16(kSensorPrivacyServiceName),this);
4103 } else {
4104 registerWithSensorPrivacyManager();
4105 }
4106}
4107
Michael Grooverd1d435a2018-12-18 17:39:42 -08004108void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4109 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004110 mSpm.removeSensorPrivacyListener(this);
4111 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004112 mRegistered = false;
4113 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4114}
4115
4116bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004117 if (!mRegistered) {
4118 registerWithSensorPrivacyManager();
4119 }
4120
Michael Grooverd1d435a2018-12-18 17:39:42 -08004121 Mutex::Autolock _l(mSensorPrivacyLock);
4122 return mSensorPrivacyEnabled;
4123}
4124
Evan Seversond0b69922022-01-27 10:47:34 -08004125bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004126 if (!hasCameraPrivacyFeature()) {
4127 return false;
4128 }
Evan Seversond0b69922022-01-27 10:47:34 -08004129 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004130}
4131
Evan Seversond0b69922022-01-27 10:47:34 -08004132binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
4133 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08004134 {
4135 Mutex::Autolock _l(mSensorPrivacyLock);
Kwangkyu Parke3af2992022-11-05 02:46:52 +09004136 mSensorPrivacyEnabled = enabled;
Michael Grooverd1d435a2018-12-18 17:39:42 -08004137 }
4138 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08004139 if (enabled) {
4140 sp<CameraService> service = mService.promote();
4141 if (service != nullptr) {
4142 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004143 }
4144 }
4145 return binder::Status::ok();
4146}
4147
4148void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4149 Mutex::Autolock _l(mSensorPrivacyLock);
4150 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
4151 mRegistered = false;
4152}
4153
Evan Severson09ab4002021-02-10 14:15:19 -08004154bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08004155 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
4156 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4157 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
4158 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4159 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08004160}
4161
Michael Grooverd1d435a2018-12-18 17:39:42 -08004162// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004163// CameraState
4164// ----------------------------------------------------------------------------
4165
4166CameraService::CameraState::CameraState(const String8& id, int cost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004167 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind,
4168 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004169 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004170 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08004171
4172CameraService::CameraState::~CameraState() {}
4173
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004174CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004175 Mutex::Autolock lock(mStatusLock);
4176 return mStatus;
4177}
4178
Shuzhen Wang43858162020-01-10 13:42:15 -08004179std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
4180 Mutex::Autolock lock(mStatusLock);
4181 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
4182 return res;
4183}
4184
Ruben Brunkcc776712015-02-17 20:18:47 -08004185CameraParameters CameraService::CameraState::getShimParams() const {
4186 return mShimParams;
4187}
4188
4189void CameraService::CameraState::setShimParams(const CameraParameters& params) {
4190 mShimParams = params;
4191}
4192
4193int CameraService::CameraState::getCost() const {
4194 return mCost;
4195}
4196
4197std::set<String8> CameraService::CameraState::getConflicting() const {
4198 return mConflicting;
4199}
4200
4201String8 CameraService::CameraState::getId() const {
4202 return mId;
4203}
4204
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004205SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
4206 return mSystemCameraKind;
4207}
4208
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004209bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
4210 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
4211 != mPhysicalCameras.end();
4212}
4213
Shuzhen Wang43858162020-01-10 13:42:15 -08004214bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
4215 Mutex::Autolock lock(mStatusLock);
4216 auto result = mUnavailablePhysicalIds.insert(physicalId);
4217 return result.second;
4218}
4219
4220bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
4221 Mutex::Autolock lock(mStatusLock);
4222 auto count = mUnavailablePhysicalIds.erase(physicalId);
4223 return count > 0;
4224}
4225
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004226void CameraService::CameraState::setClientPackage(const String8& clientPackage) {
4227 Mutex::Autolock lock(mStatusLock);
4228 mClientPackage = clientPackage;
4229}
4230
4231String8 CameraService::CameraState::getClientPackage() const {
4232 Mutex::Autolock lock(mStatusLock);
4233 return mClientPackage;
4234}
4235
Ruben Brunkcc776712015-02-17 20:18:47 -08004236// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07004237// ClientEventListener
4238// ----------------------------------------------------------------------------
4239
4240void CameraService::ClientEventListener::onClientAdded(
4241 const resource_policy::ClientDescriptor<String8,
4242 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004243 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004244 if (basicClient.get() != nullptr) {
4245 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4246 notifier.noteStartCamera(descriptor.getKey(),
4247 static_cast<int>(basicClient->getClientUid()));
4248 }
4249}
4250
4251void CameraService::ClientEventListener::onClientRemoved(
4252 const resource_policy::ClientDescriptor<String8,
4253 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004254 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004255 if (basicClient.get() != nullptr) {
4256 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4257 notifier.noteStopCamera(descriptor.getKey(),
4258 static_cast<int>(basicClient->getClientUid()));
4259 }
4260}
4261
4262
4263// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004264// CameraClientManager
4265// ----------------------------------------------------------------------------
4266
Ruben Brunk99e69712015-05-26 17:25:07 -07004267CameraService::CameraClientManager::CameraClientManager() {
4268 setListener(std::make_shared<ClientEventListener>());
4269}
4270
Ruben Brunkcc776712015-02-17 20:18:47 -08004271CameraService::CameraClientManager::~CameraClientManager() {}
4272
4273sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
4274 const String8& id) const {
4275 auto descriptor = get(id);
4276 if (descriptor == nullptr) {
4277 return sp<BasicClient>{nullptr};
4278 }
4279 return descriptor->getValue();
4280}
4281
4282String8 CameraService::CameraClientManager::toString() const {
4283 auto all = getAll();
4284 String8 ret("[");
4285 bool hasAny = false;
4286 for (auto& i : all) {
4287 hasAny = true;
4288 String8 key = i->getKey();
4289 int32_t cost = i->getCost();
4290 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00004291 int32_t score = i->getPriority().getScore();
4292 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08004293 auto conflicting = i->getConflicting();
4294 auto clientSp = i->getValue();
4295 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07004296 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08004297 if (clientSp.get() != nullptr) {
4298 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07004299 uid_t clientUid = clientSp->getClientUid();
4300 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004301 }
Emilian Peev8131a262017-02-01 12:33:43 +00004302 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
4303 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08004304
Ruben Brunk6267b532015-04-30 17:44:07 -07004305 if (clientSp.get() != nullptr) {
4306 ret.appendFormat("User Id: %d, ", clientUserId);
4307 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004308 if (packageName.size() != 0) {
4309 ret.appendFormat("Client Package Name: %s", packageName.string());
4310 }
4311
4312 ret.append(", Conflicting Client Devices: {");
4313 for (auto& j : conflicting) {
4314 ret.appendFormat("%s, ", j.string());
4315 }
4316 ret.append("})");
4317 }
4318 if (hasAny) ret.append("\n");
4319 ret.append("]\n");
4320 return ret;
4321}
4322
4323CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
4324 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00004325 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004326 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004327
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004328 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
4329 int32_t state_adj = systemNativeClient ? kSystemNativeClientState: state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07004330
Ruben Brunkcc776712015-02-17 20:18:47 -08004331 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004332 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
4333 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08004334}
4335
4336CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004337 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004338 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004339 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00004340 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004341 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
4342 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08004343}
4344
4345// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08004346// InjectionStatusListener
4347// ----------------------------------------------------------------------------
4348
4349void CameraService::InjectionStatusListener::addListener(
4350 const sp<ICameraInjectionCallback>& callback) {
4351 Mutex::Autolock lock(mListenerLock);
4352 if (mCameraInjectionCallback) return;
4353 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
4354 if (res == OK) {
4355 mCameraInjectionCallback = callback;
4356 }
4357}
4358
4359void CameraService::InjectionStatusListener::removeListener() {
4360 Mutex::Autolock lock(mListenerLock);
4361 if (mCameraInjectionCallback == nullptr) {
4362 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4363 return;
4364 }
4365 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
4366 mCameraInjectionCallback = nullptr;
4367}
4368
4369void CameraService::InjectionStatusListener::notifyInjectionError(
Cliff Wud3a05312021-04-26 23:07:31 +08004370 String8 injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08004371 if (mCameraInjectionCallback == nullptr) {
4372 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4373 return;
4374 }
Cliff Wud3a05312021-04-26 23:07:31 +08004375
4376 switch (err) {
4377 case -ENODEV:
4378 mCameraInjectionCallback->onInjectionError(
4379 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4380 ALOGE("No camera device with ID \"%s\" currently available!",
4381 injectedCamId.string());
4382 break;
4383 case -EBUSY:
4384 mCameraInjectionCallback->onInjectionError(
4385 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4386 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
4387 injectedCamId.string());
4388 break;
4389 case DEAD_OBJECT:
4390 mCameraInjectionCallback->onInjectionError(
4391 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4392 ALOGE("Camera ID \"%s\" object is dead!",
4393 injectedCamId.string());
4394 break;
4395 case INVALID_OPERATION:
4396 mCameraInjectionCallback->onInjectionError(
4397 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4398 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
4399 injectedCamId.string());
4400 break;
4401 case UNKNOWN_TRANSACTION:
4402 mCameraInjectionCallback->onInjectionError(
4403 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
4404 ALOGE("Camera ID \"%s\" method doesn't support!",
4405 injectedCamId.string());
4406 break;
4407 default:
4408 mCameraInjectionCallback->onInjectionError(
4409 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
4410 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
4411 strerror(-err), err, injectedCamId.string());
4412 }
Cliff Wud8cae102021-03-11 01:37:42 +08004413}
4414
4415void CameraService::InjectionStatusListener::binderDied(
4416 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08004417 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
4418 auto parent = mParent.promote();
4419 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08004420 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4421 if (clientDescriptor != nullptr) {
4422 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4423 baseClientPtr->stopInjection();
4424 }
Cliff Wu3b268182021-07-06 15:44:43 +08004425 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004426 }
4427}
4428
4429// ----------------------------------------------------------------------------
4430// CameraInjectionSession
4431// ----------------------------------------------------------------------------
4432
4433binder::Status CameraService::CameraInjectionSession::stopInjection() {
4434 Mutex::Autolock lock(mInjectionSessionLock);
4435 auto parent = mParent.promote();
4436 if (parent == nullptr) {
4437 ALOGE("CameraInjectionSession: Parent is gone");
4438 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
4439 "Camera service encountered error");
4440 }
Cliff Wud3a05312021-04-26 23:07:31 +08004441
4442 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08004443 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4444 if (clientDescriptor != nullptr) {
4445 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4446 res = baseClientPtr->stopInjection();
4447 if (res != OK) {
4448 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
4449 " ret != NO_ERROR: %d", res);
4450 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
4451 "Camera session encountered error");
4452 }
4453 }
Cliff Wu3b268182021-07-06 15:44:43 +08004454 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004455 return binder::Status::ok();
4456}
4457
4458// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07004459
4460static const int kDumpLockRetries = 50;
4461static const int kDumpLockSleep = 60000;
4462
4463static bool tryLock(Mutex& mutex)
4464{
4465 bool locked = false;
4466 for (int i = 0; i < kDumpLockRetries; ++i) {
4467 if (mutex.tryLock() == NO_ERROR) {
4468 locked = true;
4469 break;
4470 }
4471 usleep(kDumpLockSleep);
4472 }
4473 return locked;
4474}
4475
Rucha Katakwardf223072021-06-15 10:21:00 -07004476void CameraService::cacheDump() {
4477 if (mMemFd != -1) {
4478 const Vector<String16> args;
4479 ATRACE_CALL();
4480 // Acquiring service lock here will avoid the deadlock since
4481 // cacheDump will not be called during the second disconnect.
4482 Mutex::Autolock lock(mServiceLock);
4483
4484 Mutex::Autolock l(mCameraStatesLock);
4485 // Start collecting the info for open sessions and store it in temp file.
4486 for (const auto& state : mCameraStates) {
4487 String8 cameraId = state.first;
4488 auto clientDescriptor = mActiveClientManager.get(cameraId);
4489 if (clientDescriptor != nullptr) {
4490 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.string());
4491 // Log the current open session info before device is disconnected.
4492 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
4493 }
4494 }
4495 }
4496}
4497
Mathias Agopian65ab4712010-07-14 17:59:35 -07004498status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004499 ATRACE_CALL();
4500
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004501 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004502 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004503 CameraThreadState::getCallingPid(),
4504 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004505 return NO_ERROR;
4506 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004507 bool locked = tryLock(mServiceLock);
4508 // failed to lock - CameraService is probably deadlocked
4509 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004510 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004511 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004512
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004513 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004514 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07004515
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004516 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004517 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08004518
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004519 if (locked) mServiceLock.unlock();
4520 return NO_ERROR;
4521 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004522 dprintf(fd, "\n== Service global info: ==\n\n");
4523 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004524 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07004525 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
4526 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004527 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
4528 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
4529 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004530 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004531 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
4532 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Shuzhen Wang16610a62022-12-15 22:38:07 -08004533 if (mStreamUseCaseOverrides.size() > 0) {
4534 dprintf(fd, "Active stream use case overrides:");
4535 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
4536 dprintf(fd, " %" PRId64, useCaseOverride);
4537 }
4538 dprintf(fd, "\n");
4539 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004540
4541 dumpEventLog(fd);
4542
4543 bool stateLocked = tryLock(mCameraStatesLock);
4544 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004545 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004546 }
4547
Emilian Peevbd8c5032018-02-14 23:05:40 +00004548 int argSize = args.size();
4549 for (int i = 0; i < argSize; i++) {
4550 if (args[i] == TagMonitor::kMonitorOption) {
4551 if (i + 1 < argSize) {
4552 mMonitorTags = String8(args[i + 1]);
4553 }
4554 break;
4555 }
4556 }
4557
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004558 for (auto& state : mCameraStates) {
4559 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004560
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004561 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004562
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004563 CameraParameters p = state.second->getShimParams();
4564 if (!p.isEmpty()) {
4565 dprintf(fd, " Camera1 API shim is using parameters:\n ");
4566 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004567 }
4568
4569 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004570 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004571 // log the current open session info
4572 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004573 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07004574 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004575 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004576
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004577 }
4578
4579 if (stateLocked) mCameraStatesLock.unlock();
4580
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004581 if (locked) mServiceLock.unlock();
4582
Emilian Peevf53f66e2017-04-11 14:29:43 +01004583 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004584
4585 dprintf(fd, "\n== Vendor tags: ==\n\n");
4586
4587 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
4588 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00004589 sp<VendorTagDescriptorCache> cache =
4590 VendorTagDescriptorCache::getGlobalVendorTagCache();
4591 if (cache == NULL) {
4592 dprintf(fd, "No vendor tags.\n");
4593 } else {
4594 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
4595 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004596 } else {
4597 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
4598 }
4599
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004600 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004601 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004602 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004603
4604 // Process dump arguments, if any
4605 int n = args.size();
4606 String16 verboseOption("-v");
4607 String16 unreachableOption("--unreachable");
4608 for (int i = 0; i < n; i++) {
4609 if (args[i] == verboseOption) {
4610 // change logging level
4611 if (i + 1 >= n) continue;
4612 String8 levelStr(args[i+1]);
4613 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004614 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004615 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004616 } else if (args[i] == unreachableOption) {
4617 // Dump memory analysis
4618 // TODO - should limit be an argument parameter?
4619 UnreachableMemoryInfo info;
4620 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
4621 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004622 dprintf(fd, "\n== Unable to dump unreachable memory. "
4623 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004624 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004625 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004626 std::string s = info.ToString(/*log_contents*/ true);
4627 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004628 }
4629 }
4630 }
Rucha Katakwardf223072021-06-15 10:21:00 -07004631
4632 bool serviceLocked = tryLock(mServiceLock);
4633
4634 // Dump info from previous open sessions.
4635 // Reposition the offset to beginning of the file before reading
4636
4637 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
4638 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
4639 ssize_t size_read;
4640 char buf[4096];
4641 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
4642 // Read data from file to a small buffer and write it to fd.
4643 write(fd, buf, size_read);
4644 if (size_read == -1) {
4645 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4646 break;
4647 }
4648 }
4649 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
4650 } else {
4651 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4652 }
4653
4654 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004655 return NO_ERROR;
4656}
4657
Rucha Katakwardf223072021-06-15 10:21:00 -07004658void CameraService::dumpOpenSessionClientLogs(int fd,
4659 const Vector<String16>& args, const String8& cameraId) {
4660 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07004661 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
4662 getFormattedCurrentTime().string(),
4663 cameraId.string());
Rucha Katakwardf223072021-06-15 10:21:00 -07004664 dprintf(fd, " Client priority score: %d state: %d\n",
4665 clientDescriptor->getPriority().getScore(),
4666 clientDescriptor->getPriority().getState());
4667 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
4668
4669 auto client = clientDescriptor->getValue();
4670 dprintf(fd, " Client package: %s\n",
4671 String8(client->getPackageName()).string());
4672
4673 client->dumpClient(fd, args);
4674}
4675
4676void CameraService::dumpClosedSessionClientLogs(int fd, const String8& cameraId) {
4677 dprintf(fd, " Device %s is closed, no client instance\n",
4678 cameraId.string());
4679}
4680
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004681void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004682 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004683
4684 Mutex::Autolock l(mLogLock);
4685 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004686 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004687 }
4688
4689 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004690 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004691 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004692 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004693 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004694 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004695}
4696
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004697void CameraService::cacheClientTagDumpIfNeeded(const char *cameraId, BasicClient* client) {
4698 Mutex::Autolock lock(mLogLock);
4699 if (!isClientWatchedLocked(client)) { return; }
4700
4701 std::vector<std::string> dumpVector;
4702 client->dumpWatchedEventsToVector(dumpVector);
4703
4704 if (dumpVector.empty()) { return; }
4705
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004706 std::string dumpString;
4707
4708 String8 currentTime = getFormattedCurrentTime();
4709 dumpString += "Cached @ ";
4710 dumpString += currentTime.string();
4711 dumpString += "\n"; // First line is the timestamp of when client is cached.
4712
4713
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004714 const String16 &packageName = client->getPackageName();
4715
4716 String8 packageName8 = String8(packageName);
4717 const char *printablePackageName = packageName8.lockBuffer(packageName.size());
4718
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004719
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004720 size_t i = dumpVector.size();
4721
4722 // Store the string in reverse order (latest last)
4723 while (i > 0) {
4724 i--;
4725 dumpString += cameraId;
4726 dumpString += ":";
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004727 dumpString += printablePackageName;
4728 dumpString += " ";
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004729 dumpString += dumpVector[i]; // implicitly ends with '\n'
4730 }
4731
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004732 packageName8.unlockBuffer();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004733 mWatchedClientsDumpCache[packageName] = dumpString;
4734}
4735
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004736void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004737 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004738 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
4739 if (mTorchClientMap[i] == who) {
4740 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004741 String8 cameraId = mTorchClientMap.keyAt(i);
4742 status_t res = mFlashlight->setTorchMode(cameraId, false);
4743 if (res) {
4744 ALOGE("%s: torch client died but couldn't turn off torch: "
4745 "%s (%d)", __FUNCTION__, strerror(-res), res);
4746 return;
4747 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004748 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004749 break;
4750 }
4751 }
4752}
4753
Ruben Brunkcc776712015-02-17 20:18:47 -08004754/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07004755
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004756 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07004757 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
4758 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004759 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08004760 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004761 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004762
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004763 // check torch client
4764 handleTorchClientBinderDied(who);
4765
4766 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08004767 if(!evictClientIdByRemote(who)) {
4768 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004769 return;
4770 }
4771
Ruben Brunkcc776712015-02-17 20:18:47 -08004772 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
4773 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004774}
4775
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004776void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004777 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08004778}
4779
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004780void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
4781 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004782 // Do not lock mServiceLock here or can get into a deadlock from
4783 // connect() -> disconnect -> updateStatus
4784
4785 auto state = getCameraState(cameraId);
4786
4787 if (state == nullptr) {
4788 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4789 cameraId.string());
4790 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07004791 }
4792
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004793 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
4794 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
4795 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
4796 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
4797 return;
4798 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004799
4800 // Collect the logical cameras without holding mStatusLock in updateStatus
4801 // as that can lead to a deadlock(b/162192331).
4802 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08004803 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08004804 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07004805 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004806 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004807 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004808
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004809 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004810 // Update torch status if it has a flash unit.
4811 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004812 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004813 if (getTorchStatusLocked(cameraId, &torchStatus) !=
4814 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004815 TorchModeStatus newTorchStatus =
4816 status == StatusInternal::PRESENT ?
4817 TorchModeStatus::AVAILABLE_OFF :
4818 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004819 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07004820 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004821 }
4822 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004823 }
4824
4825 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004826 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
4827 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08004828
Ruben Brunkcc776712015-02-17 20:18:47 -08004829 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07004830 bool isVendorListener = listener->isVendorListener();
4831 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
4832 listener->getListenerPid(), listener->getListenerUid()) ||
Shuzhen Wangb8259792021-05-27 09:27:06 -07004833 isVendorListener) {
4834 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004835 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08004836 continue;
4837 }
Austin Borgere8e2c422022-05-12 13:45:24 -07004838 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08004839 String16(cameraId));
Austin Borgere8e2c422022-05-12 13:45:24 -07004840 listener->handleBinderStatus(ret,
4841 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
4842 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
4843 ret.exceptionCode());
Ruben Brunkcc776712015-02-17 20:18:47 -08004844 }
4845 });
Igor Murashkincba2c162013-03-20 15:56:31 -07004846}
4847
Shuzhen Wang695044d2020-03-06 09:02:23 -08004848void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
4849 const String16& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004850 auto state = getCameraState(cameraId);
4851 if (state == nullptr) {
4852 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4853 cameraId.string());
4854 return;
4855 }
4856 if (open) {
4857 state->setClientPackage(String8(clientPackageName));
4858 } else {
4859 state->setClientPackage(String8::empty());
4860 }
4861
Shuzhen Wang695044d2020-03-06 09:02:23 -08004862 Mutex::Autolock lock(mStatusListenerLock);
4863
4864 for (const auto& it : mListenerList) {
4865 if (!it->isOpenCloseCallbackAllowed()) {
4866 continue;
4867 }
4868
4869 binder::Status ret;
4870 String16 cameraId64(cameraId);
4871 if (open) {
4872 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
4873 } else {
4874 ret = it->getListener()->onCameraClosed(cameraId64);
4875 }
Austin Borgere8e2c422022-05-12 13:45:24 -07004876
4877 it->handleBinderStatus(ret,
4878 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
4879 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08004880 }
4881}
4882
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004883template<class Func>
4884void CameraService::CameraState::updateStatus(StatusInternal status,
4885 const String8& cameraId,
4886 std::initializer_list<StatusInternal> rejectSourceStates,
4887 Func onStatusUpdatedLocked) {
4888 Mutex::Autolock lock(mStatusLock);
4889 StatusInternal oldStatus = mStatus;
4890 mStatus = status;
4891
4892 if (oldStatus == status) {
4893 return;
4894 }
4895
4896 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
4897 cameraId.string(), oldStatus, status);
4898
4899 if (oldStatus == StatusInternal::NOT_PRESENT &&
4900 (status != StatusInternal::PRESENT &&
4901 status != StatusInternal::ENUMERATING)) {
4902
4903 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
4904 __FUNCTION__);
4905 mStatus = oldStatus;
4906 return;
4907 }
4908
4909 /**
4910 * Sometimes we want to conditionally do a transition.
4911 * For example if a client disconnects, we want to go to PRESENT
4912 * only if we weren't already in NOT_PRESENT or ENUMERATING.
4913 */
4914 for (auto& rejectStatus : rejectSourceStates) {
4915 if (oldStatus == rejectStatus) {
4916 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
4917 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
4918 mStatus = oldStatus;
4919 return;
4920 }
4921 }
4922
4923 onStatusUpdatedLocked(cameraId, status);
4924}
4925
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004926status_t CameraService::getTorchStatusLocked(
4927 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004928 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004929 if (!status) {
4930 return BAD_VALUE;
4931 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004932 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4933 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004934 // invalid camera ID or the camera doesn't have a flash unit
4935 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004936 }
4937
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004938 *status = mTorchStatusMap.valueAt(index);
4939 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004940}
4941
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004942status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004943 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004944 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4945 if (index == NAME_NOT_FOUND) {
4946 return BAD_VALUE;
4947 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004948 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004949
4950 return OK;
4951}
4952
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004953std::list<String16> CameraService::getLogicalCameras(
4954 const String8& physicalCameraId) {
4955 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08004956 Mutex::Autolock lock(mCameraStatesLock);
4957 for (const auto& state : mCameraStates) {
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004958 if (state.second->containsPhysicalCamera(physicalCameraId.c_str())) {
4959 retList.emplace_back(String16(state.first));
Shuzhen Wang43858162020-01-10 13:42:15 -08004960 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004961 }
4962 return retList;
4963}
4964
4965void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
4966 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
4967 SystemCameraKind deviceKind) {
4968 // mStatusListenerLock is expected to be locked
4969 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004970 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004971 // Note: we check only the deviceKind of the physical camera id
4972 // since, logical camera ids and their physical camera ids are
4973 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004974 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
4975 listener->getListenerPid(), listener->getListenerUid())) {
4976 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004977 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004978 continue;
4979 }
Austin Borgere8e2c422022-05-12 13:45:24 -07004980 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004981 logicalCameraId, physicalCameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07004982 listener->handleBinderStatus(ret,
4983 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
4984 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
4985 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08004986 }
4987 }
4988}
4989
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004990
Svet Ganova453d0d2018-01-11 15:37:58 -08004991void CameraService::blockClientsForUid(uid_t uid) {
4992 const auto clients = mActiveClientManager.getAll();
4993 for (auto& current : clients) {
4994 if (current != nullptr) {
4995 const auto basicClient = current->getValue();
4996 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
4997 basicClient->block();
4998 }
4999 }
5000 }
5001}
5002
Michael Grooverd1d435a2018-12-18 17:39:42 -08005003void CameraService::blockAllClients() {
5004 const auto clients = mActiveClientManager.getAll();
5005 for (auto& current : clients) {
5006 if (current != nullptr) {
5007 const auto basicClient = current->getValue();
5008 if (basicClient.get() != nullptr) {
5009 basicClient->block();
5010 }
5011 }
5012 }
5013}
5014
Svet Ganova453d0d2018-01-11 15:37:58 -08005015// NOTE: This is a remote API - make sure all args are validated
5016status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
5017 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
5018 return PERMISSION_DENIED;
5019 }
5020 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5021 return BAD_VALUE;
5022 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005023 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005024 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07005025 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005026 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07005027 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005028 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005029 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
5030 return handleSetRotateAndCrop(args);
5031 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
5032 return handleGetRotateAndCrop(out);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005033 } else if (args.size() >= 2 && args[0] == String16("set-autoframing")) {
5034 return handleSetAutoframing(args);
5035 } else if (args.size() >= 1 && args[0] == String16("get-autoframing")) {
5036 return handleGetAutoframing(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005037 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
5038 return handleSetImageDumpMask(args);
5039 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
5040 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005041 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
5042 return handleSetCameraMute(args);
Shuzhen Wang16610a62022-12-15 22:38:07 -08005043 } else if (args.size() >= 2 && args[0] == String16("set-stream-use-case-override")) {
5044 return handleSetStreamUseCaseOverrides(args);
5045 } else if (args.size() >= 1 && args[0] == String16("clear-stream-use-case-override")) {
5046 handleClearStreamUseCaseOverrides();
5047 return OK;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005048 } else if (args.size() >= 2 && args[0] == String16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005049 return handleWatchCommand(args, in, out);
Ravneetaeb20dc2022-03-30 05:33:03 +00005050 } else if (args.size() >= 2 && args[0] == String16("set-watchdog")) {
5051 return handleSetCameraServiceWatchdog(args);
Svet Ganova453d0d2018-01-11 15:37:58 -08005052 } else if (args.size() == 1 && args[0] == String16("help")) {
5053 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005054 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005055 }
5056 printHelp(err);
5057 return BAD_VALUE;
5058}
5059
5060status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07005061 String16 packageName = args[1];
5062
Svet Ganova453d0d2018-01-11 15:37:58 -08005063 bool active = false;
5064 if (args[2] == String16("active")) {
5065 active = true;
5066 } else if ((args[2] != String16("idle"))) {
5067 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
5068 return BAD_VALUE;
5069 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005070
5071 int userId = 0;
5072 if (args.size() >= 5 && args[3] == String16("--user")) {
5073 userId = atoi(String8(args[4]));
5074 }
5075
5076 uid_t uid;
5077 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5078 return BAD_VALUE;
5079 }
5080
5081 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005082 return NO_ERROR;
5083}
5084
5085status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07005086 String16 packageName = args[1];
5087
5088 int userId = 0;
5089 if (args.size() >= 4 && args[2] == String16("--user")) {
5090 userId = atoi(String8(args[3]));
5091 }
5092
5093 uid_t uid;
5094 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005095 return BAD_VALUE;
5096 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005097
5098 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005099 return NO_ERROR;
5100}
5101
5102status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07005103 String16 packageName = args[1];
5104
5105 int userId = 0;
5106 if (args.size() >= 4 && args[2] == String16("--user")) {
5107 userId = atoi(String8(args[3]));
5108 }
5109
5110 uid_t uid;
5111 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005112 return BAD_VALUE;
5113 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005114
5115 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005116 return dprintf(out, "active\n");
5117 } else {
5118 return dprintf(out, "idle\n");
5119 }
5120}
5121
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005122status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
5123 int rotateValue = atoi(String8(args[1]));
5124 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
5125 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
5126 Mutex::Autolock lock(mServiceLock);
5127
5128 mOverrideRotateAndCropMode = rotateValue;
5129
5130 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
5131
5132 const auto clients = mActiveClientManager.getAll();
5133 for (auto& current : clients) {
5134 if (current != nullptr) {
5135 const auto basicClient = current->getValue();
5136 if (basicClient.get() != nullptr) {
5137 basicClient->setRotateAndCropOverride(rotateValue);
5138 }
5139 }
5140 }
5141
5142 return OK;
5143}
5144
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005145status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
5146 char* end;
5147 int autoframingValue = (int) strtol(String8(args[1]), &end, /*base=*/10);
5148 if ((*end != '\0') ||
5149 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
5150 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
5151 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
5152 return BAD_VALUE;
5153 }
5154
5155 Mutex::Autolock lock(mServiceLock);
5156 mOverrideAutoframingMode = autoframingValue;
5157
5158 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
5159
5160 const auto clients = mActiveClientManager.getAll();
5161 for (auto& current : clients) {
5162 if (current != nullptr) {
5163 const auto basicClient = current->getValue();
5164 if (basicClient.get() != nullptr) {
5165 basicClient->setAutoframingOverride(autoframingValue);
5166 }
5167 }
5168 }
5169
5170 return OK;
5171}
5172
Ravneetaeb20dc2022-03-30 05:33:03 +00005173status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
5174 int enableWatchdog = atoi(String8(args[1]));
5175
5176 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
5177
5178 Mutex::Autolock lock(mServiceLock);
5179
5180 mCameraServiceWatchdogEnabled = enableWatchdog;
5181
5182 const auto clients = mActiveClientManager.getAll();
5183 for (auto& current : clients) {
5184 if (current != nullptr) {
5185 const auto basicClient = current->getValue();
5186 if (basicClient.get() != nullptr) {
5187 basicClient->setCameraServiceWatchdog(enableWatchdog);
5188 }
5189 }
5190 }
5191
5192 return OK;
5193}
5194
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005195status_t CameraService::handleGetRotateAndCrop(int out) {
5196 Mutex::Autolock lock(mServiceLock);
5197
5198 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
5199}
5200
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005201status_t CameraService::handleGetAutoframing(int out) {
5202 Mutex::Autolock lock(mServiceLock);
5203
5204 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
5205}
5206
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005207status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
5208 char *endPtr;
5209 errno = 0;
5210 String8 maskString8 = String8(args[1]);
5211 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
5212
5213 if (errno != 0) return BAD_VALUE;
5214 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
5215 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
5216
5217 Mutex::Autolock lock(mServiceLock);
5218
5219 mImageDumpMask = maskValue;
5220
5221 return OK;
5222}
5223
5224status_t CameraService::handleGetImageDumpMask(int out) {
5225 Mutex::Autolock lock(mServiceLock);
5226
5227 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
5228}
5229
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005230status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
5231 int muteValue = strtol(String8(args[1]), nullptr, 10);
5232 if (errno != 0) return BAD_VALUE;
5233
5234 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
5235 Mutex::Autolock lock(mServiceLock);
5236
5237 mOverrideCameraMuteMode = (muteValue == 1);
5238
5239 const auto clients = mActiveClientManager.getAll();
5240 for (auto& current : clients) {
5241 if (current != nullptr) {
5242 const auto basicClient = current->getValue();
5243 if (basicClient.get() != nullptr) {
5244 if (basicClient->supportsCameraMute()) {
5245 basicClient->setCameraMute(mOverrideCameraMuteMode);
5246 }
5247 }
5248 }
5249 }
5250
5251 return OK;
5252}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005253
Shuzhen Wang16610a62022-12-15 22:38:07 -08005254status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
5255 std::vector<int64_t> useCasesOverride;
5256 for (size_t i = 1; i < args.size(); i++) {
5257 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
5258 String8 arg8 = String8(args[i]);
5259 if (arg8 == "DEFAULT") {
5260 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
5261 } else if (arg8 == "PREVIEW") {
5262 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
5263 } else if (arg8 == "STILL_CAPTURE") {
5264 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
5265 } else if (arg8 == "VIDEO_RECORD") {
5266 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
5267 } else if (arg8 == "PREVIEW_VIDEO_STILL") {
5268 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
5269 } else if (arg8 == "VIDEO_CALL") {
5270 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
5271 } else if (arg8 == "CROPPED_RAW") {
5272 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
5273 } else {
5274 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg8.c_str());
5275 return BAD_VALUE;
5276 }
5277 useCasesOverride.push_back(useCase);
5278 }
5279
5280 Mutex::Autolock lock(mServiceLock);
5281 mStreamUseCaseOverrides = std::move(useCasesOverride);
5282
5283 return OK;
5284}
5285
5286void CameraService::handleClearStreamUseCaseOverrides() {
5287 Mutex::Autolock lock(mServiceLock);
5288 mStreamUseCaseOverrides.clear();
5289}
5290
Avichal Rakesh84147132021-11-11 17:47:11 -08005291status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005292 if (args.size() >= 3 && args[1] == String16("start")) {
5293 return startWatchingTags(args, outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005294 } else if (args.size() == 2 && args[1] == String16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005295 return stopWatchingTags(outFd);
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005296 } else if (args.size() == 2 && args[1] == String16("dump")) {
5297 return printWatchedTags(outFd);
5298 } else if (args.size() >= 2 && args[1] == String16("live")) {
5299 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005300 } else if (args.size() == 2 && args[1] == String16("clear")) {
5301 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005302 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005303 dprintf(outFd, "Camera service watch commands:\n"
5304 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
5305 " starts watching the provided tags for clients with provided package\n"
5306 " recognizes tag shorthands like '3a'\n"
5307 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005308 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005309 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005310 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005311 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08005312 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005313 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005314 return BAD_VALUE;
5315}
5316
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005317status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
5318 Mutex::Autolock lock(mLogLock);
5319 size_t tagsIdx; // index of '-m'
5320 String16 tags("");
5321 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != String16("-m"); tagsIdx++);
5322 if (tagsIdx < args.size() - 1) {
5323 tags = args[tagsIdx + 1];
5324 } else {
5325 dprintf(outFd, "No tags provided.\n");
5326 return BAD_VALUE;
5327 }
5328
5329 size_t clientsIdx; // index of '-c'
5330 String16 clients = kWatchAllClientsFlag; // watch all clients if no clients are provided
5331 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != String16("-c");
5332 clientsIdx++);
5333 if (clientsIdx < args.size() - 1) {
5334 clients = args[clientsIdx + 1];
5335 }
5336 parseClientsToWatchLocked(String8(clients));
5337
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005338 // track tags to initialize future clients with the monitoring information
5339 mMonitorTags = String8(tags);
5340
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005341 bool serviceLock = tryLock(mServiceLock);
5342 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005343 auto cameraClients = mActiveClientManager.getAll();
5344 for (const auto &clientDescriptor: cameraClients) {
5345 if (clientDescriptor == nullptr) { continue; }
5346 sp<BasicClient> client = clientDescriptor->getValue();
5347 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005348
5349 if (isClientWatchedLocked(client.get())) {
5350 client->startWatchingTags(mMonitorTags, outFd);
5351 numWatchedClients++;
5352 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005353 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005354 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
5355
5356 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005357 return OK;
5358}
5359
5360status_t CameraService::stopWatchingTags(int outFd) {
5361 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005362 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005363 mMonitorTags = String8::empty();
5364
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005365 mWatchedClientPackages.clear();
5366 mWatchedClientsDumpCache.clear();
5367
5368 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005369 auto cameraClients = mActiveClientManager.getAll();
5370 for (const auto &clientDescriptor : cameraClients) {
5371 if (clientDescriptor == nullptr) { continue; }
5372 sp<BasicClient> client = clientDescriptor->getValue();
5373 if (client.get() == nullptr) { continue; }
5374 client->stopWatchingTags(outFd);
5375 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005376 dprintf(outFd, "Stopped watching all clients.\n");
5377 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005378 return OK;
5379}
5380
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005381status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
5382 Mutex::Autolock lock(mLogLock);
5383 size_t clearedSize = mWatchedClientsDumpCache.size();
5384 mWatchedClientsDumpCache.clear();
5385 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
5386 return OK;
5387}
5388
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005389status_t CameraService::printWatchedTags(int outFd) {
5390 Mutex::Autolock logLock(mLogLock);
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08005391 std::set<String16> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005392
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005393 bool printedSomething = false; // tracks if any monitoring information was printed
5394 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005395
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005396 bool serviceLock = tryLock(mServiceLock);
5397 // get all watched clients that are currently connected
5398 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
5399 if (clientDescriptor == nullptr) { continue; }
5400
5401 sp<BasicClient> client = clientDescriptor->getValue();
5402 if (client.get() == nullptr) { continue; }
5403 if (!isClientWatchedLocked(client.get())) { continue; }
5404
5405 std::vector<std::string> dumpVector;
5406 client->dumpWatchedEventsToVector(dumpVector);
5407
5408 size_t printIdx = dumpVector.size();
5409 if (printIdx == 0) {
5410 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005411 }
5412
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005413 // Print tag dumps for active client
5414 const String8 &cameraId = clientDescriptor->getKey();
5415 String8 packageName8 = String8(client->getPackageName());
5416 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
5417 dprintf(outFd, "Client: %s (active)\n", printablePackageName);
5418 while(printIdx > 0) {
5419 printIdx--;
5420 dprintf(outFd, "%s:%s %s", cameraId.string(), printablePackageName,
5421 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005422 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005423 dprintf(outFd, "\n");
5424 packageName8.unlockBuffer();
5425 printedSomething = true;
5426
5427 connectedMonitoredClients.emplace(client->getPackageName());
5428 }
5429 if (serviceLock) { mServiceLock.unlock(); }
5430
5431 // Print entries in mWatchedClientsDumpCache for clients that are not connected
5432 for (const auto &kv: mWatchedClientsDumpCache) {
5433 const String16 &package = kv.first;
5434 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
5435 continue;
5436 }
5437
5438 dprintf(outFd, "Client: %s (cached)\n", String8(package).string());
5439 dprintf(outFd, "%s\n", kv.second.c_str());
5440 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005441 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005442
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005443 if (!printedSomething) {
5444 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005445 }
5446
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005447 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005448}
5449
Avichal Rakesh84147132021-11-11 17:47:11 -08005450// Print all events in vector `events' that came after lastPrintedEvent
5451void printNewWatchedEvents(int outFd,
5452 const char *cameraId,
5453 const String16 &packageName,
5454 const std::vector<std::string> &events,
5455 const std::string &lastPrintedEvent) {
5456 if (events.empty()) { return; }
5457
5458 // index of lastPrintedEvent in events.
5459 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
5460 size_t lastPrintedIdx;
5461 for (lastPrintedIdx = 0;
5462 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
5463 lastPrintedIdx++);
5464
5465 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
5466
5467 String8 packageName8(packageName);
5468 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
5469
5470 // print events in chronological order (latest event last)
5471 size_t idxToPrint = lastPrintedIdx;
5472 do {
5473 idxToPrint--;
5474 dprintf(outFd, "%s:%s %s", cameraId, printablePackageName, events[idxToPrint].c_str());
5475 } while (idxToPrint != 0);
5476
5477 packageName8.unlockBuffer();
5478}
5479
5480// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
5481// command should be interrupted if the user presses the return key, or if user loses any way to
5482// signal interrupt.
5483// If timeoutMs == 0, this function will always return false
5484bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
5485 struct timeval startTime;
5486 int startTimeError = gettimeofday(&startTime, nullptr);
5487 if (startTimeError) {
5488 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5489 return true;
5490 }
5491
5492 const nfds_t numFds = 1;
5493 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
5494
5495 struct timeval currTime;
5496 char buffer[2];
5497 while(true) {
5498 int currTimeError = gettimeofday(&currTime, nullptr);
5499 if (currTimeError) {
5500 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5501 return true;
5502 }
5503
5504 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
5505 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
5506 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
5507
5508 if (remainingTimeMs <= 0) {
5509 // No user interrupt within timeoutMs, don't interrupt watch command
5510 return false;
5511 }
5512
5513 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
5514 if (numFdsUpdated < 0) {
5515 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5516 return true;
5517 }
5518
5519 if (numFdsUpdated == 0) {
5520 // No user input within timeoutMs, don't interrupt watch command
5521 return false;
5522 }
5523
5524 if (!(pollFd.revents & POLLIN)) {
5525 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5526 return true;
5527 }
5528
5529 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
5530 if (sizeRead < 0) {
5531 dprintf(outFd, "Error reading user input. Exiting.\n");
5532 return true;
5533 }
5534
5535 if (sizeRead == 0) {
5536 // Reached end of input fd (can happen if input is piped)
5537 // User has no way to signal an interrupt, so interrupt here
5538 return true;
5539 }
5540
5541 if (buffer[0] == '\n') {
5542 // User pressed return, interrupt watch command.
5543 return true;
5544 }
5545 }
5546}
5547
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005548status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
5549 int inFd, int outFd) {
5550 // Figure out refresh interval, if present in args
5551 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005552 if (args.size() > 2) {
5553 size_t intervalIdx; // index of '-n'
5554 for (intervalIdx = 2; intervalIdx < args.size() && String16("-n") != args[intervalIdx];
5555 intervalIdx++);
5556
5557 size_t intervalValIdx = intervalIdx + 1;
5558 if (intervalValIdx < args.size()) {
5559 refreshTimeoutMs = strtol(String8(args[intervalValIdx].string()), nullptr, 10);
5560 if (errno) { return BAD_VALUE; }
5561 }
5562 }
5563
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005564 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
5565 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005566
Avichal Rakesh84147132021-11-11 17:47:11 -08005567 dprintf(outFd, "Press return to exit...\n\n");
Avichal Rakesha14d9832021-11-11 01:41:55 -08005568 std::map<String16, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005569
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005570 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005571 bool serviceLock = tryLock(mServiceLock);
5572 auto cameraClients = mActiveClientManager.getAll();
5573 if (serviceLock) { mServiceLock.unlock(); }
5574
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005575 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005576 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005577 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005578
5579 sp<BasicClient> client = clientDescriptor->getValue();
5580 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005581 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005582
Avichal Rakesha14d9832021-11-11 01:41:55 -08005583 const String16 &packageName = client->getPackageName();
5584 // This also initializes the map entries with an empty string
5585 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
5586
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005587 std::vector<std::string> latestEvents;
5588 client->dumpWatchedEventsToVector(latestEvents);
5589
5590 if (!latestEvents.empty()) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005591 String8 cameraId = clientDescriptor->getKey();
5592 const char *printableCameraId = cameraId.lockBuffer(cameraId.size());
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005593 printNewWatchedEvents(outFd,
Avichal Rakesha14d9832021-11-11 01:41:55 -08005594 printableCameraId,
5595 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005596 latestEvents,
5597 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08005598 packageNameToLastEvent[packageName] = latestEvents[0];
5599 cameraId.unlockBuffer();
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005600 }
5601 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005602 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005603 break;
5604 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005605 }
5606 return OK;
5607}
5608
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005609void CameraService::parseClientsToWatchLocked(String8 clients) {
5610 mWatchedClientPackages.clear();
5611
5612 const char *allSentinel = String8(kWatchAllClientsFlag).string();
5613
5614 char *tokenized = clients.lockBuffer(clients.size());
5615 char *savePtr;
5616 char *nextClient = strtok_r(tokenized, ",", &savePtr);
5617
5618 while (nextClient != nullptr) {
5619 if (strcmp(nextClient, allSentinel) == 0) {
5620 // Don't need to track any other package if 'all' is present
5621 mWatchedClientPackages.clear();
5622 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
5623 break;
5624 }
5625
5626 // track package names
5627 mWatchedClientPackages.emplace(nextClient);
5628 nextClient = strtok_r(nullptr, ",", &savePtr);
5629 }
5630 clients.unlockBuffer();
5631}
5632
Svet Ganova453d0d2018-01-11 15:37:58 -08005633status_t CameraService::printHelp(int out) {
5634 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07005635 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
5636 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
5637 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005638 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
5639 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
5640 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005641 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
5642 " Valid values 0=false, 1=true, 2=auto\n"
5643 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005644 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
5645 " Valid values 0=OFF, 1=ON for JPEG\n"
5646 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005647 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08005648 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
5649 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
5650 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
5651 " on. In case the number of usecases is smaller than the number of streams, the\n"
5652 " last use case is assigned to all the remaining streams. In case of multiple\n"
5653 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
5654 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
5655 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
5656 " clear-stream-use-case-override clear the stream use case override\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005657 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08005658 " help print this message\n");
5659}
5660
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005661bool CameraService::isClientWatched(const BasicClient *client) {
5662 Mutex::Autolock lock(mLogLock);
5663 return isClientWatchedLocked(client);
5664}
5665
5666bool CameraService::isClientWatchedLocked(const BasicClient *client) {
5667 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
5668 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
5669}
5670
Yin-Chia Yehdba03232019-08-19 15:54:28 -07005671int32_t CameraService::updateAudioRestriction() {
5672 Mutex::Autolock lock(mServiceLock);
5673 return updateAudioRestrictionLocked();
5674}
5675
5676int32_t CameraService::updateAudioRestrictionLocked() {
5677 int32_t mode = 0;
5678 // iterate through all active client
5679 for (const auto& i : mActiveClientManager.getAll()) {
5680 const auto clientSp = i->getValue();
5681 mode |= clientSp->getAudioRestriction();
5682 }
5683
5684 bool modeChanged = (mAudioRestriction != mode);
5685 mAudioRestriction = mode;
5686 if (modeChanged) {
5687 mAppOps.setCameraAudioRestriction(mode);
5688 }
5689 return mode;
5690}
5691
Cliff Wu646bd612021-11-23 23:21:29 +08005692status_t CameraService::checkIfInjectionCameraIsPresent(const String8& externalCamId,
5693 sp<BasicClient> clientSp) {
5694 std::unique_ptr<AutoConditionLock> lock =
5695 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
5696 status_t res = NO_ERROR;
5697 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
5698 ALOGW("Device %s is not usable!", externalCamId.string());
5699 mInjectionStatusListener->notifyInjectionError(
5700 externalCamId, UNKNOWN_TRANSACTION);
5701 clientSp->notifyError(
5702 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
5703 CaptureResultExtras());
5704
5705 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
5706 // other clients from connecting in mServiceLockWrapper if held
5707 mServiceLock.unlock();
5708
5709 // Clear caller identity temporarily so client disconnect PID checks work correctly
5710 int64_t token = CameraThreadState::clearCallingIdentity();
5711 clientSp->disconnect();
5712 CameraThreadState::restoreCallingIdentity(token);
5713
5714 // Reacquire mServiceLock
5715 mServiceLock.lock();
5716 }
5717
5718 return res;
5719}
5720
Cliff Wud3a05312021-04-26 23:07:31 +08005721void CameraService::clearInjectionParameters() {
5722 {
5723 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08005724 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08005725 mInjectionInternalCamId = "";
5726 }
5727 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08005728 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08005729}
5730
Mathias Agopian65ab4712010-07-14 17:59:35 -07005731}; // namespace android