blob: 5eb068fdc5475c6da6a38d06cb71ba0758901981 [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
Charles Chena7b613c2023-01-24 21:57:33 +0000173// Enable processes with isolated AID to request the binder
174void CameraService::instantiate() {
175 CameraService::publish(true);
176}
177
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800178void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
179 if (name != String16(kAppopsServiceName)) {
180 return;
181 }
182
183 ALOGV("appops service registered. setting camera audio restriction");
184 mAppOps.setCameraAudioRestriction(mAudioRestriction);
185}
186
Iliyan Malchev8951a972011-04-14 16:55:59 -0700187void CameraService::onFirstRef()
188{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700189
Ruben Brunkcc776712015-02-17 20:18:47 -0800190 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800191
Iliyan Malchev8951a972011-04-14 16:55:59 -0700192 BnCameraService::onFirstRef();
193
Ruben Brunk99e69712015-05-26 17:25:07 -0700194 // Update battery life tracking if service is restarting
195 BatteryNotifier& notifier(BatteryNotifier::getInstance());
196 notifier.noteResetCamera();
197 notifier.noteResetFlashlight();
198
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800199 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800200
Emilian Peevf53f66e2017-04-11 14:29:43 +0100201 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800202 if (res == OK) {
203 mInitialized = true;
204 }
205
Svet Ganova453d0d2018-01-11 15:37:58 -0800206 mUidPolicy = new UidPolicy(this);
207 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800208 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
209 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800210 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800211
212 // appops function setCamerAudioRestriction uses getService which
213 // is blocking till the appops service is ready. To enable early
214 // boot availability for cameraservice, use checkService which is
215 // non blocking and register for notifications
216 sp<IServiceManager> sm = defaultServiceManager();
217 sp<IBinder> binder = sm->checkService(String16(kAppopsServiceName));
218 if (!binder) {
219 sm->registerForNotifications(String16(kAppopsServiceName), this);
220 } else {
221 mAppOps.setCameraAudioRestriction(mAudioRestriction);
222 }
223
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700224 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
225 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000226 // Deprecated, so it will fail to register on newer devices
227 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700228 __FUNCTION__);
229 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700230
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700231 if (!AidlCameraService::registerService(this)) {
232 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
233 }
234
Shuzhen Wang24b44152019-09-20 10:38:11 -0700235 // This needs to be last call in this function, so that it's as close to
236 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700237 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700238 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800239}
240
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800241status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800242 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100243
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800244 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000245 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800246 {
247 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800248
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800249 if (nullptr == mCameraProviderManager.get()) {
250 mCameraProviderManager = new CameraProviderManager();
251 res = mCameraProviderManager->initialize(this);
252 if (res != OK) {
253 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
254 __FUNCTION__, strerror(-res), res);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700255 logServiceError(String8::format("Unable to initialize camera provider manager"),
256 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800257 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100258 }
259 }
260
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800261
262 // Setup vendor tags before we call get_camera_info the first time
263 // because HAL might need to setup static vendor keys in get_camera_info
264 // TODO: maybe put this into CameraProviderManager::initialize()?
265 mCameraProviderManager->setUpVendorTags();
266
267 if (nullptr == mFlashlight.get()) {
268 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700269 }
270
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800271 res = mFlashlight->findFlashUnits();
272 if (res != OK) {
273 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
274 }
275
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000276 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800277 }
278
279
280 for (auto& cameraId : deviceIds) {
281 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800282 if (getCameraState(id8) == nullptr) {
283 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
284 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000285 if (unavailPhysicalIds.count(cameraId) > 0) {
286 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
287 String8 physicalId8 = String8(physicalId.c_str());
288 onDeviceStatusChanged(id8, physicalId8, CameraDeviceStatus::NOT_PRESENT);
289 }
290 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800291 }
292
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700293 // Derive primary rear/front cameras, and filter their charactierstics.
294 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700295 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700296 // Assume internal cameras are advertised from the same
297 // provider. If multiple providers are registered at different time,
298 // and each provider contains multiple internal color cameras, the current
299 // logic may filter the characteristics of more than one front/rear color
300 // cameras.
301 Mutex::Autolock l(mServiceLock);
302 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700303 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700304
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800305 return OK;
306}
307
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700308void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status,
309 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800310 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800311 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700312 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
313 i->getListenerUid())) {
314 ALOGV("Skipping torch callback for system-only camera device %s",
315 cameraId.c_str());
316 continue;
317 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700318 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
319 String16{cameraId});
320 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
321 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800322 }
323}
324
Mathias Agopian65ab4712010-07-14 17:59:35 -0700325CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800326 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800327 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800328 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800329 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700330}
331
Emilian Peevaee727d2017-05-04 16:35:48 +0100332void CameraService::onNewProviderRegistered() {
333 enumerateProviders();
334}
335
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700336void CameraService::filterAPI1SystemCameraLocked(
337 const std::vector<std::string> &normalDeviceIds) {
338 mNormalDeviceIdsWithoutSystemCamera.clear();
339 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700340 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
341 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
342 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
343 continue;
344 }
345 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700346 // All system camera ids will necessarily come after public camera
347 // device ids as per the HAL interface contract.
348 break;
349 }
350 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
351 }
352 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
353 mNormalDeviceIdsWithoutSystemCamera.size());
354}
355
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700356status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
357 auto state = getCameraState(cameraId);
358 if (state != nullptr) {
359 *kind = state->getSystemCameraKind();
360 return OK;
361 }
362 // Hidden physical camera ids won't have CameraState
363 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
364}
365
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800366void CameraService::updateCameraNumAndIds() {
367 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700368 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
369 // Excludes hidden secure cameras
370 mNumberOfCameras =
371 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
372 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800373 mNormalDeviceIds =
374 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700375 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800376}
377
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700378void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700379 // To claim to be S Performance primary cameras, the cameras must be
380 // backward compatible. So performance class primary camera Ids must be API1
381 // compatible.
382 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
383 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
384 int facing = -1;
385 int orientation = 0;
386 String8 cameraId8(cameraId.c_str());
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800387 int portraitRotation;
388 getDeviceVersion(cameraId8, /*overrideToPortrait*/false, /*out*/&portraitRotation,
389 /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700390 if (facing == -1) {
391 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
392 return;
393 }
394
395 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
396 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700397 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
398 if (res == OK) {
399 mPerfClassPrimaryCameraIds.insert(cameraId);
400 } else {
401 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
402 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
403 break;
404 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700405
406 if (facing == hardware::CAMERA_FACING_BACK) {
407 firstRearCameraSeen = true;
408 }
409 if (facing == hardware::CAMERA_FACING_FRONT) {
410 firstFrontCameraSeen = true;
411 }
412 }
413
414 if (firstRearCameraSeen && firstFrontCameraSeen) {
415 break;
416 }
417 }
418}
419
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100420void CameraService::addStates(const String8 id) {
421 std::string cameraId(id.c_str());
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700422 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100423 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
424 if (res != OK) {
425 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
426 return;
427 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000428 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700429 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
430 if (res != OK) {
431 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
432 return;
433 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000434 std::vector<std::string> physicalCameraIds;
435 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100436 std::set<String8> conflicting;
437 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
438 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
439 }
440
441 {
442 Mutex::Autolock lock(mCameraStatesLock);
443 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000444 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100445 }
446
447 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100448 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100449 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800450
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700451 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100452 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800453
454 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100455 logDeviceAdded(id, "Device added");
456}
457
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100458void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800459 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100460 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100461 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100462 mTorchStatusMap.removeItem(id);
463 }
464
465 {
466 Mutex::Autolock lock(mCameraStatesLock);
467 mCameraStates.erase(id);
468 }
469}
470
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800471void CameraService::onDeviceStatusChanged(const String8& id,
472 CameraDeviceStatus newHalStatus) {
473 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
474 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700475
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800476 StatusInternal newStatus = mapToInternal(newHalStatus);
477
Ruben Brunkcc776712015-02-17 20:18:47 -0800478 std::shared_ptr<CameraState> state = getCameraState(id);
479
480 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700481 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100482 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700483 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100484
485 // First add as absent to make sure clients are notified below
486 addStates(id);
487
488 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700489 } else {
490 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
491 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700492 return;
493 }
494
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800495 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800496
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800497 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800498 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700499 return;
500 }
501
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800502 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700503 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
504 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800505
506 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
507 // to this device until the status changes
508 updateStatus(StatusInternal::NOT_PRESENT, id);
509
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800510 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700511 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800512 // Don't do this in updateStatus to avoid deadlock over mServiceLock
513 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700514
Ruben Brunkcc776712015-02-17 20:18:47 -0800515 // Remove cached shim parameters
516 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700517
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800518 // Remove online as well as offline client from the list of active clients,
519 // if they are present
520 clientToDisconnectOnline = removeClientLocked(id);
521 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700522 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800523
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800524 disconnectClient(id, clientToDisconnectOnline);
525 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700526
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100527 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800528 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800529 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700530 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
531 newStatus));
532 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800533 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700534 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800535}
Igor Murashkincba2c162013-03-20 15:56:31 -0700536
Shuzhen Wang43858162020-01-10 13:42:15 -0800537void CameraService::onDeviceStatusChanged(const String8& id,
538 const String8& physicalId,
539 CameraDeviceStatus newHalStatus) {
540 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
541 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
542
543 StatusInternal newStatus = mapToInternal(newHalStatus);
544
545 std::shared_ptr<CameraState> state = getCameraState(id);
546
547 if (state == nullptr) {
548 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000549 __FUNCTION__, physicalId.string(), id.string());
Shuzhen Wang43858162020-01-10 13:42:15 -0800550 return;
551 }
552
553 StatusInternal logicalCameraStatus = state->getStatus();
554 if (logicalCameraStatus != StatusInternal::PRESENT &&
555 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
556 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
557 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
558 return;
559 }
560
561 bool updated = false;
562 if (newStatus == StatusInternal::PRESENT) {
563 updated = state->removeUnavailablePhysicalId(physicalId);
564 } else {
565 updated = state->addUnavailablePhysicalId(physicalId);
566 }
567
568 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800569 String8 idCombo = id + " : " + physicalId;
570 if (newStatus == StatusInternal::PRESENT) {
571 logDeviceAdded(idCombo,
572 String8::format("Device status changed to %d", newStatus));
573 } else {
574 logDeviceRemoved(idCombo,
575 String8::format("Device status changed to %d", newStatus));
576 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700577 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
578 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
579 if (getSystemCameraKind(id, &deviceKind) != OK) {
580 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
581 return;
582 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800583 String16 id16(id), physicalId16(physicalId);
584 Mutex::Autolock lock(mStatusListenerLock);
585 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700586 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
587 listener->getListenerPid(), listener->getListenerUid())) {
588 ALOGV("Skipping discovery callback for system-only camera device %s",
589 id.c_str());
590 continue;
591 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700592 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
593 mapToInterface(newStatus), id16, physicalId16);
594 listener->handleBinderStatus(ret,
595 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
596 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
597 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800598 }
599 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700600}
601
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800602void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
603 if (clientToDisconnect.get() != nullptr) {
604 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
605 __FUNCTION__, id.string());
606 // Notify the client of disconnection
607 clientToDisconnect->notifyError(
608 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
609 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800610 clientToDisconnect->disconnect();
611 }
612}
613
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800614void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800615 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700616 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
617 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
618 if (res != OK) {
619 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
620 cameraId.string());
621 return;
622 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800623 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700624 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800625}
626
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700627
628void CameraService::onTorchStatusChanged(const String8& cameraId,
629 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
630 Mutex::Autolock al(mTorchStatusMutex);
631 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
632}
633
Rucha Katakwar38284522021-11-10 11:25:21 -0800634void CameraService::broadcastTorchStrengthLevel(const String8& cameraId,
635 int32_t newStrengthLevel) {
636 Mutex::Autolock lock(mStatusListenerLock);
637 for (auto& i : mListenerList) {
Austin Borgere8e2c422022-05-12 13:45:24 -0700638 auto ret = i->getListener()->onTorchStrengthLevelChanged(String16{cameraId},
Rucha Katakwar38284522021-11-10 11:25:21 -0800639 newStrengthLevel);
Austin Borgere8e2c422022-05-12 13:45:24 -0700640 i->handleBinderStatus(ret,
641 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
642 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800643 }
644}
645
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800646void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700647 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800648 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
649 __FUNCTION__, cameraId.string(), newStatus);
650
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800651 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800652 status_t res = getTorchStatusLocked(cameraId, &status);
653 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700654 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
655 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800656 return;
657 }
658 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800659 return;
660 }
661
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800662 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800663 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800664 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
665 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800666 return;
667 }
668
Ruben Brunkcc776712015-02-17 20:18:47 -0800669 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700670 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700671 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700672 auto iter = mTorchUidMap.find(cameraId);
673 if (iter != mTorchUidMap.end()) {
674 int oldUid = iter->second.second;
675 int newUid = iter->second.first;
676 BatteryNotifier& notifier(BatteryNotifier::getInstance());
677 if (oldUid != newUid) {
678 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800679 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700680 notifier.noteFlashlightOff(cameraId, oldUid);
681 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800682 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700683 notifier.noteFlashlightOn(cameraId, newUid);
684 }
685 iter->second.second = newUid;
686 } else {
687 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800688 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700689 notifier.noteFlashlightOn(cameraId, oldUid);
690 } else {
691 notifier.noteFlashlightOff(cameraId, oldUid);
692 }
693 }
694 }
695 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700696 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800697}
698
Jayant Chowdharyc3198c32021-07-28 20:59:14 +0000699static bool hasPermissionsForSystemCamera(int callingPid, int callingUid,
700 bool logPermissionFailure = false) {
701 return checkPermission(sSystemCameraPermission, callingPid, callingUid,
702 logPermissionFailure) &&
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700703 checkPermission(sCameraPermission, callingPid, callingUid);
704}
705
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800706Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700707 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100708 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700709 bool hasSystemCameraPermissions =
710 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
711 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700712 switch (type) {
713 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700714 if (hasSystemCameraPermissions) {
715 *numCameras = static_cast<int>(mNormalDeviceIds.size());
716 } else {
717 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
718 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800719 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700720 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700721 if (hasSystemCameraPermissions) {
722 *numCameras = mNumberOfCameras;
723 } else {
724 *numCameras = mNumberOfCamerasWithoutSystemCamera;
725 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800726 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700727 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800728 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700729 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800730 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
731 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700732 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800733 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700734}
735
Austin Borger18b30a72022-10-27 12:20:29 -0700736Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800737 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700738 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100739 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700740 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
741 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
742 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
743 "characteristics for system only device %s: ", cameraIdStr.c_str());
744 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100745
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800746 if (!mInitialized) {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700747 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800748 return STATUS_ERROR(ERROR_DISCONNECTED,
749 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700750 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700751 bool hasSystemCameraPermissions =
752 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
753 CameraThreadState::getCallingUid());
754 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
755 if (hasSystemCameraPermissions) {
756 cameraIdBound = mNumberOfCameras;
757 }
758 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800759 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
760 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700761 }
762
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800763 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -0700764 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800765 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borger18b30a72022-10-27 12:20:29 -0700766 cameraIdStr.c_str(), overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100767 if (err != OK) {
768 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
769 "Error retrieving camera info from device %d: %s (%d)", cameraId,
770 strerror(-err), err);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700771 logServiceError(String8::format("Error retrieving camera info from device %d",cameraId),
772 ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -0800773 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100774
Ruben Brunkcc776712015-02-17 20:18:47 -0800775 return ret;
776}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700777
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800778std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700779 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
780 auto callingPid = CameraThreadState::getCallingPid();
781 auto callingUid = CameraThreadState::getCallingUid();
Jayant Chowdharyc3198c32021-07-28 20:59:14 +0000782 if (checkPermission(sSystemCameraPermission, callingPid, callingUid,
783 /*logPermissionFailure*/false) || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700784 deviceIds = &mNormalDeviceIds;
785 }
786 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800787 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700788 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800789 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800790 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800791
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700792 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800793}
794
795String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
796 Mutex::Autolock lock(mServiceLock);
797 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800798}
799
800Status CameraService::getCameraCharacteristics(const String16& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -0700801 int targetSdkVersion, bool overrideToPortrait, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700802 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700803 if (!cameraInfo) {
804 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800805 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700806 }
807
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800808 if (!mInitialized) {
809 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700810 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800811 return STATUS_ERROR(ERROR_DISCONNECTED,
812 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700813 }
814
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700815 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
816 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
817 "characteristics for system only device %s: ", String8(cameraId).string());
818 }
819
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800820 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800821
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700822
823 std::string cameraIdStr = String8(cameraId).string();
824 bool overrideForPerfClass =
825 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
826 cameraIdStr, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100827 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borger18b30a72022-10-27 12:20:29 -0700828 cameraIdStr, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100829 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700830 if (res == NAME_NOT_FOUND) {
831 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
832 "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
833 strerror(-res), res);
834 } else {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700835 logServiceError(String8::format("Unable to retrieve camera characteristics for "
836 "device %s.", String8(cameraId).string()),ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700837 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
838 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
839 strerror(-res), res);
840 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700841 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700842 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
843 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
844 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
845 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
846 "for device %s", String8(cameraId).string());
847 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700848 int callingPid = CameraThreadState::getCallingPid();
849 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100850 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700851 // If it's not calling from cameraserver, check the permission only if
852 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
853 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100854 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700855 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700856 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100857 res = cameraInfo->removePermissionEntries(
858 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
859 &tagsRemoved);
860 if (res != OK) {
861 cameraInfo->clear();
862 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
863 " characteristics needing camera permission for device %s: %s (%d)",
864 String8(cameraId).string(), strerror(-res), res);
865 }
866 }
867
868 if (!tagsRemoved.empty()) {
869 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
870 tagsRemoved.data(), tagsRemoved.size());
871 if (res != OK) {
872 cameraInfo->clear();
873 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
874 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
875 strerror(-res), res);
876 }
877 }
878
Zhijun He2b59be82013-09-25 10:14:30 -0700879 return ret;
880}
881
Rucha Katakwar38284522021-11-10 11:25:21 -0800882Status CameraService::getTorchStrengthLevel(const String16& cameraId,
883 int32_t* torchStrength) {
884 ATRACE_CALL();
885 Mutex::Autolock l(mServiceLock);
886 if (!mInitialized) {
887 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
888 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
889 }
890
891 if(torchStrength == NULL) {
892 ALOGE("%s: strength level must not be null.", __FUNCTION__);
893 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
894 }
895
896 status_t res = mCameraProviderManager->getTorchStrengthLevel(String8(cameraId).string(),
897 torchStrength);
898 if (res != OK) {
899 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
900 "strength level for device %s: %s (%d)", String8(cameraId).string(),
901 strerror(-res), res);
902 }
903 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
904 return Status::ok();
905}
906
Ruben Brunkcc776712015-02-17 20:18:47 -0800907String8 CameraService::getFormattedCurrentTime() {
908 time_t now = time(nullptr);
909 char formattedTime[64];
910 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
911 return String8(formattedTime);
912}
913
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800914Status CameraService::getCameraVendorTagDescriptor(
915 /*out*/
916 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700917 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800918 if (!mInitialized) {
919 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800920 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800921 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800922 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
923 if (globalDescriptor != nullptr) {
924 *desc = *(globalDescriptor.get());
925 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800926 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800927}
928
Emilian Peev71c73a22017-03-21 16:35:51 +0000929Status CameraService::getCameraVendorTagCache(
930 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
931 ATRACE_CALL();
932 if (!mInitialized) {
933 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
934 return STATUS_ERROR(ERROR_DISCONNECTED,
935 "Camera subsystem not available");
936 }
937 sp<VendorTagDescriptorCache> globalCache =
938 VendorTagDescriptorCache::getGlobalVendorTagCache();
939 if (globalCache != nullptr) {
940 *cache = *(globalCache.get());
941 }
942 return Status::ok();
943}
944
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700945void CameraService::clearCachedVariables() {
946 BasicClient::BasicClient::sCameraService = nullptr;
947}
948
Austin Borger18b30a72022-10-27 12:20:29 -0700949std::pair<int, IPCTransport> CameraService::getDeviceVersion(const String8& cameraId,
950 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700951 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800952
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800953 int deviceVersion = 0;
954
Emilian Peevf53f66e2017-04-11 14:29:43 +0100955 status_t res;
956 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +0000957 IPCTransport transport = IPCTransport::INVALID;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100958 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +0000959 &maxVersion, &transport);
960 if (res != OK || transport == IPCTransport::INVALID) {
961 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
962 cameraId.string());
963 return std::make_pair(-1, IPCTransport::INVALID) ;
964 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100965 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800966
Emilian Peevf53f66e2017-04-11 14:29:43 +0100967 hardware::CameraInfo info;
968 if (facing) {
Austin Borger18b30a72022-10-27 12:20:29 -0700969 res = mCameraProviderManager->getCameraInfo(cameraId.string(), overrideToPortrait,
970 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +0000971 if (res != OK) {
972 return std::make_pair(-1, IPCTransport::INVALID);
973 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100974 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -0700975 if (orientation) {
976 *orientation = info.orientation;
977 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800978 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100979
Jayant Chowdharyffc5d682022-05-12 18:34:34 +0000980 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -0800981}
982
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800983Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700984 switch(err) {
985 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800986 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800987 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800988 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
989 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800990 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800991 return STATUS_ERROR(ERROR_DISCONNECTED,
992 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700993 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800994 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
995 "Camera HAL encountered error %d: %s",
996 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700997 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800998}
999
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001000Status CameraService::makeClient(const sp<CameraService>& cameraService,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001001 const sp<IInterface>& cameraCb, const String16& packageName, bool systemNativeClient,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001002 const std::optional<String16>& featureId, const String8& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001003 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001004 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001005 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
1006 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001007 // For HIDL devices
1008 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1009 // Create CameraClient based on device version reported by the HAL.
1010 int deviceVersion = deviceVersionAndTransport.first;
1011 switch(deviceVersion) {
1012 case CAMERA_DEVICE_API_VERSION_1_0:
1013 ALOGE("Camera using old HAL version: %d", deviceVersion);
1014 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1015 "Camera device \"%s\" HAL version %d no longer supported",
1016 cameraId.string(), deviceVersion);
1017 break;
1018 case CAMERA_DEVICE_API_VERSION_3_0:
1019 case CAMERA_DEVICE_API_VERSION_3_1:
1020 case CAMERA_DEVICE_API_VERSION_3_2:
1021 case CAMERA_DEVICE_API_VERSION_3_3:
1022 case CAMERA_DEVICE_API_VERSION_3_4:
1023 case CAMERA_DEVICE_API_VERSION_3_5:
1024 case CAMERA_DEVICE_API_VERSION_3_6:
1025 case CAMERA_DEVICE_API_VERSION_3_7:
1026 break;
1027 default:
1028 // Should not be reachable
1029 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1030 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1031 "Camera device \"%s\" has unknown HAL version %d",
1032 cameraId.string(), deviceVersion);
1033 }
1034 }
1035 if (effectiveApiLevel == API_1) { // Camera1 API route
1036 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001037 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
1038 packageName, featureId, cameraId, api1CameraId, facing, sensorOrientation,
Austin Borger18b30a72022-10-27 12:20:29 -07001039 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait);
1040 ALOGI("%s: Camera1 API (legacy), override to portrait %d", __FUNCTION__,
1041 overrideToPortrait);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001042 } else { // Camera2 API route
1043 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1044 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001045 *client = new CameraDeviceClient(cameraService, tmp,
1046 cameraService->mCameraServiceProxyWrapper, packageName, systemNativeClient,
1047 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
Austin Borger18b30a72022-10-27 12:20:29 -07001048 overrideForPerfClass, overrideToPortrait);
1049 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001050 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001051 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001052}
1053
Ruben Brunk6267b532015-04-30 17:44:07 -07001054String8 CameraService::toString(std::set<userid_t> intSet) {
1055 String8 s("");
1056 bool first = true;
1057 for (userid_t i : intSet) {
1058 if (first) {
1059 s.appendFormat("%d", i);
1060 first = false;
1061 } else {
1062 s.appendFormat(", %d", i);
1063 }
1064 }
1065 return s;
1066}
1067
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001068int32_t CameraService::mapToInterface(TorchModeStatus status) {
1069 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1070 switch (status) {
1071 case TorchModeStatus::NOT_AVAILABLE:
1072 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1073 break;
1074 case TorchModeStatus::AVAILABLE_OFF:
1075 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1076 break;
1077 case TorchModeStatus::AVAILABLE_ON:
1078 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1079 break;
1080 default:
1081 ALOGW("Unknown new flash status: %d", status);
1082 }
1083 return serviceStatus;
1084}
1085
1086CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1087 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1088 switch (status) {
1089 case CameraDeviceStatus::NOT_PRESENT:
1090 serviceStatus = StatusInternal::NOT_PRESENT;
1091 break;
1092 case CameraDeviceStatus::PRESENT:
1093 serviceStatus = StatusInternal::PRESENT;
1094 break;
1095 case CameraDeviceStatus::ENUMERATING:
1096 serviceStatus = StatusInternal::ENUMERATING;
1097 break;
1098 default:
1099 ALOGW("Unknown new HAL device status: %d", status);
1100 }
1101 return serviceStatus;
1102}
1103
1104int32_t CameraService::mapToInterface(StatusInternal status) {
1105 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1106 switch (status) {
1107 case StatusInternal::NOT_PRESENT:
1108 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1109 break;
1110 case StatusInternal::PRESENT:
1111 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1112 break;
1113 case StatusInternal::ENUMERATING:
1114 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1115 break;
1116 case StatusInternal::NOT_AVAILABLE:
1117 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1118 break;
1119 case StatusInternal::UNKNOWN:
1120 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1121 break;
1122 default:
1123 ALOGW("Unknown new internal device status: %d", status);
1124 }
1125 return serviceStatus;
1126}
1127
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001128Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001129 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001130
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001131 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -08001132 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001133 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001134 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001135 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001136 sp<ICameraClient>{nullptr}, id, cameraId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001137 internalPackageName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001138 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Austin Borger18b30a72022-10-27 12:20:29 -07001139 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001140 ).isOk()) {
1141 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001142 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001143 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001144}
1145
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001146Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001147 /*out*/
1148 CameraParameters* parameters) {
1149
1150 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1151
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001152 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001153
1154 if (parameters == NULL) {
1155 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001156 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001157 }
1158
Ruben Brunkcc776712015-02-17 20:18:47 -08001159 String8 id = String8::format("%d", cameraId);
1160
1161 // Check if we already have parameters
1162 {
1163 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001164 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001165 auto cameraState = getCameraState(id);
1166 if (cameraState == nullptr) {
1167 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001168 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1169 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001170 }
1171 CameraParameters p = cameraState->getShimParams();
1172 if (!p.isEmpty()) {
1173 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001174 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001175 }
1176 }
1177
Jayant Chowdhary12361932018-08-27 14:46:13 -07001178 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001179 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001180 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001181 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001182 // Error already logged by callee
1183 return ret;
1184 }
1185
1186 // Check for parameters again
1187 {
1188 // Scope for service lock
1189 Mutex::Autolock lock(mServiceLock);
1190 auto cameraState = getCameraState(id);
1191 if (cameraState == nullptr) {
1192 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001193 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1194 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001195 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001196 CameraParameters p = cameraState->getShimParams();
1197 if (!p.isEmpty()) {
1198 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001199 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001200 }
1201 }
1202
Ruben Brunkcc776712015-02-17 20:18:47 -08001203 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1204 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001205 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001206}
1207
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001208// Can camera service trust the caller based on the calling UID?
1209static bool isTrustedCallingUid(uid_t uid) {
1210 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001211 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001212 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001213 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001214 return true;
1215 default:
1216 return false;
1217 }
1218}
1219
Nicholas Sauera3620332019-04-03 14:05:17 -07001220static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1221 PermissionController pc;
1222 uid = pc.getPackageUid(packageName, 0);
1223 if (uid <= 0) {
1224 ALOGE("Unknown package: '%s'", String8(packageName).string());
1225 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1226 return BAD_VALUE;
1227 }
1228
1229 if (userId < 0) {
1230 ALOGE("Invalid user: %d", userId);
1231 dprintf(err, "Invalid user: %d\n", userId);
1232 return BAD_VALUE;
1233 }
1234
1235 uid = multiuser_get_uid(userId, uid);
1236 return NO_ERROR;
1237}
1238
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001239Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001240 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1241 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001242
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001243#ifdef __BRILLO__
1244 UNUSED(clientName8);
1245 UNUSED(clientUid);
1246 UNUSED(clientPid);
1247 UNUSED(originalClientPid);
1248#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001249 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1250 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001251 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001252 return allowed;
1253 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001254#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001255
Jayant Chowdhary12361932018-08-27 14:46:13 -07001256 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001257
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001258 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001259 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1260 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001261 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1262 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001263 }
1264
Ruben Brunkcc776712015-02-17 20:18:47 -08001265 if (getCameraState(cameraId) == nullptr) {
1266 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1267 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001268 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1269 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001270 }
1271
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001272 status_t err = checkIfDeviceIsUsable(cameraId);
1273 if (err != NO_ERROR) {
1274 switch(err) {
1275 case -ENODEV:
1276 case -EBUSY:
1277 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1278 "No camera device with ID \"%s\" currently available", cameraId.string());
1279 default:
1280 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1281 "Unknown error connecting to ID \"%s\"", cameraId.string());
1282 }
1283 }
1284 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001285}
1286
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001287Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001288 const String8& clientName8, int& clientUid, int& clientPid,
1289 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001290 int callingPid = CameraThreadState::getCallingPid();
1291 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001292
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001293 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001294 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001295 clientUid = callingUid;
1296 } else if (!isTrustedCallingUid(callingUid)) {
1297 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1298 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001299 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1300 "Untrusted caller (calling PID %d, UID %d) trying to "
1301 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1302 callingPid, callingUid, cameraId.string(),
1303 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001304 }
1305
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001306 // Check if we can trust clientPid
1307 if (clientPid == USE_CALLING_PID) {
1308 clientPid = callingPid;
1309 } else if (!isTrustedCallingUid(callingUid)) {
1310 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1311 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001312 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1313 "Untrusted caller (calling PID %d, UID %d) trying to "
1314 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1315 callingPid, callingUid, cameraId.string(),
1316 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001317 }
1318
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001319 if (shouldRejectSystemCameraConnection(cameraId)) {
1320 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1321 cameraId.c_str());
1322 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1323 "available", cameraId.string());
1324 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001325 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1326 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1327 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1328 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1329 "found while trying to query device kind", cameraId.string());
1330
1331 }
1332
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001333 // If it's not calling from cameraserver, check the permission if the
1334 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1335 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001336 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001337 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001338 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001339 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001340 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1341 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1342 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001343 }
1344
Svet Ganova453d0d2018-01-11 15:37:58 -08001345 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001346 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001347 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001348 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1349 clientPid, clientUid);
1350 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001351 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1352 "calling UID %d proc state %" PRId32 ")",
1353 clientName8.string(), clientUid, clientPid, cameraId.string(),
1354 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001355 }
1356
Michael Grooverd1d435a2018-12-18 17:39:42 -08001357 // If sensor privacy is enabled then prevent access to the camera
1358 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1359 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1360 return STATUS_ERROR_FMT(ERROR_DISABLED,
1361 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1362 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1363 }
1364
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001365 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1366 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001367 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001368 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001369
Ruben Brunk6267b532015-04-30 17:44:07 -07001370 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001371
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001372 // For non-system clients : Only allow clients who are being used by the current foreground
1373 // device user, unless calling from our own process.
1374 if (!doesClientHaveSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001375 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001376 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1377 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1378 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001379 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1380 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1381 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001382 }
1383
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001384 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001385}
1386
1387status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1388 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001389 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001390 if (cameraState == nullptr) {
1391 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1392 cameraId.string());
1393 return -ENODEV;
1394 }
1395
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001396 StatusInternal currentStatus = cameraState->getStatus();
1397 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001398 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1399 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001400 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001401 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001402 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1403 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001404 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001405 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001406
Ruben Brunkcc776712015-02-17 20:18:47 -08001407 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001408}
1409
Ruben Brunkcc776712015-02-17 20:18:47 -08001410void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001411 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001412
Ruben Brunkcc776712015-02-17 20:18:47 -08001413 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001414 auto clientDescriptor =
1415 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001416 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001417 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1418
1419 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1420 String8(client->getPackageName()));
1421
1422 if (evicted.size() > 0) {
1423 // This should never happen - clients should already have been removed in disconnect
1424 for (auto& i : evicted) {
1425 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1426 __FUNCTION__, i->getKey().string());
1427 }
1428
1429 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1430 __FUNCTION__);
1431 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001432
1433 // And register a death notification for the client callback. Do
1434 // this last to avoid Binder policy where a nested Binder
1435 // transaction might be pre-empted to service the client death
1436 // notification if the client process dies before linkToDeath is
1437 // invoked.
1438 sp<IBinder> remoteCallback = client->getRemote();
1439 if (remoteCallback != nullptr) {
1440 remoteCallback->linkToDeath(this);
1441 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001442}
1443
1444status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1445 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001446 int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001447 /*out*/
1448 sp<BasicClient>* client,
1449 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001450 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001451 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001452 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001453 DescriptorPtr clientDescriptor;
1454 {
1455 if (effectiveApiLevel == API_1) {
1456 // If we are using API1, any existing client for this camera ID with the same remote
1457 // should be returned rather than evicted to allow MediaRecorder to work properly.
1458
1459 auto current = mActiveClientManager.get(cameraId);
1460 if (current != nullptr) {
1461 auto clientSp = current->getValue();
1462 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001463 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001464 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001465 " API level, evicting prior client...");
1466 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001467 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001468 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001469 *client = clientSp;
1470 return NO_ERROR;
1471 }
1472 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001473 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001474 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001475
Ruben Brunkcc776712015-02-17 20:18:47 -08001476 // Get current active client PIDs
1477 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1478 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001479
Emilian Peev8131a262017-02-01 12:33:43 +00001480 std::vector<int> priorityScores(ownerPids.size());
1481 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001482
Emilian Peev8131a262017-02-01 12:33:43 +00001483 // Get priority scores of all active PIDs
1484 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1485 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1486 /*out*/&priorityScores[0]);
1487 if (err != OK) {
1488 ALOGE("%s: Priority score query failed: %d",
1489 __FUNCTION__, err);
1490 return err;
1491 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001492
Ruben Brunkcc776712015-02-17 20:18:47 -08001493 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001494 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001495 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001496 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001497 resource_policy::ClientPriority(priorityScores[i], states[i],
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001498 /* isVendorClient won't get copied over*/ false,
1499 /* oomScoreOffset won't get copied over*/ 0));
Ruben Brunkcc776712015-02-17 20:18:47 -08001500 }
1501 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001502
Ruben Brunkcc776712015-02-17 20:18:47 -08001503 // Get state for the given cameraId
1504 auto state = getCameraState(cameraId);
1505 if (state == nullptr) {
1506 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1507 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001508 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001509 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001510 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001511
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001512 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1513 int32_t actualState = states[states.size() - 1];
1514
1515 // Make descriptor for incoming client. We store the oomScoreOffset
1516 // since we might need it later on new handleEvictionsLocked and
1517 // ProcessInfoService would not take that into account.
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001518 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001519 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001520 state->getConflicting(), actualScore, clientPid, actualState,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001521 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001522
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001523 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1524
Ruben Brunkcc776712015-02-17 20:18:47 -08001525 // Find clients that would be evicted
1526 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1527
1528 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1529 // background, so we cannot do evictions
1530 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1531 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1532 " priority).", clientPid);
1533
1534 sp<BasicClient> clientSp = clientDescriptor->getValue();
1535 String8 curTime = getFormattedCurrentTime();
1536 auto incompatibleClients =
1537 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1538
1539 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001540 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001541 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001542 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001543
1544 for (auto& i : incompatibleClients) {
1545 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001546 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1547 i->getKey().string(),
1548 String8{i->getValue()->getPackageName()}.string(),
1549 i->getOwnerId(), i->getPriority().getScore(),
1550 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001551 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001552 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001553 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001554 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001555 }
1556
1557 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001558 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001559 mEventLog.add(msg);
1560
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001561 auto current = mActiveClientManager.get(cameraId);
1562 if (current != nullptr) {
1563 return -EBUSY; // CAMERA_IN_USE
1564 } else {
1565 return -EUSERS; // MAX_CAMERAS_IN_USE
1566 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001567 }
1568
1569 for (auto& i : evicted) {
1570 sp<BasicClient> clientSp = i->getValue();
1571 if (clientSp.get() == nullptr) {
1572 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1573
1574 // TODO: Remove this
1575 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1576 __FUNCTION__);
1577 mActiveClientManager.remove(i);
1578 continue;
1579 }
1580
1581 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1582 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001583 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001584
Ruben Brunkcc776712015-02-17 20:18:47 -08001585 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001586 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001587 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1588 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001589 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001590 i->getOwnerId(), i->getPriority().getScore(),
1591 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001592 packageName.string(), clientPid, clientPriority.getScore(),
1593 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001594
1595 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001596 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001597 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001598 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001599 }
1600
Ruben Brunkcc776712015-02-17 20:18:47 -08001601 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1602 // other clients from connecting in mServiceLockWrapper if held
1603 mServiceLock.unlock();
1604
1605 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001606 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001607
1608 // Destroy evicted clients
1609 for (auto& i : evictedClients) {
1610 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001611 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001612 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001613
Jayant Chowdhary12361932018-08-27 14:46:13 -07001614 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001615
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001616 for (const auto& i : evictedClients) {
1617 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1618 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1619 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1620 if (ret == TIMED_OUT) {
1621 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1622 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1623 mActiveClientManager.toString().string());
1624 return -EBUSY;
1625 }
1626 if (ret != NO_ERROR) {
1627 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1628 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1629 ret, mActiveClientManager.toString().string());
1630 return ret;
1631 }
1632 }
1633
1634 evictedClients.clear();
1635
Ruben Brunkcc776712015-02-17 20:18:47 -08001636 // Once clients have been disconnected, relock
1637 mServiceLock.lock();
1638
1639 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1640 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1641 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001642 }
1643
Ruben Brunkcc776712015-02-17 20:18:47 -08001644 *partial = clientDescriptor;
1645 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001646}
1647
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001648Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001649 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001650 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001651 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001652 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001653 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001654 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001655 bool overrideToPortrait,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001656 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001657 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001658
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001659 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001660 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001661
1662 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001663 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001664 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001665 clientPackageName,/*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07001666 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
1667 overrideToPortrait, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001668
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001669 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001670 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001671 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001672 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001673 }
1674
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001675 *device = client;
1676 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001677}
1678
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001679bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1680 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001681 // If the client is not a vendor client, don't add listener if
1682 // a) the camera is a publicly hidden secure camera OR
1683 // b) the camera is a system only camera and the client doesn't
1684 // have android.permission.SYSTEM_CAMERA permissions.
1685 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1686 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1687 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001688 return true;
1689 }
1690 return false;
1691}
1692
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001693bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1694 // Rules for rejection:
1695 // 1) If cameraserver tries to access this camera device, accept the
1696 // connection.
1697 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001698 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001699 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1700 // and the serving thread is a non hwbinder thread, the client must have
1701 // android.permission.SYSTEM_CAMERA permissions to connect.
1702
1703 int cPid = CameraThreadState::getCallingPid();
1704 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001705 bool systemClient = doesClientHaveSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001706 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1707 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001708 // This isn't a known camera ID, so it's not a system camera
1709 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1710 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001711 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001712
1713 // (1) Cameraserver trying to connect, accept.
1714 if (CameraThreadState::getCallingPid() == getpid()) {
1715 return false;
1716 }
1717 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001718 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001719 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1720 return true;
1721 }
1722 // (3) Here we only check for permissions if it is a system only camera device. This is since
1723 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1724 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1725 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001726 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jayant Chowdharyc3198c32021-07-28 20:59:14 +00001727 !hasPermissionsForSystemCamera(cPid, cUid, /*logPermissionFailure*/true)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001728 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1729 cameraId.c_str());
1730 return true;
1731 }
1732
1733 return false;
1734}
1735
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001736Status CameraService::connectDevice(
1737 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001738 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001739 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001740 const std::optional<String16>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001741 int clientUid, int oomScoreOffset, int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001742 bool overrideToPortrait,
Ruben Brunkcc776712015-02-17 20:18:47 -08001743 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001744 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001745
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001746 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001747 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001748 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001749 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001750 String16 clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001751 int callingPid = CameraThreadState::getCallingPid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001752 bool systemNativeClient = false;
1753 if (doesClientHaveSystemUid() && (clientPackageNameAdj.size() == 0)) {
1754 std::string systemClient =
1755 StringPrintf("client.pid<%d>", CameraThreadState::getCallingPid());
1756 clientPackageNameAdj = String16(systemClient.c_str());
1757 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001758 }
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001759
1760 if (oomScoreOffset < 0) {
1761 String8 msg =
1762 String8::format("Cannot increase the priority of a client %s pid %d for "
1763 "camera id %s", String8(clientPackageNameAdj).string(), callingPid,
1764 id.string());
1765 ALOGE("%s: %s", __FUNCTION__, msg.string());
1766 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1767 }
1768
Austin Borger9bfa0a72022-08-03 17:50:40 -07001769 userid_t clientUserId = multiuser_get_user_id(clientUid);
1770 int callingUid = CameraThreadState::getCallingUid();
1771 if (clientUid == USE_CALLING_UID) {
1772 clientUserId = multiuser_get_user_id(callingUid);
1773 }
1774
1775 if (mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borger5f7abe22022-04-26 15:55:10 -07001776 String8 msg =
1777 String8::format("Camera disabled by device policy");
1778 ALOGE("%s: %s", __FUNCTION__, msg.string());
1779 return STATUS_ERROR(ERROR_DISABLED, msg.string());
1780 }
1781
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001782 // enforce system camera permissions
1783 if (oomScoreOffset > 0 &&
Austin Borger86a588e2022-05-23 12:41:58 -07001784 !hasPermissionsForSystemCamera(callingPid, CameraThreadState::getCallingUid()) &&
1785 !isTrustedCallingUid(CameraThreadState::getCallingUid())) {
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001786 String8 msg =
1787 String8::format("Cannot change the priority of a client %s pid %d for "
1788 "camera id %s without SYSTEM_CAMERA permissions",
1789 String8(clientPackageNameAdj).string(), callingPid, id.string());
1790 ALOGE("%s: %s", __FUNCTION__, msg.string());
1791 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.string());
1792 }
1793
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001794 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001795 /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient,clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001796 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
Austin Borger18b30a72022-10-27 12:20:29 -07001797 targetSdkVersion, overrideToPortrait, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001798
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001799 if(!ret.isOk()) {
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001800 logRejected(id, callingPid, String8(clientPackageNameAdj), ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001801 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001802 }
1803
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001804 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07001805 Mutex::Autolock lock(mServiceLock);
1806
1807 // Clear the previous cached logs and reposition the
1808 // file offset to beginning of the file to log new data.
1809 // If either truncate or lseek fails, close the previous file and create a new one.
1810 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
1811 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
1812 // Close the previous memfd.
1813 close(mMemFd);
1814 // If failure to wipe the data, then create a new file and
1815 // assign the new value to mMemFd.
1816 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
1817 if (mMemFd == -1) {
1818 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
1819 }
1820 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001821 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001822}
1823
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001824String16 CameraService::getPackageNameFromUid(int clientUid) {
1825 String16 packageName("");
1826
1827 sp<IServiceManager> sm = defaultServiceManager();
1828 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
1829 if (binder == 0) {
1830 ALOGE("Cannot get permission service");
1831 // Return empty package name and the further interaction
1832 // with camera will likely fail
1833 return packageName;
1834 }
1835
1836 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
1837 Vector<String16> packages;
1838
1839 permCtrl->getPackagesForUid(clientUid, packages);
1840
1841 if (packages.isEmpty()) {
1842 ALOGE("No packages for calling UID %d", clientUid);
1843 // Return empty package name and the further interaction
1844 // with camera will likely fail
1845 return packageName;
1846 }
1847
1848 // Arbitrarily pick the first name in the list
1849 packageName = packages[0];
1850
1851 return packageName;
1852}
1853
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001854template<class CALLBACK, class CLIENT>
1855Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001856 int api1CameraId, const String16& clientPackageNameMaybe, bool systemNativeClient,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001857 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001858 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001859 bool overrideToPortrait, /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001860 binder::Status ret = binder::Status::ok();
1861
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001862 bool isNonSystemNdk = false;
1863 String16 clientPackageName;
1864 if (clientPackageNameMaybe.size() <= 0) {
1865 // NDK calls don't come with package names, but we need one for various cases.
1866 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
1867 // do exist. For all authentication cases, all packages under the same UID get the
1868 // same permissions, so picking any associated package name is sufficient. For some
1869 // other cases, this may give inaccurate names for clients in logs.
1870 isNonSystemNdk = true;
1871 int packageUid = (clientUid == USE_CALLING_UID) ?
1872 CameraThreadState::getCallingUid() : clientUid;
1873 clientPackageName = getPackageNameFromUid(packageUid);
1874 } else {
1875 clientPackageName = clientPackageNameMaybe;
1876 }
1877
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001878 String8 clientName8(clientPackageName);
1879
1880 int originalClientPid = 0;
1881
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001882 int packagePid = (clientPid == USE_CALLING_PID) ?
1883 CameraThreadState::getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001884 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001885 "Camera API version %d", packagePid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001886 static_cast<int>(effectiveApiLevel));
1887
Shuzhen Wang316781a2020-08-18 18:11:01 -07001888 nsecs_t openTimeNs = systemTime();
1889
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001890 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001891 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07001892 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001893
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001894 {
1895 // Acquire mServiceLock and prevent other clients from connecting
1896 std::unique_ptr<AutoConditionLock> lock =
1897 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1898
1899 if (lock == nullptr) {
1900 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1901 , clientPid);
1902 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1903 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1904 cameraId.string(), clientName8.string(), clientPid);
1905 }
1906
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001907 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001908 if(!(ret = validateConnectLocked(cameraId, clientName8,
1909 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1910 return ret;
1911 }
1912
1913 // Check the shim parameters after acquiring lock, if they have already been updated and
1914 // we were doing a shim update, return immediately
1915 if (shimUpdateOnly) {
1916 auto cameraState = getCameraState(cameraId);
1917 if (cameraState != nullptr) {
1918 if (!cameraState->getShimParams().isEmpty()) return ret;
1919 }
1920 }
1921
1922 status_t err;
1923
1924 sp<BasicClient> clientTmp = nullptr;
1925 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1926 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001927 IInterface::asBinder(cameraCb), clientName8, oomScoreOffset, systemNativeClient,
1928 /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001929 switch (err) {
1930 case -ENODEV:
1931 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1932 "No camera device with ID \"%s\" currently available",
1933 cameraId.string());
1934 case -EBUSY:
1935 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1936 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1937 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001938 case -EUSERS:
1939 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1940 "Too many cameras already open, cannot open camera \"%s\"",
1941 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001942 default:
1943 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1944 "Unexpected error %s (%d) opening camera \"%s\"",
1945 strerror(-err), err, cameraId.string());
1946 }
1947 }
1948
1949 if (clientTmp.get() != nullptr) {
1950 // Handle special case for API1 MediaRecorder where the existing client is returned
1951 device = static_cast<CLIENT*>(clientTmp.get());
1952 return ret;
1953 }
1954
1955 // give flashlight a chance to close devices if necessary.
1956 mFlashlight->prepareDeviceOpen(cameraId);
1957
Austin Borger18b30a72022-10-27 12:20:29 -07001958 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001959 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07001960 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
1961 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001962 if (facing == -1) {
1963 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1964 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1965 "Unable to get camera device \"%s\" facing", cameraId.string());
1966 }
1967
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001968 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001969 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1970 mPerfClassPrimaryCameraIds, cameraId.string(), targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001971 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
1972 clientFeatureId, cameraId, api1CameraId, facing, orientation,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001973 clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001974 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
Austin Borger18b30a72022-10-27 12:20:29 -07001975 overrideToPortrait, /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001976 return ret;
1977 }
1978 client = static_cast<CLIENT*>(tmp.get());
1979
1980 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1981 __FUNCTION__);
1982
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07001983 String8 monitorTags = isClientWatched(client.get()) ? mMonitorTags : String8("");
1984 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001985 if (err != OK) {
1986 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001987 // Errors could be from the HAL module open call or from AppOpsManager
1988 switch(err) {
1989 case BAD_VALUE:
1990 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1991 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1992 case -EBUSY:
1993 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1994 "Camera \"%s\" is already open", cameraId.string());
1995 case -EUSERS:
1996 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1997 "Too many cameras already open, cannot open camera \"%s\"",
1998 cameraId.string());
1999 case PERMISSION_DENIED:
2000 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2001 "No permission to open camera \"%s\"", cameraId.string());
2002 case -EACCES:
2003 return STATUS_ERROR_FMT(ERROR_DISABLED,
2004 "Camera \"%s\" disabled by policy", cameraId.string());
2005 case -ENODEV:
2006 default:
2007 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2008 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
2009 strerror(-err), err);
2010 }
2011 }
2012
2013 // Update shim paremeters for legacy clients
2014 if (effectiveApiLevel == API_1) {
2015 // Assume we have always received a Client subclass for API1
2016 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2017 String8 rawParams = shimClient->getParameters();
2018 CameraParameters params(rawParams);
2019
2020 auto cameraState = getCameraState(cameraId);
2021 if (cameraState != nullptr) {
2022 cameraState->setShimParams(params);
2023 } else {
2024 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
2025 __FUNCTION__, cameraId.string());
2026 }
2027 }
2028
Ravneetaeb20dc2022-03-30 05:33:03 +00002029 // Enable/disable camera service watchdog
2030 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2031
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002032 // Set rotate-and-crop override behavior
2033 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2034 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Austin Borger18b30a72022-10-27 12:20:29 -07002035 } else if (overrideToPortrait && portraitRotation != 0) {
2036 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2037 switch (portraitRotation) {
2038 case 90:
2039 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2040 break;
2041 case 180:
2042 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2043 break;
2044 case 270:
2045 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2046 break;
2047 default:
2048 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2049 break;
2050 }
2051 client->setRotateAndCropOverride(rotateAndCropMode);
Emilian Peev13f35ad2022-04-27 11:28:48 -07002052 } else {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002053 client->setRotateAndCropOverride(
2054 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2055 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2056 }
2057
2058 // Set autoframing override behaviour
2059 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2060 client->setAutoframingOverride(mOverrideAutoframingMode);
2061 } else {
2062 client->setAutoframingOverride(
2063 mCameraServiceProxyWrapper->getAutoframingOverride(
2064 clientPackageName));
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002065 }
2066
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002067 // Set camera muting behavior
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002068 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08002069 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002070 if (client->supportsCameraMute()) {
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002071 client->setCameraMute(
2072 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2073 } else if (isCameraPrivacyEnabled) {
2074 // no camera mute supported, but privacy is on! => disconnect
2075 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2076 String8(client->getPackageName()).string(), cameraId.string());
2077 // Do not hold mServiceLock while disconnecting clients, but
2078 // retain the condition blocking other clients from connecting
2079 // in mServiceLockWrapper if held.
2080 mServiceLock.unlock();
2081 // Clear caller identity temporarily so client disconnect PID
2082 // checks work correctly
2083 int64_t token = CameraThreadState::clearCallingIdentity();
2084 // Note AppOp to trigger the "Unblock" dialog
2085 client->noteAppOp();
2086 client->disconnect();
2087 CameraThreadState::restoreCallingIdentity(token);
2088 // Reacquire mServiceLock
2089 mServiceLock.lock();
2090
2091 return STATUS_ERROR_FMT(ERROR_DISABLED,
2092 "Camera \"%s\" disabled due to camera mute", cameraId.string());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002093 }
2094
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002095 if (shimUpdateOnly) {
2096 // If only updating legacy shim parameters, immediately disconnect client
2097 mServiceLock.unlock();
2098 client->disconnect();
2099 mServiceLock.lock();
2100 } else {
2101 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002102 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002103 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002104
2105 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002106 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002107 } // lock is destroyed, allow further connect calls
2108
2109 // Important: release the mutex here so the client can call back into the service from its
2110 // destructor (can be at the end of the call)
2111 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002112
2113 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002114 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002115 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002116
Cliff Wud3a05312021-04-26 23:07:31 +08002117 {
2118 Mutex::Autolock lock(mInjectionParametersLock);
2119 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2120 mInjectionInitPending = false;
2121 status_t res = NO_ERROR;
2122 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2123 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002124 sp<BasicClient> clientSp = clientDescriptor->getValue();
2125 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2126 if(res != OK) {
2127 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2128 "No camera device with ID \"%s\" currently available",
2129 mInjectionExternalCamId.string());
2130 }
2131 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002132 if (res != OK) {
2133 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2134 }
2135 } else {
2136 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
2137 __FUNCTION__, mInjectionInternalCamId.string());
2138 res = NO_INIT;
2139 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2140 }
2141 }
2142 }
2143
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002144 return ret;
2145}
2146
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002147status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
2148 if (offlineClient.get() == nullptr) {
2149 return BAD_VALUE;
2150 }
2151
2152 {
2153 // Acquire mServiceLock and prevent other clients from connecting
2154 std::unique_ptr<AutoConditionLock> lock =
2155 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2156
2157 if (lock == nullptr) {
2158 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2159 , __FUNCTION__, offlineClient->getClientPid());
2160 return TIMED_OUT;
2161 }
2162
2163 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2164 if (onlineClientDesc.get() == nullptr) {
2165 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2166 cameraId.c_str());
2167 return BAD_VALUE;
2168 }
2169
2170 // Offline clients do not evict or conflict with other online devices. Resource sharing
2171 // conflicts are handled by the camera provider which will either succeed or fail before
2172 // reaching this method.
2173 const auto& onlinePriority = onlineClientDesc->getPriority();
2174 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2175 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
2176 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002177 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002178 // native clients don't have offline processing support.
2179 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002180 if (offlineClientDesc == nullptr) {
2181 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2182 return BAD_VALUE;
2183 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002184
2185 // Allow only one offline device per camera
2186 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2187 if (!incompatibleClients.empty()) {
2188 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2189 return BAD_VALUE;
2190 }
2191
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002192 String8 monitorTags = isClientWatched(offlineClient.get()) ? mMonitorTags : String8("");
2193 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002194 if (err != OK) {
2195 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2196 return err;
2197 }
2198
2199 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2200 if (evicted.size() > 0) {
2201 for (auto& i : evicted) {
2202 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
2203 __FUNCTION__, i->getKey().string());
2204 }
2205
2206 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2207 "properly", __FUNCTION__);
2208
2209 return BAD_VALUE;
2210 }
2211
2212 logConnectedOffline(offlineClientDesc->getKey(),
2213 static_cast<int>(offlineClientDesc->getOwnerId()),
2214 String8(offlineClient->getPackageName()));
2215
2216 sp<IBinder> remoteCallback = offlineClient->getRemote();
2217 if (remoteCallback != nullptr) {
2218 remoteCallback->linkToDeath(this);
2219 }
2220 } // lock is destroyed, allow further connect calls
2221
2222 return OK;
2223}
2224
Rucha Katakwar38284522021-11-10 11:25:21 -08002225Status CameraService::turnOnTorchWithStrengthLevel(const String16& cameraId, int32_t torchStrength,
2226 const sp<IBinder>& clientBinder) {
2227 Mutex::Autolock lock(mServiceLock);
2228
2229 ATRACE_CALL();
2230 if (clientBinder == nullptr) {
2231 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2232 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2233 "Torch client binder in null.");
2234 }
2235
2236 String8 id = String8(cameraId.string());
2237 int uid = CameraThreadState::getCallingUid();
2238
2239 if (shouldRejectSystemCameraConnection(id)) {
2240 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
2241 "for system only device %s: ", id.string());
2242 }
2243
2244 // verify id is valid
2245 auto state = getCameraState(id);
2246 if (state == nullptr) {
2247 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
2248 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2249 "Camera ID \"%s\" is a not valid camera ID", id.string());
2250 }
2251
2252 StatusInternal cameraStatus = state->getStatus();
2253 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2254 cameraStatus != StatusInternal::PRESENT) {
2255 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(),
2256 (int)cameraStatus);
2257 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2258 "Camera ID \"%s\" is a not valid camera ID", id.string());
2259 }
2260
2261 {
2262 Mutex::Autolock al(mTorchStatusMutex);
2263 TorchModeStatus status;
2264 status_t err = getTorchStatusLocked(id, &status);
2265 if (err != OK) {
2266 if (err == NAME_NOT_FOUND) {
2267 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2268 "Camera \"%s\" does not have a flash unit", id.string());
2269 }
2270 ALOGE("%s: getting current torch status failed for camera %s",
2271 __FUNCTION__, id.string());
2272 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2273 "Error changing torch strength level for camera \"%s\": %s (%d)",
2274 id.string(), strerror(-err), err);
2275 }
2276
2277 if (status == TorchModeStatus::NOT_AVAILABLE) {
2278 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2279 ALOGE("%s: torch mode of camera %s is not available because "
2280 "camera is in use.", __FUNCTION__, id.string());
2281 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2282 "Torch for camera \"%s\" is not available due to an existing camera user",
2283 id.string());
2284 } else {
2285 ALOGE("%s: torch mode of camera %s is not available due to "
2286 "insufficient resources", __FUNCTION__, id.string());
2287 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2288 "Torch for camera \"%s\" is not available due to insufficient resources",
2289 id.string());
2290 }
2291 }
2292 }
2293
2294 {
2295 Mutex::Autolock al(mTorchUidMapMutex);
2296 updateTorchUidMapLocked(cameraId, uid);
2297 }
2298 // Check if the current torch strength level is same as the new one.
2299 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
2300 id.string(), torchStrength);
2301
2302 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(id, torchStrength);
2303
2304 if (err != OK) {
2305 int32_t errorCode;
2306 String8 msg;
2307 switch (err) {
2308 case -ENOSYS:
2309 msg = String8::format("Camera \"%s\" has no flashlight.",
2310 id.string());
2311 errorCode = ERROR_ILLEGAL_ARGUMENT;
2312 break;
2313 case -EBUSY:
2314 msg = String8::format("Camera \"%s\" is in use",
2315 id.string());
2316 errorCode = ERROR_CAMERA_IN_USE;
2317 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002318 case -EINVAL:
2319 msg = String8::format("Torch strength level %d is not within the "
2320 "valid range.", torchStrength);
2321 errorCode = ERROR_ILLEGAL_ARGUMENT;
2322 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002323 default:
2324 msg = String8::format("Changing torch strength level failed.");
2325 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002326 }
2327 ALOGE("%s: %s", __FUNCTION__, msg.string());
2328 return STATUS_ERROR(errorCode, msg.string());
2329 }
2330
2331 {
2332 // update the link to client's death
2333 // Store the last client that turns on each camera's torch mode.
2334 Mutex::Autolock al(mTorchClientMapMutex);
2335 ssize_t index = mTorchClientMap.indexOfKey(id);
2336 if (index == NAME_NOT_FOUND) {
2337 mTorchClientMap.add(id, clientBinder);
2338 } else {
2339 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2340 mTorchClientMap.replaceValueAt(index, clientBinder);
2341 }
2342 clientBinder->linkToDeath(this);
2343 }
2344
2345 int clientPid = CameraThreadState::getCallingPid();
2346 const char *id_cstr = id.c_str();
2347 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
2348 __FUNCTION__, id_cstr, torchStrength, clientPid);
2349 if (!shouldSkipTorchStrengthUpdates) {
2350 broadcastTorchStrengthLevel(id, torchStrength);
2351 }
2352 return Status::ok();
2353}
2354
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002355Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002356 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002357 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002358
2359 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002360 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002361 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002362 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2363 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002364 }
2365
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002366 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07002367 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002368
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002369 if (shouldRejectSystemCameraConnection(id)) {
2370 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
2371 " for system only device %s: ", id.string());
2372 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002373 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08002374 auto state = getCameraState(id);
2375 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002376 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002377 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2378 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002379 }
2380
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002381 StatusInternal cameraStatus = state->getStatus();
2382 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002383 cameraStatus != StatusInternal::NOT_AVAILABLE) {
2384 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002385 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2386 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002387 }
2388
2389 {
2390 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002391 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002392 status_t err = getTorchStatusLocked(id, &status);
2393 if (err != OK) {
2394 if (err == NAME_NOT_FOUND) {
2395 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2396 "Camera \"%s\" does not have a flash unit", id.string());
2397 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002398 ALOGE("%s: getting current torch status failed for camera %s",
2399 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002400 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2401 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
2402 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002403 }
2404
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002405 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002406 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002407 ALOGE("%s: torch mode of camera %s is not available because "
2408 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002409 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2410 "Torch for camera \"%s\" is not available due to an existing camera user",
2411 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002412 } else {
2413 ALOGE("%s: torch mode of camera %s is not available due to "
2414 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002415 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2416 "Torch for camera \"%s\" is not available due to insufficient resources",
2417 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002418 }
2419 }
2420 }
2421
Ruben Brunk99e69712015-05-26 17:25:07 -07002422 {
2423 // Update UID map - this is used in the torch status changed callbacks, so must be done
2424 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002425 Mutex::Autolock al(mTorchUidMapMutex);
Rucha Katakwar38284522021-11-10 11:25:21 -08002426 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07002427 }
2428
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002429 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002430
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002431 if (err != OK) {
2432 int32_t errorCode;
2433 String8 msg;
2434 switch (err) {
2435 case -ENOSYS:
2436 msg = String8::format("Camera \"%s\" has no flashlight",
2437 id.string());
2438 errorCode = ERROR_ILLEGAL_ARGUMENT;
2439 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08002440 case -EBUSY:
2441 msg = String8::format("Camera \"%s\" is in use",
2442 id.string());
2443 errorCode = ERROR_CAMERA_IN_USE;
2444 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002445 default:
2446 msg = String8::format(
2447 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
2448 id.string(), enabled, strerror(-err), err);
2449 errorCode = ERROR_INVALID_OPERATION;
2450 }
2451 ALOGE("%s: %s", __FUNCTION__, msg.string());
Rucha Katakward9ea6452021-05-06 11:57:16 -07002452 logServiceError(msg,errorCode);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002453 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002454 }
2455
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002456 {
2457 // update the link to client's death
2458 Mutex::Autolock al(mTorchClientMapMutex);
2459 ssize_t index = mTorchClientMap.indexOfKey(id);
2460 if (enabled) {
2461 if (index == NAME_NOT_FOUND) {
2462 mTorchClientMap.add(id, clientBinder);
2463 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07002464 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002465 mTorchClientMap.replaceValueAt(index, clientBinder);
2466 }
2467 clientBinder->linkToDeath(this);
2468 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07002469 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002470 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002471 }
2472
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002473 int clientPid = CameraThreadState::getCallingPid();
2474 const char *id_cstr = id.c_str();
2475 const char *torchState = enabled ? "on" : "off";
2476 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
2477 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002478 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002479}
2480
Rucha Katakwar38284522021-11-10 11:25:21 -08002481void CameraService::updateTorchUidMapLocked(const String16& cameraId, int uid) {
2482 String8 id = String8(cameraId.string());
2483 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
2484 mTorchUidMap[id].first = uid;
2485 mTorchUidMap[id].second = uid;
2486 } else {
2487 // Set the pending UID
2488 mTorchUidMap[id].first = uid;
2489 }
2490}
2491
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002492Status CameraService::notifySystemEvent(int32_t eventId,
2493 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002494 const int pid = CameraThreadState::getCallingPid();
2495 const int selfPid = getpid();
2496
2497 // Permission checks
2498 if (pid != selfPid) {
2499 // Ensure we're being called by system_server, or similar process with
2500 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002501 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002502 const int uid = CameraThreadState::getCallingUid();
2503 ALOGE("Permission Denial: cannot send updates to camera service about system"
2504 " events from pid=%d, uid=%d", pid, uid);
2505 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09002506 "No permission to send updates to camera service about system events"
2507 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002508 }
2509 }
2510
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002511 ATRACE_CALL();
2512
Ruben Brunk36597b22015-03-20 22:15:57 -07002513 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002514 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002515 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002516 // from a system server crash
2517 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002518 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002519 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002520 break;
2521 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02002522 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
2523 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
2524 // Notify CameraProviderManager for lazy HALs
2525 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
2526 std::to_string(args[0]));
2527 break;
2528 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002529 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002530 default: {
2531 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2532 eventId);
2533 break;
2534 }
2535 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002536 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002537}
2538
Emilian Peev53722fa2019-02-22 17:47:20 -08002539void CameraService::notifyMonitoredUids() {
2540 Mutex::Autolock lock(mStatusListenerLock);
2541
2542 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002543 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07002544 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
2545 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08002546 }
2547}
2548
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002549Status CameraService::notifyDeviceStateChange(int64_t newState) {
2550 const int pid = CameraThreadState::getCallingPid();
2551 const int selfPid = getpid();
2552
2553 // Permission checks
2554 if (pid != selfPid) {
2555 // Ensure we're being called by system_server, or similar process with
2556 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002557 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002558 const int uid = CameraThreadState::getCallingUid();
2559 ALOGE("Permission Denial: cannot send updates to camera service about device"
2560 " state changes from pid=%d, uid=%d", pid, uid);
2561 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2562 "No permission to send updates to camera service about device state"
2563 " changes from pid=%d, uid=%d", pid, uid);
2564 }
2565 }
2566
2567 ATRACE_CALL();
2568
Austin Borger18b30a72022-10-27 12:20:29 -07002569 {
2570 Mutex::Autolock lock(mServiceLock);
2571 mDeviceState = newState;
2572 }
2573
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07002574 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002575
2576 return Status::ok();
2577}
2578
Emilian Peev8b64f282021-03-25 16:49:57 -07002579Status CameraService::notifyDisplayConfigurationChange() {
2580 ATRACE_CALL();
2581 const int callingPid = CameraThreadState::getCallingPid();
2582 const int selfPid = getpid();
2583
2584 // Permission checks
2585 if (callingPid != selfPid) {
2586 // Ensure we're being called by system_server, or similar process with
2587 // permissions to notify the camera service about system events
2588 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2589 const int uid = CameraThreadState::getCallingUid();
2590 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2591 " changes from pid=%d, uid=%d", callingPid, uid);
2592 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2593 "No permission to send updates to camera service about orientation"
2594 " changes from pid=%d, uid=%d", callingPid, uid);
2595 }
2596 }
2597
2598 Mutex::Autolock lock(mServiceLock);
2599
2600 // Don't do anything if rotate-and-crop override via cmd is active
2601 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2602
2603 const auto clients = mActiveClientManager.getAll();
2604 for (auto& current : clients) {
2605 if (current != nullptr) {
2606 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07002607 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
2608 basicClient->setRotateAndCropOverride(
2609 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2610 basicClient->getPackageName(),
2611 basicClient->getCameraFacing(),
2612 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07002613 }
2614 }
2615 }
2616
2617 return Status::ok();
2618}
2619
2620Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002621 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2622 ATRACE_CALL();
2623 if (!concurrentCameraIds) {
2624 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2625 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2626 }
2627
2628 if (!mInitialized) {
2629 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002630 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002631 return STATUS_ERROR(ERROR_DISCONNECTED,
2632 "Camera subsystem is not available");
2633 }
2634 // First call into the provider and get the set of concurrent camera
2635 // combinations
2636 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002637 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002638 for (auto &combination : concurrentCameraCombinations) {
2639 std::vector<std::string> validCombination;
2640 for (auto &cameraId : combination) {
2641 // if the camera state is not present, skip
2642 String8 cameraIdStr(cameraId.c_str());
2643 auto state = getCameraState(cameraIdStr);
2644 if (state == nullptr) {
2645 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2646 continue;
2647 }
2648 StatusInternal status = state->getStatus();
2649 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2650 continue;
2651 }
2652 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2653 continue;
2654 }
2655 validCombination.push_back(cameraId);
2656 }
2657 if (validCombination.size() != 0) {
2658 concurrentCameraIds->push_back(std::move(validCombination));
2659 }
2660 }
2661 return Status::ok();
2662}
2663
2664Status CameraService::isConcurrentSessionConfigurationSupported(
2665 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002666 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002667 if (!isSupported) {
2668 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2669 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2670 }
2671
2672 if (!mInitialized) {
2673 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2674 return STATUS_ERROR(ERROR_DISCONNECTED,
2675 "Camera subsystem is not available");
2676 }
2677
2678 // Check for camera permissions
2679 int callingPid = CameraThreadState::getCallingPid();
2680 int callingUid = CameraThreadState::getCallingUid();
2681 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2682 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2683 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2684 "android.permission.CAMERA needed to call"
2685 "isConcurrentSessionConfigurationSupported");
2686 }
2687
2688 status_t res =
2689 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002690 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
2691 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002692 if (res != OK) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07002693 logServiceError(String8::format("Unable to query session configuration support"),
2694 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002695 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2696 "support %s (%d)", strerror(-res), res);
2697 }
2698 return Status::ok();
2699}
2700
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002701Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2702 /*out*/
2703 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002704 return addListenerHelper(listener, cameraStatuses);
2705}
2706
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002707binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2708 std::vector<hardware::CameraStatus>* cameraStatuses) {
2709 return addListenerHelper(listener, cameraStatuses, false, true);
2710}
2711
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002712Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2713 /*out*/
2714 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002715 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002716
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002717 ATRACE_CALL();
2718
Igor Murashkinbfc99152013-02-27 12:55:20 -08002719 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002720
Ruben Brunk3450ba72015-06-16 11:00:37 -07002721 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002722 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002723 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002724 }
2725
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002726 auto clientUid = CameraThreadState::getCallingUid();
2727 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002728 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
Jayant Chowdharyc3198c32021-07-28 20:59:14 +00002729 clientPid, clientUid, /*logPermissionFailure*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002730
Igor Murashkinbfc99152013-02-27 12:55:20 -08002731 Mutex::Autolock lock(mServiceLock);
2732
Ruben Brunkcc776712015-02-17 20:18:47 -08002733 {
2734 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002735 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002736 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002737 ALOGW("%s: Tried to add listener %p which was already subscribed",
2738 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002739 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002740 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002741 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002742
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002743 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002744 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2745 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002746 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08002747 if (ret != NO_ERROR) {
2748 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2749 strerror(-ret), ret);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002750 logServiceError(msg,ERROR_ILLEGAL_ARGUMENT);
Emilian Peev53722fa2019-02-22 17:47:20 -08002751 ALOGE("%s: %s", __FUNCTION__, msg.string());
2752 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2753 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002754 // The listener still needs to be added to the list of listeners, regardless of what
2755 // permissions the listener process has / whether it is a vendor listener. Since it might be
2756 // eligible to listen to other camera ids.
2757 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002758 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002759 }
2760
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002761 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002762 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002763 Mutex::Autolock lock(mCameraStatesLock);
2764 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002765 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07002766 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
2767 openCloseCallbackAllowed ? i.second->getClientPackage() : String8::empty());
Igor Murashkincba2c162013-03-20 15:56:31 -07002768 }
2769 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002770 // Remove the camera statuses that should be hidden from the client, we do
2771 // this after collecting the states in order to avoid holding
2772 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2773 // the same time.
2774 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2775 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2776 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2777 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2778 ALOGE("%s: Invalid camera id %s, skipping status update",
2779 __FUNCTION__, s.cameraId.c_str());
2780 return true;
2781 }
2782 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2783 clientUid);}), cameraStatuses->end());
2784
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002785 //cameraStatuses will have non-eligible camera ids removed.
2786 std::set<String16> idsChosenForCallback;
2787 for (const auto &s : *cameraStatuses) {
2788 idsChosenForCallback.insert(String16(s.cameraId));
2789 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002790
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002791 /*
2792 * Immediately signal current torch status to this listener only
2793 * This may be a subset of all the devices, so don't include it in the response directly
2794 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002795 {
2796 Mutex::Autolock al(mTorchStatusMutex);
2797 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002798 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002799 // The camera id is visible to the client. Fine to send torch
2800 // callback.
2801 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2802 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2803 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002804 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002805 }
2806
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002807 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002808}
Ruben Brunkcc776712015-02-17 20:18:47 -08002809
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002810Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002811 ATRACE_CALL();
2812
Igor Murashkinbfc99152013-02-27 12:55:20 -08002813 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2814
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002815 if (listener == 0) {
2816 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002817 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002818 }
2819
Igor Murashkinbfc99152013-02-27 12:55:20 -08002820 Mutex::Autolock lock(mServiceLock);
2821
Ruben Brunkcc776712015-02-17 20:18:47 -08002822 {
2823 Mutex::Autolock lock(mStatusListenerLock);
2824 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002825 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2826 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2827 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002828 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002829 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002830 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002831 }
2832 }
2833
2834 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2835 __FUNCTION__, listener.get());
2836
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002837 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002838}
2839
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002840Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002841
2842 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002843 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2844
2845 if (parameters == NULL) {
2846 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002847 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002848 }
2849
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002850 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002851
2852 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002853 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002854 // Error logged by caller
2855 return ret;
2856 }
2857
2858 String8 shimParamsString8 = shimParams.flatten();
2859 String16 shimParamsString16 = String16(shimParamsString8);
2860
2861 *parameters = shimParamsString16;
2862
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002863 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002864}
2865
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002866Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2867 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002868 ATRACE_CALL();
2869
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002870 const String8 id = String8(cameraId);
2871
2872 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002873
2874 switch (apiVersion) {
2875 case API_VERSION_1:
2876 case API_VERSION_2:
2877 break;
2878 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002879 String8 msg = String8::format("Unknown API version %d", apiVersion);
2880 ALOGE("%s: %s", __FUNCTION__, msg.string());
2881 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002882 }
2883
Austin Borger18b30a72022-10-27 12:20:29 -07002884 int portraitRotation;
2885 auto deviceVersionAndTransport = getDeviceVersion(id, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002886 if (deviceVersionAndTransport.first == -1) {
2887 String8 msg = String8::format("Unknown camera ID %s", id.string());
2888 ALOGE("%s: %s", __FUNCTION__, msg.string());
2889 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2890 }
2891 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
2892 int deviceVersion = deviceVersionAndTransport.first;
2893 switch (deviceVersion) {
2894 case CAMERA_DEVICE_API_VERSION_1_0:
2895 case CAMERA_DEVICE_API_VERSION_3_0:
2896 case CAMERA_DEVICE_API_VERSION_3_1:
2897 if (apiVersion == API_VERSION_2) {
2898 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
2899 "shim", __FUNCTION__, id.string(), deviceVersion);
2900 *isSupported = false;
2901 } else { // if (apiVersion == API_VERSION_1) {
2902 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
2903 "supported", __FUNCTION__, id.string());
2904 *isSupported = true;
2905 }
2906 break;
2907 case CAMERA_DEVICE_API_VERSION_3_2:
2908 case CAMERA_DEVICE_API_VERSION_3_3:
2909 case CAMERA_DEVICE_API_VERSION_3_4:
2910 case CAMERA_DEVICE_API_VERSION_3_5:
2911 case CAMERA_DEVICE_API_VERSION_3_6:
2912 case CAMERA_DEVICE_API_VERSION_3_7:
2913 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002914 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002915 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002916 break;
2917 default: {
2918 String8 msg = String8::format("Unknown device version %x for device %s",
2919 deviceVersion, id.string());
2920 ALOGE("%s: %s", __FUNCTION__, msg.string());
2921 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002922 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002923 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002924 } else {
2925 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002926 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002927 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002928}
2929
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002930Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2931 /*out*/ bool *isSupported) {
2932 ATRACE_CALL();
2933
2934 const String8 id = String8(cameraId);
2935
2936 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2937 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2938
2939 return Status::ok();
2940}
2941
Cliff Wud8cae102021-03-11 01:37:42 +08002942Status CameraService::injectCamera(
2943 const String16& packageName, const String16& internalCamId,
2944 const String16& externalCamId,
2945 const sp<ICameraInjectionCallback>& callback,
2946 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08002947 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08002948 ATRACE_CALL();
2949
2950 if (!checkCallingPermission(sCameraInjectExternalCameraPermission)) {
2951 const int pid = CameraThreadState::getCallingPid();
2952 const int uid = CameraThreadState::getCallingUid();
2953 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
2954 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2955 "Permission Denial: no permission to inject camera");
2956 }
2957
2958 ALOGV(
2959 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
2960 "%s",
2961 __FUNCTION__, String8(packageName).string(),
2962 String8(internalCamId).string(), String8(externalCamId).string());
2963
Cliff Wud3a05312021-04-26 23:07:31 +08002964 {
2965 Mutex::Autolock lock(mInjectionParametersLock);
2966 mInjectionInternalCamId = String8(internalCamId);
2967 mInjectionExternalCamId = String8(externalCamId);
Cliff Wu646bd612021-11-23 23:21:29 +08002968 mInjectionStatusListener->addListener(callback);
2969 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08002970 status_t res = NO_ERROR;
2971 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2972 // If the client already exists, we can directly connect to the camera device through the
2973 // client's injectCamera(), otherwise we need to wait until the client is established
2974 // (execute connectHelper()) before injecting the camera to the camera device.
2975 if (clientDescriptor != nullptr) {
2976 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08002977 sp<BasicClient> clientSp = clientDescriptor->getValue();
2978 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2979 if(res != OK) {
2980 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2981 "No camera device with ID \"%s\" currently available",
2982 mInjectionExternalCamId.string());
2983 }
2984 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002985 if(res != OK) {
2986 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2987 }
2988 } else {
2989 mInjectionInitPending = true;
2990 }
2991 }
Cliff Wud8cae102021-03-11 01:37:42 +08002992
Cliff Wud3a05312021-04-26 23:07:31 +08002993 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08002994}
2995
Ruben Brunkcc776712015-02-17 20:18:47 -08002996void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002997 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002998 for (auto& i : mActiveClientManager.getAll()) {
2999 auto clientSp = i->getValue();
3000 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003001 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003002 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003003 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003004 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003005 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003006}
3007
Ruben Brunkcc776712015-02-17 20:18:47 -08003008bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003009 bool ret = false;
3010 {
3011 // Acquire mServiceLock and prevent other clients from connecting
3012 std::unique_ptr<AutoConditionLock> lock =
3013 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003014
Igor Murashkin634a5152013-02-20 17:15:11 -08003015
Ruben Brunkcc776712015-02-17 20:18:47 -08003016 std::vector<sp<BasicClient>> evicted;
3017 for (auto& i : mActiveClientManager.getAll()) {
3018 auto clientSp = i->getValue();
3019 if (clientSp.get() == nullptr) {
3020 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3021 mActiveClientManager.remove(i);
3022 continue;
3023 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003024 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003025 mActiveClientManager.remove(i);
3026 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003027
Ruben Brunkcc776712015-02-17 20:18:47 -08003028 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003029 clientSp->notifyError(
3030 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003031 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003032 }
3033 }
3034
Ruben Brunkcc776712015-02-17 20:18:47 -08003035 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3036 // other clients from connecting in mServiceLockWrapper if held
3037 mServiceLock.unlock();
3038
Ruben Brunk36597b22015-03-20 22:15:57 -07003039 // Do not clear caller identity, remote caller should be client proccess
3040
Ruben Brunkcc776712015-02-17 20:18:47 -08003041 for (auto& i : evicted) {
3042 if (i.get() != nullptr) {
3043 i->disconnect();
3044 ret = true;
3045 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003046 }
3047
Ruben Brunkcc776712015-02-17 20:18:47 -08003048 // Reacquire mServiceLock
3049 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003050
Ruben Brunkcc776712015-02-17 20:18:47 -08003051 } // lock is destroyed, allow further connect calls
3052
3053 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003054}
3055
Ruben Brunkcc776712015-02-17 20:18:47 -08003056std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
3057 const String8& cameraId) const {
3058 std::shared_ptr<CameraState> state;
3059 {
3060 Mutex::Autolock lock(mCameraStatesLock);
3061 auto iter = mCameraStates.find(cameraId);
3062 if (iter != mCameraStates.end()) {
3063 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003064 }
3065 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003066 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003067}
3068
Ruben Brunkcc776712015-02-17 20:18:47 -08003069sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
3070 // Remove from active clients list
3071 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3072 if (clientDescriptorPtr == nullptr) {
3073 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
3074 cameraId.string());
3075 return sp<BasicClient>{nullptr};
3076 }
3077
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003078 sp<BasicClient> client = clientDescriptorPtr->getValue();
3079 if (client.get() != nullptr) {
3080 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3081 }
3082 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003083}
3084
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003085void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003086 // Acquire mServiceLock and prevent other clients from connecting
3087 std::unique_ptr<AutoConditionLock> lock =
3088 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3089
Ruben Brunk6267b532015-04-30 17:44:07 -07003090 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003091 for (size_t i = 0; i < newUserIds.size(); i++) {
3092 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003093 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003094 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003095 return;
3096 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003097 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003098 }
3099
Ruben Brunka8ca9152015-04-07 14:23:40 -07003100
Ruben Brunk6267b532015-04-30 17:44:07 -07003101 if (newAllowedUsers == mAllowedUsers) {
3102 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3103 return;
3104 }
3105
3106 logUserSwitch(mAllowedUsers, newAllowedUsers);
3107
3108 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003109
3110 // Current user has switched, evict all current clients.
3111 std::vector<sp<BasicClient>> evicted;
3112 for (auto& i : mActiveClientManager.getAll()) {
3113 auto clientSp = i->getValue();
3114
3115 if (clientSp.get() == nullptr) {
3116 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3117 continue;
3118 }
3119
Ruben Brunk6267b532015-04-30 17:44:07 -07003120 // Don't evict clients that are still allowed.
3121 uid_t clientUid = clientSp->getClientUid();
3122 userid_t clientUserId = multiuser_get_user_id(clientUid);
3123 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3124 continue;
3125 }
3126
Ruben Brunk36597b22015-03-20 22:15:57 -07003127 evicted.push_back(clientSp);
3128
3129 String8 curTime = getFormattedCurrentTime();
3130
3131 ALOGE("Evicting conflicting client for camera ID %s due to user change",
3132 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003133
Ruben Brunk36597b22015-03-20 22:15:57 -07003134 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07003135 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003136 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
3137 " to user switch.", i->getKey().string(),
3138 String8{clientSp->getPackageName()}.string(),
3139 i->getOwnerId(), i->getPriority().getScore(),
3140 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003141
3142 }
3143
3144 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3145 // blocking other clients from connecting in mServiceLockWrapper if held.
3146 mServiceLock.unlock();
3147
3148 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07003149 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003150
3151 for (auto& i : evicted) {
3152 i->disconnect();
3153 }
3154
Jayant Chowdhary12361932018-08-27 14:46:13 -07003155 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003156
3157 // Reacquire mServiceLock
3158 mServiceLock.lock();
3159}
Ruben Brunkcc776712015-02-17 20:18:47 -08003160
Ruben Brunka8ca9152015-04-07 14:23:40 -07003161void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003162 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003163 Mutex::Autolock l(mLogLock);
Rucha Katakward9ea6452021-05-06 11:57:16 -07003164 String8 msg = String8::format("%s : %s", curTime.string(), event);
3165 // For service error events, print the msg only once.
3166 if(!msg.contains("SERVICE ERROR")) {
3167 mEventLog.add(msg);
3168 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3169 // Error event not added to the dumpsys log before
3170 mEventLog.add(msg);
3171 sServiceErrorEventSet.insert(msg);
3172 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003173}
3174
Ruben Brunka8ca9152015-04-07 14:23:40 -07003175void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003176 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003177 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07003178 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003179 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003180}
3181
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003182void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
3183 const char* clientPackage) {
3184 // Log the clients evicted
3185 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
3186 cameraId, clientPackage, clientPid));
3187}
3188
Ruben Brunka8ca9152015-04-07 14:23:40 -07003189void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003190 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003191 // Log the clients evicted
3192 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003193 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003194}
3195
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003196void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
3197 const char* clientPackage) {
3198 // Log the clients evicted
3199 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
3200 clientPackage, clientPid));
3201}
3202
Ruben Brunka8ca9152015-04-07 14:23:40 -07003203void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003204 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003205 // Log the client rejected
3206 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003207 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003208}
3209
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003210void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
3211 // Log torch event
3212 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
3213 torchState, clientPid));
3214}
3215
Ruben Brunk6267b532015-04-30 17:44:07 -07003216void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3217 const std::set<userid_t>& newUserIds) {
3218 String8 newUsers = toString(newUserIds);
3219 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003220 if (oldUsers.size() == 0) {
3221 oldUsers = "<None>";
3222 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003223 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003224 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07003225 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003226}
3227
3228void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
3229 // Log the device removal
3230 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
3231}
3232
3233void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
3234 // Log the device removal
3235 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
3236}
3237
3238void CameraService::logClientDied(int clientPid, const char* reason) {
3239 // Log the device removal
3240 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003241}
3242
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003243void CameraService::logServiceError(const char* msg, int errorCode) {
3244 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003245 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003246}
3247
Ruben Brunk36597b22015-03-20 22:15:57 -07003248status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3249 uint32_t flags) {
3250
Mathias Agopian65ab4712010-07-14 17:59:35 -07003251 // Permission checks
3252 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003253 case SHELL_COMMAND_TRANSACTION: {
3254 int in = data.readFileDescriptor();
3255 int out = data.readFileDescriptor();
3256 int err = data.readFileDescriptor();
3257 int argc = data.readInt32();
3258 Vector<String16> args;
3259 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3260 args.add(data.readString16());
3261 }
3262 sp<IBinder> unusedCallback;
3263 sp<IResultReceiver> resultReceiver;
3264 status_t status;
3265 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3266 return status;
3267 }
3268 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3269 return status;
3270 }
3271 status = shellCommand(in, out, err, args);
3272 if (resultReceiver != nullptr) {
3273 resultReceiver->send(status);
3274 }
3275 return NO_ERROR;
3276 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003277 }
3278
3279 return BnCameraService::onTransact(code, data, reply, flags);
3280}
3281
Mathias Agopian65ab4712010-07-14 17:59:35 -07003282// We share the media players for shutter and recording sound for all clients.
3283// A reference count is kept to determine when we will actually release the
3284// media players.
3285
Jaekyun Seokef498052018-03-23 13:09:44 +09003286sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3287 sp<MediaPlayer> mp = new MediaPlayer();
3288 status_t error;
3289 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003290 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003291 error = mp->prepare();
3292 }
3293 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003294 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003295 mp->disconnect();
3296 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003297 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003298 }
3299 return mp;
3300}
3301
username5755fea2018-12-27 09:48:08 +08003302void CameraService::increaseSoundRef() {
3303 Mutex::Autolock lock(mSoundLock);
3304 mSoundRef++;
3305}
3306
3307void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003308 ATRACE_CALL();
3309
username5755fea2018-12-27 09:48:08 +08003310 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3311 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3312 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3313 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3314 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3315 }
3316 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3317 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3318 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3319 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003320 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003321 }
3322 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3323 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3324 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3325 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3326 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003327 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003328}
3329
username5755fea2018-12-27 09:48:08 +08003330void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003331 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003332 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003333 if (--mSoundRef) return;
3334
3335 for (int i = 0; i < NUM_SOUNDS; i++) {
3336 if (mSoundPlayer[i] != 0) {
3337 mSoundPlayer[i]->disconnect();
3338 mSoundPlayer[i].clear();
3339 }
3340 }
3341}
3342
3343void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003344 ATRACE_CALL();
3345
Mathias Agopian65ab4712010-07-14 17:59:35 -07003346 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07003347 if (kind < 0 || kind >= NUM_SOUNDS) {
3348 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
3349 return;
3350 }
3351
Mathias Agopian65ab4712010-07-14 17:59:35 -07003352 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003353 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003354 sp<MediaPlayer> player = mSoundPlayer[kind];
3355 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08003356 player->seekTo(0);
3357 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003358 }
3359}
3360
3361// ----------------------------------------------------------------------------
3362
3363CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07003364 const sp<ICameraClient>& cameraClient,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003365 const String16& clientPackageName, bool systemNativeClient,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003366 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003367 const String8& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003368 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003369 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003370 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003371 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003372 IInterface::asBinder(cameraClient),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003373 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003374 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003375 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003376 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003377 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003378{
Jayant Chowdhary12361932018-08-27 14:46:13 -07003379 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003380 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003381
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003382 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003383
username5755fea2018-12-27 09:48:08 +08003384 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003385
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003386 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003387}
3388
Mathias Agopian65ab4712010-07-14 17:59:35 -07003389// tear down the client
3390CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003391 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08003392 mDestructionStarted = true;
3393
username5755fea2018-12-27 09:48:08 +08003394 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003395 // unconditionally disconnect. function is idempotent
3396 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003397}
3398
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003399sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
3400
Igor Murashkin634a5152013-02-20 17:15:11 -08003401CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003402 const sp<IBinder>& remoteCallback,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003403 const String16& clientPackageName, bool nativeClient,
3404 const std::optional<String16>& clientFeatureId, const String8& cameraIdStr,
3405 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003406 int servicePid, bool overrideToPortrait):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003407 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07003408 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003409 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
3410 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003411 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003412 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07003413 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07003414 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003415 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003416 mRemoteBinder(remoteCallback),
3417 mOpsActive(false),
3418 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08003419{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003420 if (sCameraService == nullptr) {
3421 sCameraService = cameraService;
3422 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08003423
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003424 // There are 2 scenarios in which a client won't have AppOps operations
3425 // (both scenarios : native clients)
3426 // 1) It's an system native client*, the package name will be empty
3427 // and it will return from this function in the previous if condition
3428 // (This is the same as the previously existing behavior).
3429 // 2) It is a system native client, but its package name has been
3430 // modified for debugging, however it still must not use AppOps since
3431 // the package name is not a real one.
3432 //
3433 // * system native client - native client with UID < AID_APP_START. It
3434 // doesn't exclude clients not on the system partition.
3435 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003436 mAppOpsManager = std::make_unique<AppOpsManager>();
3437 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07003438
3439 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08003440}
3441
3442CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003443 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08003444 mDestructionStarted = true;
3445}
3446
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003447binder::Status CameraService::BasicClient::disconnect() {
3448 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003449 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003450 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07003451 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07003452 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08003453
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003454 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003455 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07003456 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
3457 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003458
3459 sp<IBinder> remote = getRemote();
3460 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003461 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08003462 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003463
3464 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07003465 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003466 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
3467 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
3468 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003469
Igor Murashkincba2c162013-03-20 15:56:31 -07003470 // client shouldn't be able to call into us anymore
3471 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003472
3473 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08003474}
3475
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003476status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
3477 // No dumping of clients directly over Binder,
3478 // must go through CameraService::dump
3479 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003480 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003481 return OK;
3482}
3483
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07003484status_t CameraService::BasicClient::startWatchingTags(const String8&, int) {
3485 // Can't watch tags directly, must go through CameraService::startWatchingTags
3486 return OK;
3487}
3488
3489status_t CameraService::BasicClient::stopWatchingTags(int) {
3490 // Can't watch tags directly, must go through CameraService::stopWatchingTags
3491 return OK;
3492}
3493
3494status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
3495 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
3496 return OK;
3497}
3498
Ruben Brunkcc776712015-02-17 20:18:47 -08003499String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003500 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08003501}
3502
Emilian Peev8b64f282021-03-25 16:49:57 -07003503int CameraService::BasicClient::getCameraFacing() const {
3504 return mCameraFacing;
3505}
3506
3507int CameraService::BasicClient::getCameraOrientation() const {
3508 return mOrientation;
3509}
Ruben Brunkcc776712015-02-17 20:18:47 -08003510
3511int CameraService::BasicClient::getClientPid() const {
3512 return mClientPid;
3513}
3514
Ruben Brunk6267b532015-04-30 17:44:07 -07003515uid_t CameraService::BasicClient::getClientUid() const {
3516 return mClientUid;
3517}
3518
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003519bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
3520 // Defaults to API2.
3521 return level == API_2;
3522}
3523
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003524status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003525 {
3526 Mutex::Autolock l(mAudioRestrictionLock);
3527 mAudioRestriction = mode;
3528 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003529 sCameraService->updateAudioRestriction();
3530 return OK;
3531}
3532
3533int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003534 return sCameraService->updateAudioRestriction();
3535}
3536
3537int32_t CameraService::BasicClient::getAudioRestriction() const {
3538 Mutex::Autolock l(mAudioRestrictionLock);
3539 return mAudioRestriction;
3540}
3541
3542bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
3543 switch (mode) {
3544 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
3545 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
3546 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
3547 return true;
3548 default:
3549 return false;
3550 }
3551}
3552
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003553status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
3554 if (mode == AppOpsManager::MODE_ERRORED) {
3555 ALOGI("Camera %s: Access for \"%s\" has been revoked",
3556 mCameraIdStr.string(), String8(mClientPackageName).string());
3557 return PERMISSION_DENIED;
3558 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
3559 // If the calling Uid is trusted (a native service), the AppOpsManager could
3560 // return MODE_IGNORED. Do not treat such case as error.
3561 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
3562 mClientPackageName);
3563 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08003564 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayana8143e572023-01-09 08:46:49 -08003565 // We don't want to return EACCESS if the CameraPrivacy is enabled.
3566 // We prefer to successfully open the camera and perform camera muting
3567 // or blocking in connectHelper as handleAppOpMode can be called before the
3568 // connection has been fully established and at that time camera muting
3569 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003570 if (!isUidActive || !isCameraPrivacyEnabled) {
3571 ALOGI("Camera %s: Access for \"%s\" has been restricted",
3572 mCameraIdStr.string(), String8(mClientPackageName).string());
3573 // Return the same error as for device policy manager rejection
3574 return -EACCES;
3575 }
3576 }
3577 return OK;
3578}
3579
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003580status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003581 ATRACE_CALL();
3582
Igor Murashkine6800ce2013-03-04 17:25:57 -08003583 {
3584 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003585 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003586 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003587 if (mAppOpsManager != nullptr) {
3588 // Notify app ops that the camera is not available
3589 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003590 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
3591 mClientPackageName, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003592
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003593 // Just check for camera acccess here on open - delay startOp until
3594 // camera frames start streaming in startCameraStreamingOps
3595 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
3596 mClientPackageName);
3597 status_t res = handleAppOpMode(mode);
3598 if (res != OK) {
3599 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003600 }
Svetoslav28e8ef72015-05-11 19:21:31 -07003601 }
3602
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003603 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003604
3605 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003606 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003607
Emilian Peev53722fa2019-02-22 17:47:20 -08003608 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
3609
Shuzhen Wang695044d2020-03-06 09:02:23 -08003610 // Notify listeners of camera open/close status
3611 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
3612
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003613 return OK;
3614}
3615
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003616status_t CameraService::BasicClient::startCameraStreamingOps() {
3617 ATRACE_CALL();
3618
3619 if (!mOpsActive) {
3620 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3621 return INVALID_OPERATION;
3622 }
3623 if (mOpsStreaming) {
3624 ALOGV("%s: Streaming already active!", __FUNCTION__);
3625 return OK;
3626 }
3627
3628 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
3629 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3630
3631 if (mAppOpsManager != nullptr) {
3632 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
3633 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
3634 String16("start camera ") + String16(mCameraIdStr));
3635 status_t res = handleAppOpMode(mode);
3636 if (res != OK) {
3637 return res;
3638 }
3639 }
3640
3641 mOpsStreaming = true;
3642
3643 return OK;
3644}
3645
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003646status_t CameraService::BasicClient::noteAppOp() {
3647 ATRACE_CALL();
3648
3649 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
3650 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3651
3652 // noteAppOp is only used for when camera mute is not supported, in order
3653 // to trigger the sensor privacy "Unblock" dialog
3654 if (mAppOpsManager != nullptr) {
3655 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
3656 mClientPackageName, mClientFeatureId,
3657 String16("start camera ") + String16(mCameraIdStr));
3658 status_t res = handleAppOpMode(mode);
3659 if (res != OK) {
3660 return res;
3661 }
3662 }
3663
3664 return OK;
3665}
3666
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003667status_t CameraService::BasicClient::finishCameraStreamingOps() {
3668 ATRACE_CALL();
3669
3670 if (!mOpsActive) {
3671 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3672 return INVALID_OPERATION;
3673 }
3674 if (!mOpsStreaming) {
3675 ALOGV("%s: Streaming not active!", __FUNCTION__);
3676 return OK;
3677 }
3678
3679 if (mAppOpsManager != nullptr) {
3680 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
3681 mClientPackageName, mClientFeatureId);
3682 mOpsStreaming = false;
3683 }
3684
3685 return OK;
3686}
3687
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003688status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003689 ATRACE_CALL();
3690
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003691 if (mOpsStreaming) {
3692 // Make sure we've notified everyone about camera stopping
3693 finishCameraStreamingOps();
3694 }
3695
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003696 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003697 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003698 mOpsActive = false;
3699
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003700 // This function is called when a client disconnects. This should
3701 // release the camera, but actually only if it was in a proper
3702 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003703 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003704 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003705
Ruben Brunkcc776712015-02-17 20:18:47 -08003706 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003707 sCameraService->updateStatus(StatusInternal::PRESENT,
3708 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003709 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003710 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003711 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3712 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003713 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003714 mOpsCallback.clear();
3715
Emilian Peev53722fa2019-02-22 17:47:20 -08003716 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3717
Shuzhen Wang695044d2020-03-06 09:02:23 -08003718 // Notify listeners of camera open/close status
3719 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3720
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003721 return OK;
3722}
3723
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003724void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003725 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003726 if (mAppOpsManager == nullptr) {
3727 return;
3728 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003729 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003730 if (op != AppOpsManager::OP_CAMERA) {
3731 ALOGW("Unexpected app ops notification received: %d", op);
3732 return;
3733 }
3734
3735 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003736 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003737 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003738 ALOGV("checkOp returns: %d, %s ", res,
3739 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3740 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3741 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3742 "UNKNOWN");
3743
Shuzhen Wang64900852021-02-05 09:03:29 -08003744 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003745 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003746 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003747 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003748 } else if (res == AppOpsManager::MODE_IGNORED) {
3749 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08003750 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08003751 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Shuzhen Wang64900852021-02-05 09:03:29 -08003752 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3753 mCameraIdStr.string(), String8(mClientPackageName).string(),
3754 mUidIsTrusted, isUidActive);
3755 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3756 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3757 // error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003758 if (!mUidIsTrusted) {
3759 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
3760 setCameraMute(true);
3761 } else if (!isUidActive
3762 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
3763 block();
3764 }
Shuzhen Wang64900852021-02-05 09:03:29 -08003765 }
Evan Severson09ab4002021-02-10 14:15:19 -08003766 } else if (res == AppOpsManager::MODE_ALLOWED) {
3767 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003768 }
3769}
3770
Svet Ganova453d0d2018-01-11 15:37:58 -08003771void CameraService::BasicClient::block() {
3772 ATRACE_CALL();
3773
3774 // Reset the client PID to allow server-initiated disconnect,
3775 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003776 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003777 CaptureResultExtras resultExtras; // a dummy result (invalid)
3778 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3779 disconnect();
3780}
3781
Mathias Agopian65ab4712010-07-14 17:59:35 -07003782// ----------------------------------------------------------------------------
3783
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003784void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003785 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003786 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003787 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003788 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3789 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3790 api1ErrorCode = CAMERA_ERROR_DISABLED;
3791 }
3792 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003793 } else {
3794 ALOGE("mRemoteCallback is NULL!!");
3795 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003796}
3797
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003798// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003799binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003800 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003801 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003802}
3803
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003804bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3805 return level == API_1;
3806}
3807
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003808CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3809 mClient(client) {
3810}
3811
3812void CameraService::Client::OpsCallback::opChanged(int32_t op,
3813 const String16& packageName) {
3814 sp<BasicClient> client = mClient.promote();
3815 if (client != NULL) {
3816 client->opChanged(op, packageName);
3817 }
3818}
3819
Mathias Agopian65ab4712010-07-14 17:59:35 -07003820// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003821// UidPolicy
3822// ----------------------------------------------------------------------------
3823
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08003824void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003825 Mutex::Autolock _l(mUidLock);
3826
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003827 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003828 status_t res = mAm.linkToDeath(this);
3829 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003830 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00003831 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
3832 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08003833 ActivityManager::PROCESS_STATE_UNKNOWN,
3834 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003835 if (res == OK) {
3836 mRegistered = true;
3837 ALOGV("UidPolicy: Registered with ActivityManager");
3838 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003839}
3840
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08003841void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
3842 if (name != String16(kActivityServiceName)) {
3843 return;
3844 }
3845
3846 registerWithActivityManager();
3847}
3848
3849void CameraService::UidPolicy::registerSelf() {
3850 // Use check service to see if the activity service is available
3851 // If not available then register for notifications, instead of blocking
3852 // till the service is ready
3853 sp<IServiceManager> sm = defaultServiceManager();
3854 sp<IBinder> binder = sm->checkService(String16(kActivityServiceName));
3855 if (!binder) {
3856 sm->registerForNotifications(String16(kActivityServiceName), this);
3857 } else {
3858 registerWithActivityManager();
3859 }
3860}
3861
Svet Ganova453d0d2018-01-11 15:37:58 -08003862void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003863 Mutex::Autolock _l(mUidLock);
3864
Steven Moreland2f348142019-07-02 15:59:07 -07003865 mAm.unregisterUidObserver(this);
3866 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003867 mRegistered = false;
3868 mActiveUids.clear();
3869 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003870}
3871
3872void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3873 onUidIdle(uid, disabled);
3874}
3875
3876void CameraService::UidPolicy::onUidActive(uid_t uid) {
3877 Mutex::Autolock _l(mUidLock);
3878 mActiveUids.insert(uid);
3879}
3880
3881void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3882 bool deleted = false;
3883 {
3884 Mutex::Autolock _l(mUidLock);
3885 if (mActiveUids.erase(uid) > 0) {
3886 deleted = true;
3887 }
3888 }
3889 if (deleted) {
3890 sp<CameraService> service = mService.promote();
3891 if (service != nullptr) {
3892 service->blockClientsForUid(uid);
3893 }
3894 }
3895}
3896
Emilian Peev53722fa2019-02-22 17:47:20 -08003897void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003898 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00003899 bool procStateChange = false;
3900 {
3901 Mutex::Autolock _l(mUidLock);
3902 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
3903 mMonitoredUids[uid].procState != procState) {
3904 mMonitoredUids[uid].procState = procState;
3905 procStateChange = true;
3906 }
3907 }
3908
3909 if (procStateChange) {
3910 sp<CameraService> service = mService.promote();
3911 if (service != nullptr) {
3912 service->notifyMonitoredUids();
3913 }
Emilian Peev53722fa2019-02-22 17:47:20 -08003914 }
3915}
3916
Austin Borger65577682022-02-17 00:25:43 +00003917void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid) {
3918 bool procAdjChange = false;
3919 {
3920 Mutex::Autolock _l(mUidLock);
3921 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3922 procAdjChange = true;
3923 }
3924 }
3925
3926 if (procAdjChange) {
3927 sp<CameraService> service = mService.promote();
3928 if (service != nullptr) {
3929 service->notifyMonitoredUids();
3930 }
3931 }
3932}
3933
Emilian Peev53722fa2019-02-22 17:47:20 -08003934void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3935 Mutex::Autolock _l(mUidLock);
3936 auto it = mMonitoredUids.find(uid);
3937 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00003938 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08003939 } else {
Austin Borger65577682022-02-17 00:25:43 +00003940 MonitoredUid monitoredUid;
3941 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
3942 monitoredUid.refCount = 1;
3943 mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid));
Emilian Peev53722fa2019-02-22 17:47:20 -08003944 }
3945}
3946
3947void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3948 Mutex::Autolock _l(mUidLock);
3949 auto it = mMonitoredUids.find(uid);
3950 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00003951 it->second.refCount--;
3952 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003953 mMonitoredUids.erase(it);
3954 }
3955 } else {
3956 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3957 }
3958}
3959
Svet Ganov7b4ab782018-03-25 12:48:10 -07003960bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003961 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003962 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003963}
3964
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003965static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3966static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003967
Svet Ganov7b4ab782018-03-25 12:48:10 -07003968bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003969 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003970 // If activity manager is unreachable, assume everything is active
3971 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003972 return true;
3973 }
3974 auto it = mOverrideUids.find(uid);
3975 if (it != mOverrideUids.end()) {
3976 return it->second;
3977 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003978 bool active = mActiveUids.find(uid) != mActiveUids.end();
3979 if (!active) {
3980 // We want active UIDs to always access camera with their first attempt since
3981 // there is no guarantee the app is robustly written and would retry getting
3982 // the camera on failure. The inverse case is not a problem as we would take
3983 // camera away soon once we get the callback that the uid is no longer active.
3984 ActivityManager am;
3985 // Okay to access with a lock held as UID changes are dispatched without
3986 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003987 int64_t startTimeMillis = 0;
3988 do {
3989 // TODO: Fix this b/109950150!
3990 // Okay this is a hack. There is a race between the UID turning active and
3991 // activity being resumed. The proper fix is very risky, so we temporary add
3992 // some polling which should happen pretty rarely anyway as the race is hard
3993 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003994 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003995 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003996 if (active) {
3997 break;
3998 }
3999 if (startTimeMillis <= 0) {
4000 startTimeMillis = uptimeMillis();
4001 }
4002 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004003 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004004 if (remainingTimeMillis <= 0) {
4005 break;
4006 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004007 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4008
4009 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004010 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004011 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004012 } while (true);
4013
Svet Ganov7b4ab782018-03-25 12:48:10 -07004014 if (active) {
4015 // Now that we found out the UID is actually active, cache that
4016 mActiveUids.insert(uid);
4017 }
4018 }
4019 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004020}
4021
Varun Shahb42f1eb2019-04-16 14:45:13 -07004022int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4023 Mutex::Autolock _l(mUidLock);
4024 return getProcStateLocked(uid);
4025}
4026
4027int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4028 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4029 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004030 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004031 }
4032 return procState;
4033}
4034
Svet Ganov7b4ab782018-03-25 12:48:10 -07004035void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
4036 String16 callingPackage, bool active) {
4037 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004038}
4039
Svet Ganov7b4ab782018-03-25 12:48:10 -07004040void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
4041 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004042}
4043
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004044void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4045 Mutex::Autolock _l(mUidLock);
4046 ALOGV("UidPolicy: ActivityManager has died");
4047 mRegistered = false;
4048 mActiveUids.clear();
4049}
4050
Svet Ganov7b4ab782018-03-25 12:48:10 -07004051void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
4052 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004053 bool wasActive = false;
4054 bool isActive = false;
4055 {
4056 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004057 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004058 mOverrideUids.erase(uid);
4059 if (insert) {
4060 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4061 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004062 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004063 }
4064 if (wasActive != isActive && !isActive) {
4065 sp<CameraService> service = mService.promote();
4066 if (service != nullptr) {
4067 service->blockClientsForUid(uid);
4068 }
4069 }
4070}
4071
4072// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004073// SensorPrivacyPolicy
4074// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004075
4076void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4077{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004078 Mutex::Autolock _l(mSensorPrivacyLock);
4079 if (mRegistered) {
4080 return;
4081 }
Evan Severson09ab4002021-02-10 14:15:19 -08004082 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004083 mSpm.addSensorPrivacyListener(this);
4084 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
4085 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004086 if (res == OK) {
4087 mRegistered = true;
4088 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4089 }
4090}
4091
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004092void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4093 const sp<IBinder>&) {
4094 if (name != String16(kSensorPrivacyServiceName)) {
4095 return;
4096 }
4097
4098 registerWithSensorPrivacyManager();
4099}
4100
4101void CameraService::SensorPrivacyPolicy::registerSelf() {
4102 // Use checkservice to see if the sensor_privacy service is available
4103 // If service is not available then register for notification
4104 sp<IServiceManager> sm = defaultServiceManager();
4105 sp<IBinder> binder = sm->checkService(String16(kSensorPrivacyServiceName));
4106 if (!binder) {
4107 sm->registerForNotifications(String16(kSensorPrivacyServiceName),this);
4108 } else {
4109 registerWithSensorPrivacyManager();
4110 }
4111}
4112
Michael Grooverd1d435a2018-12-18 17:39:42 -08004113void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4114 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004115 mSpm.removeSensorPrivacyListener(this);
4116 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004117 mRegistered = false;
4118 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4119}
4120
4121bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004122 if (!mRegistered) {
4123 registerWithSensorPrivacyManager();
4124 }
4125
Michael Grooverd1d435a2018-12-18 17:39:42 -08004126 Mutex::Autolock _l(mSensorPrivacyLock);
4127 return mSensorPrivacyEnabled;
4128}
4129
Evan Seversond0b69922022-01-27 10:47:34 -08004130bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004131 if (!hasCameraPrivacyFeature()) {
4132 return false;
4133 }
Evan Seversond0b69922022-01-27 10:47:34 -08004134 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004135}
4136
Evan Seversond0b69922022-01-27 10:47:34 -08004137binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
4138 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08004139 {
4140 Mutex::Autolock _l(mSensorPrivacyLock);
Kwangkyu Parke3af2992022-11-05 02:46:52 +09004141 mSensorPrivacyEnabled = enabled;
Michael Grooverd1d435a2018-12-18 17:39:42 -08004142 }
4143 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08004144 if (enabled) {
4145 sp<CameraService> service = mService.promote();
4146 if (service != nullptr) {
4147 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004148 }
4149 }
4150 return binder::Status::ok();
4151}
4152
4153void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4154 Mutex::Autolock _l(mSensorPrivacyLock);
4155 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
4156 mRegistered = false;
4157}
4158
Evan Severson09ab4002021-02-10 14:15:19 -08004159bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08004160 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
4161 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4162 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
4163 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4164 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08004165}
4166
Michael Grooverd1d435a2018-12-18 17:39:42 -08004167// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004168// CameraState
4169// ----------------------------------------------------------------------------
4170
4171CameraService::CameraState::CameraState(const String8& id, int cost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004172 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind,
4173 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004174 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004175 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08004176
4177CameraService::CameraState::~CameraState() {}
4178
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004179CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004180 Mutex::Autolock lock(mStatusLock);
4181 return mStatus;
4182}
4183
Shuzhen Wang43858162020-01-10 13:42:15 -08004184std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
4185 Mutex::Autolock lock(mStatusLock);
4186 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
4187 return res;
4188}
4189
Ruben Brunkcc776712015-02-17 20:18:47 -08004190CameraParameters CameraService::CameraState::getShimParams() const {
4191 return mShimParams;
4192}
4193
4194void CameraService::CameraState::setShimParams(const CameraParameters& params) {
4195 mShimParams = params;
4196}
4197
4198int CameraService::CameraState::getCost() const {
4199 return mCost;
4200}
4201
4202std::set<String8> CameraService::CameraState::getConflicting() const {
4203 return mConflicting;
4204}
4205
4206String8 CameraService::CameraState::getId() const {
4207 return mId;
4208}
4209
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004210SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
4211 return mSystemCameraKind;
4212}
4213
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004214bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
4215 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
4216 != mPhysicalCameras.end();
4217}
4218
Shuzhen Wang43858162020-01-10 13:42:15 -08004219bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
4220 Mutex::Autolock lock(mStatusLock);
4221 auto result = mUnavailablePhysicalIds.insert(physicalId);
4222 return result.second;
4223}
4224
4225bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
4226 Mutex::Autolock lock(mStatusLock);
4227 auto count = mUnavailablePhysicalIds.erase(physicalId);
4228 return count > 0;
4229}
4230
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004231void CameraService::CameraState::setClientPackage(const String8& clientPackage) {
4232 Mutex::Autolock lock(mStatusLock);
4233 mClientPackage = clientPackage;
4234}
4235
4236String8 CameraService::CameraState::getClientPackage() const {
4237 Mutex::Autolock lock(mStatusLock);
4238 return mClientPackage;
4239}
4240
Ruben Brunkcc776712015-02-17 20:18:47 -08004241// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07004242// ClientEventListener
4243// ----------------------------------------------------------------------------
4244
4245void CameraService::ClientEventListener::onClientAdded(
4246 const resource_policy::ClientDescriptor<String8,
4247 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004248 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004249 if (basicClient.get() != nullptr) {
4250 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4251 notifier.noteStartCamera(descriptor.getKey(),
4252 static_cast<int>(basicClient->getClientUid()));
4253 }
4254}
4255
4256void CameraService::ClientEventListener::onClientRemoved(
4257 const resource_policy::ClientDescriptor<String8,
4258 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004259 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004260 if (basicClient.get() != nullptr) {
4261 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4262 notifier.noteStopCamera(descriptor.getKey(),
4263 static_cast<int>(basicClient->getClientUid()));
4264 }
4265}
4266
4267
4268// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004269// CameraClientManager
4270// ----------------------------------------------------------------------------
4271
Ruben Brunk99e69712015-05-26 17:25:07 -07004272CameraService::CameraClientManager::CameraClientManager() {
4273 setListener(std::make_shared<ClientEventListener>());
4274}
4275
Ruben Brunkcc776712015-02-17 20:18:47 -08004276CameraService::CameraClientManager::~CameraClientManager() {}
4277
4278sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
4279 const String8& id) const {
4280 auto descriptor = get(id);
4281 if (descriptor == nullptr) {
4282 return sp<BasicClient>{nullptr};
4283 }
4284 return descriptor->getValue();
4285}
4286
4287String8 CameraService::CameraClientManager::toString() const {
4288 auto all = getAll();
4289 String8 ret("[");
4290 bool hasAny = false;
4291 for (auto& i : all) {
4292 hasAny = true;
4293 String8 key = i->getKey();
4294 int32_t cost = i->getCost();
4295 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00004296 int32_t score = i->getPriority().getScore();
4297 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08004298 auto conflicting = i->getConflicting();
4299 auto clientSp = i->getValue();
4300 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07004301 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08004302 if (clientSp.get() != nullptr) {
4303 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07004304 uid_t clientUid = clientSp->getClientUid();
4305 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004306 }
Emilian Peev8131a262017-02-01 12:33:43 +00004307 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
4308 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08004309
Ruben Brunk6267b532015-04-30 17:44:07 -07004310 if (clientSp.get() != nullptr) {
4311 ret.appendFormat("User Id: %d, ", clientUserId);
4312 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004313 if (packageName.size() != 0) {
4314 ret.appendFormat("Client Package Name: %s", packageName.string());
4315 }
4316
4317 ret.append(", Conflicting Client Devices: {");
4318 for (auto& j : conflicting) {
4319 ret.appendFormat("%s, ", j.string());
4320 }
4321 ret.append("})");
4322 }
4323 if (hasAny) ret.append("\n");
4324 ret.append("]\n");
4325 return ret;
4326}
4327
4328CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
4329 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00004330 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004331 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004332
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004333 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
4334 int32_t state_adj = systemNativeClient ? kSystemNativeClientState: state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07004335
Ruben Brunkcc776712015-02-17 20:18:47 -08004336 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004337 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
4338 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08004339}
4340
4341CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004342 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004343 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004344 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00004345 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004346 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
4347 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08004348}
4349
4350// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08004351// InjectionStatusListener
4352// ----------------------------------------------------------------------------
4353
4354void CameraService::InjectionStatusListener::addListener(
4355 const sp<ICameraInjectionCallback>& callback) {
4356 Mutex::Autolock lock(mListenerLock);
4357 if (mCameraInjectionCallback) return;
4358 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
4359 if (res == OK) {
4360 mCameraInjectionCallback = callback;
4361 }
4362}
4363
4364void CameraService::InjectionStatusListener::removeListener() {
4365 Mutex::Autolock lock(mListenerLock);
4366 if (mCameraInjectionCallback == nullptr) {
4367 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4368 return;
4369 }
4370 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
4371 mCameraInjectionCallback = nullptr;
4372}
4373
4374void CameraService::InjectionStatusListener::notifyInjectionError(
Cliff Wud3a05312021-04-26 23:07:31 +08004375 String8 injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08004376 if (mCameraInjectionCallback == nullptr) {
4377 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4378 return;
4379 }
Cliff Wud3a05312021-04-26 23:07:31 +08004380
4381 switch (err) {
4382 case -ENODEV:
4383 mCameraInjectionCallback->onInjectionError(
4384 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4385 ALOGE("No camera device with ID \"%s\" currently available!",
4386 injectedCamId.string());
4387 break;
4388 case -EBUSY:
4389 mCameraInjectionCallback->onInjectionError(
4390 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4391 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
4392 injectedCamId.string());
4393 break;
4394 case DEAD_OBJECT:
4395 mCameraInjectionCallback->onInjectionError(
4396 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4397 ALOGE("Camera ID \"%s\" object is dead!",
4398 injectedCamId.string());
4399 break;
4400 case INVALID_OPERATION:
4401 mCameraInjectionCallback->onInjectionError(
4402 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4403 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
4404 injectedCamId.string());
4405 break;
4406 case UNKNOWN_TRANSACTION:
4407 mCameraInjectionCallback->onInjectionError(
4408 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
4409 ALOGE("Camera ID \"%s\" method doesn't support!",
4410 injectedCamId.string());
4411 break;
4412 default:
4413 mCameraInjectionCallback->onInjectionError(
4414 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
4415 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
4416 strerror(-err), err, injectedCamId.string());
4417 }
Cliff Wud8cae102021-03-11 01:37:42 +08004418}
4419
4420void CameraService::InjectionStatusListener::binderDied(
4421 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08004422 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
4423 auto parent = mParent.promote();
4424 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08004425 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4426 if (clientDescriptor != nullptr) {
4427 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4428 baseClientPtr->stopInjection();
4429 }
Cliff Wu3b268182021-07-06 15:44:43 +08004430 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004431 }
4432}
4433
4434// ----------------------------------------------------------------------------
4435// CameraInjectionSession
4436// ----------------------------------------------------------------------------
4437
4438binder::Status CameraService::CameraInjectionSession::stopInjection() {
4439 Mutex::Autolock lock(mInjectionSessionLock);
4440 auto parent = mParent.promote();
4441 if (parent == nullptr) {
4442 ALOGE("CameraInjectionSession: Parent is gone");
4443 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
4444 "Camera service encountered error");
4445 }
Cliff Wud3a05312021-04-26 23:07:31 +08004446
4447 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08004448 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4449 if (clientDescriptor != nullptr) {
4450 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4451 res = baseClientPtr->stopInjection();
4452 if (res != OK) {
4453 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
4454 " ret != NO_ERROR: %d", res);
4455 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
4456 "Camera session encountered error");
4457 }
4458 }
Cliff Wu3b268182021-07-06 15:44:43 +08004459 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004460 return binder::Status::ok();
4461}
4462
4463// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07004464
4465static const int kDumpLockRetries = 50;
4466static const int kDumpLockSleep = 60000;
4467
4468static bool tryLock(Mutex& mutex)
4469{
4470 bool locked = false;
4471 for (int i = 0; i < kDumpLockRetries; ++i) {
4472 if (mutex.tryLock() == NO_ERROR) {
4473 locked = true;
4474 break;
4475 }
4476 usleep(kDumpLockSleep);
4477 }
4478 return locked;
4479}
4480
Rucha Katakwardf223072021-06-15 10:21:00 -07004481void CameraService::cacheDump() {
4482 if (mMemFd != -1) {
4483 const Vector<String16> args;
4484 ATRACE_CALL();
4485 // Acquiring service lock here will avoid the deadlock since
4486 // cacheDump will not be called during the second disconnect.
4487 Mutex::Autolock lock(mServiceLock);
4488
4489 Mutex::Autolock l(mCameraStatesLock);
4490 // Start collecting the info for open sessions and store it in temp file.
4491 for (const auto& state : mCameraStates) {
4492 String8 cameraId = state.first;
4493 auto clientDescriptor = mActiveClientManager.get(cameraId);
4494 if (clientDescriptor != nullptr) {
4495 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.string());
4496 // Log the current open session info before device is disconnected.
4497 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
4498 }
4499 }
4500 }
4501}
4502
Mathias Agopian65ab4712010-07-14 17:59:35 -07004503status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004504 ATRACE_CALL();
4505
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004506 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004507 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004508 CameraThreadState::getCallingPid(),
4509 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004510 return NO_ERROR;
4511 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004512 bool locked = tryLock(mServiceLock);
4513 // failed to lock - CameraService is probably deadlocked
4514 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004515 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004516 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004517
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004518 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004519 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07004520
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004521 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004522 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08004523
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004524 if (locked) mServiceLock.unlock();
4525 return NO_ERROR;
4526 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004527 dprintf(fd, "\n== Service global info: ==\n\n");
4528 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004529 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07004530 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
4531 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004532 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
4533 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
4534 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004535 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004536 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
4537 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Shuzhen Wang16610a62022-12-15 22:38:07 -08004538 if (mStreamUseCaseOverrides.size() > 0) {
4539 dprintf(fd, "Active stream use case overrides:");
4540 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
4541 dprintf(fd, " %" PRId64, useCaseOverride);
4542 }
4543 dprintf(fd, "\n");
4544 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004545
4546 dumpEventLog(fd);
4547
4548 bool stateLocked = tryLock(mCameraStatesLock);
4549 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004550 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004551 }
4552
Emilian Peevbd8c5032018-02-14 23:05:40 +00004553 int argSize = args.size();
4554 for (int i = 0; i < argSize; i++) {
4555 if (args[i] == TagMonitor::kMonitorOption) {
4556 if (i + 1 < argSize) {
4557 mMonitorTags = String8(args[i + 1]);
4558 }
4559 break;
4560 }
4561 }
4562
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004563 for (auto& state : mCameraStates) {
4564 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004565
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004566 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004567
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004568 CameraParameters p = state.second->getShimParams();
4569 if (!p.isEmpty()) {
4570 dprintf(fd, " Camera1 API shim is using parameters:\n ");
4571 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004572 }
4573
4574 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004575 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004576 // log the current open session info
4577 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004578 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07004579 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004580 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004581
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004582 }
4583
4584 if (stateLocked) mCameraStatesLock.unlock();
4585
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004586 if (locked) mServiceLock.unlock();
4587
Emilian Peevf53f66e2017-04-11 14:29:43 +01004588 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004589
4590 dprintf(fd, "\n== Vendor tags: ==\n\n");
4591
4592 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
4593 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00004594 sp<VendorTagDescriptorCache> cache =
4595 VendorTagDescriptorCache::getGlobalVendorTagCache();
4596 if (cache == NULL) {
4597 dprintf(fd, "No vendor tags.\n");
4598 } else {
4599 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
4600 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004601 } else {
4602 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
4603 }
4604
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004605 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004606 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004607 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004608
4609 // Process dump arguments, if any
4610 int n = args.size();
4611 String16 verboseOption("-v");
4612 String16 unreachableOption("--unreachable");
4613 for (int i = 0; i < n; i++) {
4614 if (args[i] == verboseOption) {
4615 // change logging level
4616 if (i + 1 >= n) continue;
4617 String8 levelStr(args[i+1]);
4618 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004619 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004620 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004621 } else if (args[i] == unreachableOption) {
4622 // Dump memory analysis
4623 // TODO - should limit be an argument parameter?
4624 UnreachableMemoryInfo info;
4625 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
4626 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004627 dprintf(fd, "\n== Unable to dump unreachable memory. "
4628 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004629 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004630 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004631 std::string s = info.ToString(/*log_contents*/ true);
4632 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004633 }
4634 }
4635 }
Rucha Katakwardf223072021-06-15 10:21:00 -07004636
4637 bool serviceLocked = tryLock(mServiceLock);
4638
4639 // Dump info from previous open sessions.
4640 // Reposition the offset to beginning of the file before reading
4641
4642 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
4643 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
4644 ssize_t size_read;
4645 char buf[4096];
4646 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
4647 // Read data from file to a small buffer and write it to fd.
4648 write(fd, buf, size_read);
4649 if (size_read == -1) {
4650 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4651 break;
4652 }
4653 }
4654 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
4655 } else {
4656 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4657 }
4658
4659 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004660 return NO_ERROR;
4661}
4662
Rucha Katakwardf223072021-06-15 10:21:00 -07004663void CameraService::dumpOpenSessionClientLogs(int fd,
4664 const Vector<String16>& args, const String8& cameraId) {
4665 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07004666 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
4667 getFormattedCurrentTime().string(),
4668 cameraId.string());
Rucha Katakwardf223072021-06-15 10:21:00 -07004669 dprintf(fd, " Client priority score: %d state: %d\n",
4670 clientDescriptor->getPriority().getScore(),
4671 clientDescriptor->getPriority().getState());
4672 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
4673
4674 auto client = clientDescriptor->getValue();
4675 dprintf(fd, " Client package: %s\n",
4676 String8(client->getPackageName()).string());
4677
4678 client->dumpClient(fd, args);
4679}
4680
4681void CameraService::dumpClosedSessionClientLogs(int fd, const String8& cameraId) {
4682 dprintf(fd, " Device %s is closed, no client instance\n",
4683 cameraId.string());
4684}
4685
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004686void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004687 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004688
4689 Mutex::Autolock l(mLogLock);
4690 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004691 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004692 }
4693
4694 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004695 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004696 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004697 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004698 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004699 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004700}
4701
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004702void CameraService::cacheClientTagDumpIfNeeded(const char *cameraId, BasicClient* client) {
4703 Mutex::Autolock lock(mLogLock);
4704 if (!isClientWatchedLocked(client)) { return; }
4705
4706 std::vector<std::string> dumpVector;
4707 client->dumpWatchedEventsToVector(dumpVector);
4708
4709 if (dumpVector.empty()) { return; }
4710
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004711 std::string dumpString;
4712
4713 String8 currentTime = getFormattedCurrentTime();
4714 dumpString += "Cached @ ";
4715 dumpString += currentTime.string();
4716 dumpString += "\n"; // First line is the timestamp of when client is cached.
4717
4718
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004719 const String16 &packageName = client->getPackageName();
4720
4721 String8 packageName8 = String8(packageName);
4722 const char *printablePackageName = packageName8.lockBuffer(packageName.size());
4723
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004724
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004725 size_t i = dumpVector.size();
4726
4727 // Store the string in reverse order (latest last)
4728 while (i > 0) {
4729 i--;
4730 dumpString += cameraId;
4731 dumpString += ":";
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004732 dumpString += printablePackageName;
4733 dumpString += " ";
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004734 dumpString += dumpVector[i]; // implicitly ends with '\n'
4735 }
4736
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004737 packageName8.unlockBuffer();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004738 mWatchedClientsDumpCache[packageName] = dumpString;
4739}
4740
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004741void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004742 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004743 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
4744 if (mTorchClientMap[i] == who) {
4745 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004746 String8 cameraId = mTorchClientMap.keyAt(i);
4747 status_t res = mFlashlight->setTorchMode(cameraId, false);
4748 if (res) {
4749 ALOGE("%s: torch client died but couldn't turn off torch: "
4750 "%s (%d)", __FUNCTION__, strerror(-res), res);
4751 return;
4752 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004753 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004754 break;
4755 }
4756 }
4757}
4758
Ruben Brunkcc776712015-02-17 20:18:47 -08004759/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07004760
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004761 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07004762 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
4763 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004764 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08004765 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004766 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004767
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004768 // check torch client
4769 handleTorchClientBinderDied(who);
4770
4771 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08004772 if(!evictClientIdByRemote(who)) {
4773 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004774 return;
4775 }
4776
Ruben Brunkcc776712015-02-17 20:18:47 -08004777 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
4778 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004779}
4780
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004781void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004782 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08004783}
4784
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004785void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
4786 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004787 // Do not lock mServiceLock here or can get into a deadlock from
4788 // connect() -> disconnect -> updateStatus
4789
4790 auto state = getCameraState(cameraId);
4791
4792 if (state == nullptr) {
4793 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4794 cameraId.string());
4795 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07004796 }
4797
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004798 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
4799 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
4800 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
4801 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
4802 return;
4803 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004804
4805 // Collect the logical cameras without holding mStatusLock in updateStatus
4806 // as that can lead to a deadlock(b/162192331).
4807 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08004808 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08004809 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07004810 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004811 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004812 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004813
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004814 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004815 // Update torch status if it has a flash unit.
4816 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004817 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004818 if (getTorchStatusLocked(cameraId, &torchStatus) !=
4819 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004820 TorchModeStatus newTorchStatus =
4821 status == StatusInternal::PRESENT ?
4822 TorchModeStatus::AVAILABLE_OFF :
4823 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004824 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07004825 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004826 }
4827 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004828 }
4829
4830 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004831 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
4832 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08004833
Ruben Brunkcc776712015-02-17 20:18:47 -08004834 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07004835 bool isVendorListener = listener->isVendorListener();
4836 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
4837 listener->getListenerPid(), listener->getListenerUid()) ||
Shuzhen Wangb8259792021-05-27 09:27:06 -07004838 isVendorListener) {
4839 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004840 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08004841 continue;
4842 }
Austin Borgere8e2c422022-05-12 13:45:24 -07004843 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08004844 String16(cameraId));
Austin Borgere8e2c422022-05-12 13:45:24 -07004845 listener->handleBinderStatus(ret,
4846 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
4847 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
4848 ret.exceptionCode());
Ruben Brunkcc776712015-02-17 20:18:47 -08004849 }
4850 });
Igor Murashkincba2c162013-03-20 15:56:31 -07004851}
4852
Shuzhen Wang695044d2020-03-06 09:02:23 -08004853void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
4854 const String16& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004855 auto state = getCameraState(cameraId);
4856 if (state == nullptr) {
4857 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4858 cameraId.string());
4859 return;
4860 }
4861 if (open) {
4862 state->setClientPackage(String8(clientPackageName));
4863 } else {
4864 state->setClientPackage(String8::empty());
4865 }
4866
Shuzhen Wang695044d2020-03-06 09:02:23 -08004867 Mutex::Autolock lock(mStatusListenerLock);
4868
4869 for (const auto& it : mListenerList) {
4870 if (!it->isOpenCloseCallbackAllowed()) {
4871 continue;
4872 }
4873
4874 binder::Status ret;
4875 String16 cameraId64(cameraId);
4876 if (open) {
4877 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
4878 } else {
4879 ret = it->getListener()->onCameraClosed(cameraId64);
4880 }
Austin Borgere8e2c422022-05-12 13:45:24 -07004881
4882 it->handleBinderStatus(ret,
4883 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
4884 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08004885 }
4886}
4887
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004888template<class Func>
4889void CameraService::CameraState::updateStatus(StatusInternal status,
4890 const String8& cameraId,
4891 std::initializer_list<StatusInternal> rejectSourceStates,
4892 Func onStatusUpdatedLocked) {
4893 Mutex::Autolock lock(mStatusLock);
4894 StatusInternal oldStatus = mStatus;
4895 mStatus = status;
4896
4897 if (oldStatus == status) {
4898 return;
4899 }
4900
4901 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
4902 cameraId.string(), oldStatus, status);
4903
4904 if (oldStatus == StatusInternal::NOT_PRESENT &&
4905 (status != StatusInternal::PRESENT &&
4906 status != StatusInternal::ENUMERATING)) {
4907
4908 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
4909 __FUNCTION__);
4910 mStatus = oldStatus;
4911 return;
4912 }
4913
4914 /**
4915 * Sometimes we want to conditionally do a transition.
4916 * For example if a client disconnects, we want to go to PRESENT
4917 * only if we weren't already in NOT_PRESENT or ENUMERATING.
4918 */
4919 for (auto& rejectStatus : rejectSourceStates) {
4920 if (oldStatus == rejectStatus) {
4921 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
4922 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
4923 mStatus = oldStatus;
4924 return;
4925 }
4926 }
4927
4928 onStatusUpdatedLocked(cameraId, status);
4929}
4930
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004931status_t CameraService::getTorchStatusLocked(
4932 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004933 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004934 if (!status) {
4935 return BAD_VALUE;
4936 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004937 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4938 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004939 // invalid camera ID or the camera doesn't have a flash unit
4940 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004941 }
4942
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004943 *status = mTorchStatusMap.valueAt(index);
4944 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004945}
4946
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004947status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004948 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004949 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4950 if (index == NAME_NOT_FOUND) {
4951 return BAD_VALUE;
4952 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004953 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004954
4955 return OK;
4956}
4957
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004958std::list<String16> CameraService::getLogicalCameras(
4959 const String8& physicalCameraId) {
4960 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08004961 Mutex::Autolock lock(mCameraStatesLock);
4962 for (const auto& state : mCameraStates) {
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004963 if (state.second->containsPhysicalCamera(physicalCameraId.c_str())) {
4964 retList.emplace_back(String16(state.first));
Shuzhen Wang43858162020-01-10 13:42:15 -08004965 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004966 }
4967 return retList;
4968}
4969
4970void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
4971 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
4972 SystemCameraKind deviceKind) {
4973 // mStatusListenerLock is expected to be locked
4974 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004975 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004976 // Note: we check only the deviceKind of the physical camera id
4977 // since, logical camera ids and their physical camera ids are
4978 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004979 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
4980 listener->getListenerPid(), listener->getListenerUid())) {
4981 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004982 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004983 continue;
4984 }
Austin Borgere8e2c422022-05-12 13:45:24 -07004985 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004986 logicalCameraId, physicalCameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07004987 listener->handleBinderStatus(ret,
4988 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
4989 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
4990 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08004991 }
4992 }
4993}
4994
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004995
Svet Ganova453d0d2018-01-11 15:37:58 -08004996void CameraService::blockClientsForUid(uid_t uid) {
4997 const auto clients = mActiveClientManager.getAll();
4998 for (auto& current : clients) {
4999 if (current != nullptr) {
5000 const auto basicClient = current->getValue();
5001 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5002 basicClient->block();
5003 }
5004 }
5005 }
5006}
5007
Michael Grooverd1d435a2018-12-18 17:39:42 -08005008void CameraService::blockAllClients() {
5009 const auto clients = mActiveClientManager.getAll();
5010 for (auto& current : clients) {
5011 if (current != nullptr) {
5012 const auto basicClient = current->getValue();
5013 if (basicClient.get() != nullptr) {
5014 basicClient->block();
5015 }
5016 }
5017 }
5018}
5019
Svet Ganova453d0d2018-01-11 15:37:58 -08005020// NOTE: This is a remote API - make sure all args are validated
5021status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
5022 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
5023 return PERMISSION_DENIED;
5024 }
5025 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5026 return BAD_VALUE;
5027 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005028 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005029 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07005030 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005031 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07005032 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005033 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005034 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
5035 return handleSetRotateAndCrop(args);
5036 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
5037 return handleGetRotateAndCrop(out);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005038 } else if (args.size() >= 2 && args[0] == String16("set-autoframing")) {
5039 return handleSetAutoframing(args);
5040 } else if (args.size() >= 1 && args[0] == String16("get-autoframing")) {
5041 return handleGetAutoframing(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005042 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
5043 return handleSetImageDumpMask(args);
5044 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
5045 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005046 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
5047 return handleSetCameraMute(args);
Shuzhen Wang16610a62022-12-15 22:38:07 -08005048 } else if (args.size() >= 2 && args[0] == String16("set-stream-use-case-override")) {
5049 return handleSetStreamUseCaseOverrides(args);
5050 } else if (args.size() >= 1 && args[0] == String16("clear-stream-use-case-override")) {
5051 handleClearStreamUseCaseOverrides();
5052 return OK;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005053 } else if (args.size() >= 2 && args[0] == String16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005054 return handleWatchCommand(args, in, out);
Ravneetaeb20dc2022-03-30 05:33:03 +00005055 } else if (args.size() >= 2 && args[0] == String16("set-watchdog")) {
5056 return handleSetCameraServiceWatchdog(args);
Svet Ganova453d0d2018-01-11 15:37:58 -08005057 } else if (args.size() == 1 && args[0] == String16("help")) {
5058 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005059 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005060 }
5061 printHelp(err);
5062 return BAD_VALUE;
5063}
5064
5065status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07005066 String16 packageName = args[1];
5067
Svet Ganova453d0d2018-01-11 15:37:58 -08005068 bool active = false;
5069 if (args[2] == String16("active")) {
5070 active = true;
5071 } else if ((args[2] != String16("idle"))) {
5072 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
5073 return BAD_VALUE;
5074 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005075
5076 int userId = 0;
5077 if (args.size() >= 5 && args[3] == String16("--user")) {
5078 userId = atoi(String8(args[4]));
5079 }
5080
5081 uid_t uid;
5082 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5083 return BAD_VALUE;
5084 }
5085
5086 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005087 return NO_ERROR;
5088}
5089
5090status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07005091 String16 packageName = args[1];
5092
5093 int userId = 0;
5094 if (args.size() >= 4 && args[2] == String16("--user")) {
5095 userId = atoi(String8(args[3]));
5096 }
5097
5098 uid_t uid;
5099 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005100 return BAD_VALUE;
5101 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005102
5103 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005104 return NO_ERROR;
5105}
5106
5107status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07005108 String16 packageName = args[1];
5109
5110 int userId = 0;
5111 if (args.size() >= 4 && args[2] == String16("--user")) {
5112 userId = atoi(String8(args[3]));
5113 }
5114
5115 uid_t uid;
5116 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005117 return BAD_VALUE;
5118 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005119
5120 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005121 return dprintf(out, "active\n");
5122 } else {
5123 return dprintf(out, "idle\n");
5124 }
5125}
5126
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005127status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
5128 int rotateValue = atoi(String8(args[1]));
5129 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
5130 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
5131 Mutex::Autolock lock(mServiceLock);
5132
5133 mOverrideRotateAndCropMode = rotateValue;
5134
5135 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
5136
5137 const auto clients = mActiveClientManager.getAll();
5138 for (auto& current : clients) {
5139 if (current != nullptr) {
5140 const auto basicClient = current->getValue();
5141 if (basicClient.get() != nullptr) {
5142 basicClient->setRotateAndCropOverride(rotateValue);
5143 }
5144 }
5145 }
5146
5147 return OK;
5148}
5149
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005150status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
5151 char* end;
5152 int autoframingValue = (int) strtol(String8(args[1]), &end, /*base=*/10);
5153 if ((*end != '\0') ||
5154 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
5155 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
5156 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
5157 return BAD_VALUE;
5158 }
5159
5160 Mutex::Autolock lock(mServiceLock);
5161 mOverrideAutoframingMode = autoframingValue;
5162
5163 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
5164
5165 const auto clients = mActiveClientManager.getAll();
5166 for (auto& current : clients) {
5167 if (current != nullptr) {
5168 const auto basicClient = current->getValue();
5169 if (basicClient.get() != nullptr) {
5170 basicClient->setAutoframingOverride(autoframingValue);
5171 }
5172 }
5173 }
5174
5175 return OK;
5176}
5177
Ravneetaeb20dc2022-03-30 05:33:03 +00005178status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
5179 int enableWatchdog = atoi(String8(args[1]));
5180
5181 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
5182
5183 Mutex::Autolock lock(mServiceLock);
5184
5185 mCameraServiceWatchdogEnabled = enableWatchdog;
5186
5187 const auto clients = mActiveClientManager.getAll();
5188 for (auto& current : clients) {
5189 if (current != nullptr) {
5190 const auto basicClient = current->getValue();
5191 if (basicClient.get() != nullptr) {
5192 basicClient->setCameraServiceWatchdog(enableWatchdog);
5193 }
5194 }
5195 }
5196
5197 return OK;
5198}
5199
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005200status_t CameraService::handleGetRotateAndCrop(int out) {
5201 Mutex::Autolock lock(mServiceLock);
5202
5203 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
5204}
5205
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005206status_t CameraService::handleGetAutoframing(int out) {
5207 Mutex::Autolock lock(mServiceLock);
5208
5209 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
5210}
5211
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005212status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
5213 char *endPtr;
5214 errno = 0;
5215 String8 maskString8 = String8(args[1]);
5216 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
5217
5218 if (errno != 0) return BAD_VALUE;
5219 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
5220 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
5221
5222 Mutex::Autolock lock(mServiceLock);
5223
5224 mImageDumpMask = maskValue;
5225
5226 return OK;
5227}
5228
5229status_t CameraService::handleGetImageDumpMask(int out) {
5230 Mutex::Autolock lock(mServiceLock);
5231
5232 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
5233}
5234
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005235status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
5236 int muteValue = strtol(String8(args[1]), nullptr, 10);
5237 if (errno != 0) return BAD_VALUE;
5238
5239 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
5240 Mutex::Autolock lock(mServiceLock);
5241
5242 mOverrideCameraMuteMode = (muteValue == 1);
5243
5244 const auto clients = mActiveClientManager.getAll();
5245 for (auto& current : clients) {
5246 if (current != nullptr) {
5247 const auto basicClient = current->getValue();
5248 if (basicClient.get() != nullptr) {
5249 if (basicClient->supportsCameraMute()) {
5250 basicClient->setCameraMute(mOverrideCameraMuteMode);
5251 }
5252 }
5253 }
5254 }
5255
5256 return OK;
5257}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005258
Shuzhen Wang16610a62022-12-15 22:38:07 -08005259status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
5260 std::vector<int64_t> useCasesOverride;
5261 for (size_t i = 1; i < args.size(); i++) {
5262 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
5263 String8 arg8 = String8(args[i]);
5264 if (arg8 == "DEFAULT") {
5265 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
5266 } else if (arg8 == "PREVIEW") {
5267 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
5268 } else if (arg8 == "STILL_CAPTURE") {
5269 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
5270 } else if (arg8 == "VIDEO_RECORD") {
5271 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
5272 } else if (arg8 == "PREVIEW_VIDEO_STILL") {
5273 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
5274 } else if (arg8 == "VIDEO_CALL") {
5275 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
5276 } else if (arg8 == "CROPPED_RAW") {
5277 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
5278 } else {
5279 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg8.c_str());
5280 return BAD_VALUE;
5281 }
5282 useCasesOverride.push_back(useCase);
5283 }
5284
5285 Mutex::Autolock lock(mServiceLock);
5286 mStreamUseCaseOverrides = std::move(useCasesOverride);
5287
5288 return OK;
5289}
5290
5291void CameraService::handleClearStreamUseCaseOverrides() {
5292 Mutex::Autolock lock(mServiceLock);
5293 mStreamUseCaseOverrides.clear();
5294}
5295
Avichal Rakesh84147132021-11-11 17:47:11 -08005296status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005297 if (args.size() >= 3 && args[1] == String16("start")) {
5298 return startWatchingTags(args, outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005299 } else if (args.size() == 2 && args[1] == String16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005300 return stopWatchingTags(outFd);
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005301 } else if (args.size() == 2 && args[1] == String16("dump")) {
5302 return printWatchedTags(outFd);
5303 } else if (args.size() >= 2 && args[1] == String16("live")) {
5304 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005305 } else if (args.size() == 2 && args[1] == String16("clear")) {
5306 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005307 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005308 dprintf(outFd, "Camera service watch commands:\n"
5309 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
5310 " starts watching the provided tags for clients with provided package\n"
5311 " recognizes tag shorthands like '3a'\n"
5312 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005313 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005314 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005315 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005316 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08005317 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005318 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005319 return BAD_VALUE;
5320}
5321
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005322status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
5323 Mutex::Autolock lock(mLogLock);
5324 size_t tagsIdx; // index of '-m'
5325 String16 tags("");
5326 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != String16("-m"); tagsIdx++);
5327 if (tagsIdx < args.size() - 1) {
5328 tags = args[tagsIdx + 1];
5329 } else {
5330 dprintf(outFd, "No tags provided.\n");
5331 return BAD_VALUE;
5332 }
5333
5334 size_t clientsIdx; // index of '-c'
5335 String16 clients = kWatchAllClientsFlag; // watch all clients if no clients are provided
5336 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != String16("-c");
5337 clientsIdx++);
5338 if (clientsIdx < args.size() - 1) {
5339 clients = args[clientsIdx + 1];
5340 }
5341 parseClientsToWatchLocked(String8(clients));
5342
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005343 // track tags to initialize future clients with the monitoring information
5344 mMonitorTags = String8(tags);
5345
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005346 bool serviceLock = tryLock(mServiceLock);
5347 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005348 auto cameraClients = mActiveClientManager.getAll();
5349 for (const auto &clientDescriptor: cameraClients) {
5350 if (clientDescriptor == nullptr) { continue; }
5351 sp<BasicClient> client = clientDescriptor->getValue();
5352 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005353
5354 if (isClientWatchedLocked(client.get())) {
5355 client->startWatchingTags(mMonitorTags, outFd);
5356 numWatchedClients++;
5357 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005358 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005359 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
5360
5361 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005362 return OK;
5363}
5364
5365status_t CameraService::stopWatchingTags(int outFd) {
5366 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005367 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005368 mMonitorTags = String8::empty();
5369
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005370 mWatchedClientPackages.clear();
5371 mWatchedClientsDumpCache.clear();
5372
5373 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005374 auto cameraClients = mActiveClientManager.getAll();
5375 for (const auto &clientDescriptor : cameraClients) {
5376 if (clientDescriptor == nullptr) { continue; }
5377 sp<BasicClient> client = clientDescriptor->getValue();
5378 if (client.get() == nullptr) { continue; }
5379 client->stopWatchingTags(outFd);
5380 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005381 dprintf(outFd, "Stopped watching all clients.\n");
5382 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005383 return OK;
5384}
5385
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005386status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
5387 Mutex::Autolock lock(mLogLock);
5388 size_t clearedSize = mWatchedClientsDumpCache.size();
5389 mWatchedClientsDumpCache.clear();
5390 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
5391 return OK;
5392}
5393
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005394status_t CameraService::printWatchedTags(int outFd) {
5395 Mutex::Autolock logLock(mLogLock);
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08005396 std::set<String16> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005397
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005398 bool printedSomething = false; // tracks if any monitoring information was printed
5399 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005400
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005401 bool serviceLock = tryLock(mServiceLock);
5402 // get all watched clients that are currently connected
5403 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
5404 if (clientDescriptor == nullptr) { continue; }
5405
5406 sp<BasicClient> client = clientDescriptor->getValue();
5407 if (client.get() == nullptr) { continue; }
5408 if (!isClientWatchedLocked(client.get())) { continue; }
5409
5410 std::vector<std::string> dumpVector;
5411 client->dumpWatchedEventsToVector(dumpVector);
5412
5413 size_t printIdx = dumpVector.size();
5414 if (printIdx == 0) {
5415 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005416 }
5417
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005418 // Print tag dumps for active client
5419 const String8 &cameraId = clientDescriptor->getKey();
5420 String8 packageName8 = String8(client->getPackageName());
5421 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
5422 dprintf(outFd, "Client: %s (active)\n", printablePackageName);
5423 while(printIdx > 0) {
5424 printIdx--;
5425 dprintf(outFd, "%s:%s %s", cameraId.string(), printablePackageName,
5426 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005427 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005428 dprintf(outFd, "\n");
5429 packageName8.unlockBuffer();
5430 printedSomething = true;
5431
5432 connectedMonitoredClients.emplace(client->getPackageName());
5433 }
5434 if (serviceLock) { mServiceLock.unlock(); }
5435
5436 // Print entries in mWatchedClientsDumpCache for clients that are not connected
5437 for (const auto &kv: mWatchedClientsDumpCache) {
5438 const String16 &package = kv.first;
5439 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
5440 continue;
5441 }
5442
5443 dprintf(outFd, "Client: %s (cached)\n", String8(package).string());
5444 dprintf(outFd, "%s\n", kv.second.c_str());
5445 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005446 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005447
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005448 if (!printedSomething) {
5449 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005450 }
5451
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005452 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005453}
5454
Avichal Rakesh84147132021-11-11 17:47:11 -08005455// Print all events in vector `events' that came after lastPrintedEvent
5456void printNewWatchedEvents(int outFd,
5457 const char *cameraId,
5458 const String16 &packageName,
5459 const std::vector<std::string> &events,
5460 const std::string &lastPrintedEvent) {
5461 if (events.empty()) { return; }
5462
5463 // index of lastPrintedEvent in events.
5464 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
5465 size_t lastPrintedIdx;
5466 for (lastPrintedIdx = 0;
5467 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
5468 lastPrintedIdx++);
5469
5470 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
5471
5472 String8 packageName8(packageName);
5473 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
5474
5475 // print events in chronological order (latest event last)
5476 size_t idxToPrint = lastPrintedIdx;
5477 do {
5478 idxToPrint--;
5479 dprintf(outFd, "%s:%s %s", cameraId, printablePackageName, events[idxToPrint].c_str());
5480 } while (idxToPrint != 0);
5481
5482 packageName8.unlockBuffer();
5483}
5484
5485// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
5486// command should be interrupted if the user presses the return key, or if user loses any way to
5487// signal interrupt.
5488// If timeoutMs == 0, this function will always return false
5489bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
5490 struct timeval startTime;
5491 int startTimeError = gettimeofday(&startTime, nullptr);
5492 if (startTimeError) {
5493 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5494 return true;
5495 }
5496
5497 const nfds_t numFds = 1;
5498 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
5499
5500 struct timeval currTime;
5501 char buffer[2];
5502 while(true) {
5503 int currTimeError = gettimeofday(&currTime, nullptr);
5504 if (currTimeError) {
5505 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5506 return true;
5507 }
5508
5509 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
5510 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
5511 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
5512
5513 if (remainingTimeMs <= 0) {
5514 // No user interrupt within timeoutMs, don't interrupt watch command
5515 return false;
5516 }
5517
5518 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
5519 if (numFdsUpdated < 0) {
5520 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5521 return true;
5522 }
5523
5524 if (numFdsUpdated == 0) {
5525 // No user input within timeoutMs, don't interrupt watch command
5526 return false;
5527 }
5528
5529 if (!(pollFd.revents & POLLIN)) {
5530 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5531 return true;
5532 }
5533
5534 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
5535 if (sizeRead < 0) {
5536 dprintf(outFd, "Error reading user input. Exiting.\n");
5537 return true;
5538 }
5539
5540 if (sizeRead == 0) {
5541 // Reached end of input fd (can happen if input is piped)
5542 // User has no way to signal an interrupt, so interrupt here
5543 return true;
5544 }
5545
5546 if (buffer[0] == '\n') {
5547 // User pressed return, interrupt watch command.
5548 return true;
5549 }
5550 }
5551}
5552
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005553status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
5554 int inFd, int outFd) {
5555 // Figure out refresh interval, if present in args
5556 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005557 if (args.size() > 2) {
5558 size_t intervalIdx; // index of '-n'
5559 for (intervalIdx = 2; intervalIdx < args.size() && String16("-n") != args[intervalIdx];
5560 intervalIdx++);
5561
5562 size_t intervalValIdx = intervalIdx + 1;
5563 if (intervalValIdx < args.size()) {
5564 refreshTimeoutMs = strtol(String8(args[intervalValIdx].string()), nullptr, 10);
5565 if (errno) { return BAD_VALUE; }
5566 }
5567 }
5568
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005569 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
5570 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005571
Avichal Rakesh84147132021-11-11 17:47:11 -08005572 dprintf(outFd, "Press return to exit...\n\n");
Avichal Rakesha14d9832021-11-11 01:41:55 -08005573 std::map<String16, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005574
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005575 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005576 bool serviceLock = tryLock(mServiceLock);
5577 auto cameraClients = mActiveClientManager.getAll();
5578 if (serviceLock) { mServiceLock.unlock(); }
5579
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005580 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005581 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005582 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005583
5584 sp<BasicClient> client = clientDescriptor->getValue();
5585 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005586 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005587
Avichal Rakesha14d9832021-11-11 01:41:55 -08005588 const String16 &packageName = client->getPackageName();
5589 // This also initializes the map entries with an empty string
5590 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
5591
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005592 std::vector<std::string> latestEvents;
5593 client->dumpWatchedEventsToVector(latestEvents);
5594
5595 if (!latestEvents.empty()) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005596 String8 cameraId = clientDescriptor->getKey();
5597 const char *printableCameraId = cameraId.lockBuffer(cameraId.size());
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005598 printNewWatchedEvents(outFd,
Avichal Rakesha14d9832021-11-11 01:41:55 -08005599 printableCameraId,
5600 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005601 latestEvents,
5602 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08005603 packageNameToLastEvent[packageName] = latestEvents[0];
5604 cameraId.unlockBuffer();
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005605 }
5606 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005607 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005608 break;
5609 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005610 }
5611 return OK;
5612}
5613
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005614void CameraService::parseClientsToWatchLocked(String8 clients) {
5615 mWatchedClientPackages.clear();
5616
5617 const char *allSentinel = String8(kWatchAllClientsFlag).string();
5618
5619 char *tokenized = clients.lockBuffer(clients.size());
5620 char *savePtr;
5621 char *nextClient = strtok_r(tokenized, ",", &savePtr);
5622
5623 while (nextClient != nullptr) {
5624 if (strcmp(nextClient, allSentinel) == 0) {
5625 // Don't need to track any other package if 'all' is present
5626 mWatchedClientPackages.clear();
5627 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
5628 break;
5629 }
5630
5631 // track package names
5632 mWatchedClientPackages.emplace(nextClient);
5633 nextClient = strtok_r(nullptr, ",", &savePtr);
5634 }
5635 clients.unlockBuffer();
5636}
5637
Svet Ganova453d0d2018-01-11 15:37:58 -08005638status_t CameraService::printHelp(int out) {
5639 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07005640 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
5641 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
5642 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005643 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
5644 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
5645 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005646 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
5647 " Valid values 0=false, 1=true, 2=auto\n"
5648 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005649 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
5650 " Valid values 0=OFF, 1=ON for JPEG\n"
5651 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005652 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08005653 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
5654 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
5655 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
5656 " on. In case the number of usecases is smaller than the number of streams, the\n"
5657 " last use case is assigned to all the remaining streams. In case of multiple\n"
5658 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
5659 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
5660 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
5661 " clear-stream-use-case-override clear the stream use case override\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005662 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08005663 " help print this message\n");
5664}
5665
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005666bool CameraService::isClientWatched(const BasicClient *client) {
5667 Mutex::Autolock lock(mLogLock);
5668 return isClientWatchedLocked(client);
5669}
5670
5671bool CameraService::isClientWatchedLocked(const BasicClient *client) {
5672 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
5673 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
5674}
5675
Yin-Chia Yehdba03232019-08-19 15:54:28 -07005676int32_t CameraService::updateAudioRestriction() {
5677 Mutex::Autolock lock(mServiceLock);
5678 return updateAudioRestrictionLocked();
5679}
5680
5681int32_t CameraService::updateAudioRestrictionLocked() {
5682 int32_t mode = 0;
5683 // iterate through all active client
5684 for (const auto& i : mActiveClientManager.getAll()) {
5685 const auto clientSp = i->getValue();
5686 mode |= clientSp->getAudioRestriction();
5687 }
5688
5689 bool modeChanged = (mAudioRestriction != mode);
5690 mAudioRestriction = mode;
5691 if (modeChanged) {
5692 mAppOps.setCameraAudioRestriction(mode);
5693 }
5694 return mode;
5695}
5696
Cliff Wu646bd612021-11-23 23:21:29 +08005697status_t CameraService::checkIfInjectionCameraIsPresent(const String8& externalCamId,
5698 sp<BasicClient> clientSp) {
5699 std::unique_ptr<AutoConditionLock> lock =
5700 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
5701 status_t res = NO_ERROR;
5702 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
5703 ALOGW("Device %s is not usable!", externalCamId.string());
5704 mInjectionStatusListener->notifyInjectionError(
5705 externalCamId, UNKNOWN_TRANSACTION);
5706 clientSp->notifyError(
5707 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
5708 CaptureResultExtras());
5709
5710 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
5711 // other clients from connecting in mServiceLockWrapper if held
5712 mServiceLock.unlock();
5713
5714 // Clear caller identity temporarily so client disconnect PID checks work correctly
5715 int64_t token = CameraThreadState::clearCallingIdentity();
5716 clientSp->disconnect();
5717 CameraThreadState::restoreCallingIdentity(token);
5718
5719 // Reacquire mServiceLock
5720 mServiceLock.lock();
5721 }
5722
5723 return res;
5724}
5725
Cliff Wud3a05312021-04-26 23:07:31 +08005726void CameraService::clearInjectionParameters() {
5727 {
5728 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08005729 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08005730 mInjectionInternalCamId = "";
5731 }
5732 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08005733 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08005734}
5735
Mathias Agopian65ab4712010-07-14 17:59:35 -07005736}; // namespace android