blob: 0115023fac25b307f46e2881350003e7c2e36c53 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080024#include <cstdlib>
Ruben Brunkcc776712015-02-17 20:18:47 -080025#include <cstring>
26#include <ctime>
27#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080029#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <pthread.h>
Avichal Rakesh84147132021-11-11 17:47:11 -080031#include <poll.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080033#include <android/hardware/ICamera.h>
34#include <android/hardware/ICameraClient.h>
35
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -070036#include <aidl/AidlCameraService.h>
Alex Deymo9c2a2c22016-08-25 11:59:14 -070037#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080038#include <android-base/parseint.h>
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070039#include <android-base/stringprintf.h>
Joanne Chung02c13d02023-01-16 12:58:05 +000040#include <android/permission/PermissionChecker.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080041#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080042#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044#include <binder/MemoryBase.h>
45#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080046#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080047#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080048#include <binderthreadstate/CallerUtils.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070049#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070050#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080051#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080052#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070053#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070054#include "hidl/HidlCameraService.h"
55#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080056#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070057#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080059#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070060#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070061#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000062#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070063#include <utils/Errors.h>
64#include <utils/Log.h>
65#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070066#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080067#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080068#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080069#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080070#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070071#include <system/camera_metadata.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080072
Ruben Brunkb2119af2014-05-09 19:57:56 -070073#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070074
75#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070076#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070077#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070078#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000079#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070080#include "utils/CameraThreadState.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070081#include "utils/CameraServiceProxyWrapper.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070082
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080083namespace {
84 const char* kPermissionServiceName = "permission";
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080085 const char* kActivityServiceName = "activity";
86 const char* kSensorPrivacyServiceName = "sensor_privacy";
87 const char* kAppopsServiceName = "appops";
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080088}; // namespace anonymous
89
Mathias Agopian65ab4712010-07-14 17:59:35 -070090namespace android {
91
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070092using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080093using binder::Status;
Austin Borgerea931242021-12-13 23:10:41 +000094using namespace camera3;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070095using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -070096using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080097using hardware::ICamera;
98using hardware::ICameraClient;
99using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800100using hardware::camera2::ICameraInjectionCallback;
101using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800102using hardware::camera2::utils::CameraIdAndSessionConfiguration;
103using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800104
Mathias Agopian65ab4712010-07-14 17:59:35 -0700105// ----------------------------------------------------------------------------
106// Logging support -- this is for debugging only
107// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700108volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109
Steve Blockb8a80522011-12-20 16:23:08 +0000110#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
111#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700112
113static void setLogLevel(int level) {
114 android_atomic_write(level, &gLogLevel);
115}
116
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800117// Convenience methods for constructing binder::Status objects for error returns
118
119#define STATUS_ERROR(errorCode, errorString) \
120 binder::Status::fromServiceSpecificError(errorCode, \
121 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
122
123#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
124 binder::Status::fromServiceSpecificError(errorCode, \
125 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
126 __VA_ARGS__))
127
Mathias Agopian65ab4712010-07-14 17:59:35 -0700128// ----------------------------------------------------------------------------
129
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700130static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800131static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700132static const String16 sCameraPermission("android.permission.CAMERA");
133static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
134static const String16
135 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Shuzhen Wang695044d2020-03-06 09:02:23 -0800136static const String16 sCameraOpenCloseListenerPermission(
137 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Cliff Wud8cae102021-03-11 01:37:42 +0800138static const String16
139 sCameraInjectExternalCameraPermission("android.permission.CAMERA_INJECT_EXTERNAL_CAMERA");
Rucha Katakwardf223072021-06-15 10:21:00 -0700140const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800141static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
142static constexpr int32_t kSystemNativeClientState =
143 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700144
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800145const String8 CameraService::kOfflineDevice("offline-");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -0700146const String16 CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700147
Rucha Katakward9ea6452021-05-06 11:57:16 -0700148// Set to keep track of logged service error events.
149static std::set<String8> sServiceErrorEventSet;
150
Austin Borger74fca042022-05-23 12:41:21 -0700151CameraService::CameraService(
152 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper) :
153 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
154 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800155 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800156 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700157 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700158 mSoundRef(0), mInitialized(false),
159 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000160 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800161 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700162 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
163 if (mMemFd == -1) {
164 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
165 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700166}
167
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800168// The word 'System' here does not refer to clients only on the system
169// partition. They just need to have a android system uid.
170static bool doesClientHaveSystemUid() {
171 return (CameraThreadState::getCallingUid() < AID_APP_START);
172}
173
Charles Chena7b613c2023-01-24 21:57:33 +0000174// Enable processes with isolated AID to request the binder
175void CameraService::instantiate() {
176 CameraService::publish(true);
177}
178
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800179void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
180 if (name != String16(kAppopsServiceName)) {
181 return;
182 }
183
184 ALOGV("appops service registered. setting camera audio restriction");
185 mAppOps.setCameraAudioRestriction(mAudioRestriction);
186}
187
Iliyan Malchev8951a972011-04-14 16:55:59 -0700188void CameraService::onFirstRef()
189{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700190
Ruben Brunkcc776712015-02-17 20:18:47 -0800191 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800192
Iliyan Malchev8951a972011-04-14 16:55:59 -0700193 BnCameraService::onFirstRef();
194
Ruben Brunk99e69712015-05-26 17:25:07 -0700195 // Update battery life tracking if service is restarting
196 BatteryNotifier& notifier(BatteryNotifier::getInstance());
197 notifier.noteResetCamera();
198 notifier.noteResetFlashlight();
199
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800200 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800201
Emilian Peevf53f66e2017-04-11 14:29:43 +0100202 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800203 if (res == OK) {
204 mInitialized = true;
205 }
206
Svet Ganova453d0d2018-01-11 15:37:58 -0800207 mUidPolicy = new UidPolicy(this);
208 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800209 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
210 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800211 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800212
213 // appops function setCamerAudioRestriction uses getService which
214 // is blocking till the appops service is ready. To enable early
215 // boot availability for cameraservice, use checkService which is
216 // non blocking and register for notifications
217 sp<IServiceManager> sm = defaultServiceManager();
218 sp<IBinder> binder = sm->checkService(String16(kAppopsServiceName));
219 if (!binder) {
220 sm->registerForNotifications(String16(kAppopsServiceName), this);
221 } else {
222 mAppOps.setCameraAudioRestriction(mAudioRestriction);
223 }
224
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700225 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
226 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000227 // Deprecated, so it will fail to register on newer devices
228 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700229 __FUNCTION__);
230 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700231
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700232 if (!AidlCameraService::registerService(this)) {
233 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
234 }
235
Shuzhen Wang24b44152019-09-20 10:38:11 -0700236 // This needs to be last call in this function, so that it's as close to
237 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700238 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700239 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800240}
241
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800242status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800243 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100244
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800245 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000246 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800247 {
248 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800249
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800250 if (nullptr == mCameraProviderManager.get()) {
251 mCameraProviderManager = new CameraProviderManager();
252 res = mCameraProviderManager->initialize(this);
253 if (res != OK) {
254 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
255 __FUNCTION__, strerror(-res), res);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700256 logServiceError(String8::format("Unable to initialize camera provider manager"),
257 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800258 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100259 }
260 }
261
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800262
263 // Setup vendor tags before we call get_camera_info the first time
264 // because HAL might need to setup static vendor keys in get_camera_info
265 // TODO: maybe put this into CameraProviderManager::initialize()?
266 mCameraProviderManager->setUpVendorTags();
267
268 if (nullptr == mFlashlight.get()) {
269 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700270 }
271
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800272 res = mFlashlight->findFlashUnits();
273 if (res != OK) {
274 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
275 }
276
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000277 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800278 }
279
280
281 for (auto& cameraId : deviceIds) {
282 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800283 if (getCameraState(id8) == nullptr) {
284 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
285 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000286 if (unavailPhysicalIds.count(cameraId) > 0) {
287 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
288 String8 physicalId8 = String8(physicalId.c_str());
289 onDeviceStatusChanged(id8, physicalId8, CameraDeviceStatus::NOT_PRESENT);
290 }
291 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800292 }
293
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700294 // Derive primary rear/front cameras, and filter their charactierstics.
295 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700296 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700297 // Assume internal cameras are advertised from the same
298 // provider. If multiple providers are registered at different time,
299 // and each provider contains multiple internal color cameras, the current
300 // logic may filter the characteristics of more than one front/rear color
301 // cameras.
302 Mutex::Autolock l(mServiceLock);
303 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700304 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700305
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800306 return OK;
307}
308
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700309void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status,
310 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800311 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800312 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700313 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
314 i->getListenerUid())) {
315 ALOGV("Skipping torch callback for system-only camera device %s",
316 cameraId.c_str());
317 continue;
318 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700319 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
320 String16{cameraId});
321 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
322 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800323 }
324}
325
Mathias Agopian65ab4712010-07-14 17:59:35 -0700326CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800327 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800328 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800329 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800330 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700331}
332
Emilian Peevaee727d2017-05-04 16:35:48 +0100333void CameraService::onNewProviderRegistered() {
334 enumerateProviders();
335}
336
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700337void CameraService::filterAPI1SystemCameraLocked(
338 const std::vector<std::string> &normalDeviceIds) {
339 mNormalDeviceIdsWithoutSystemCamera.clear();
340 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700341 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
342 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
343 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
344 continue;
345 }
346 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700347 // All system camera ids will necessarily come after public camera
348 // device ids as per the HAL interface contract.
349 break;
350 }
351 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
352 }
353 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
354 mNormalDeviceIdsWithoutSystemCamera.size());
355}
356
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700357status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
358 auto state = getCameraState(cameraId);
359 if (state != nullptr) {
360 *kind = state->getSystemCameraKind();
361 return OK;
362 }
363 // Hidden physical camera ids won't have CameraState
364 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
365}
366
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800367void CameraService::updateCameraNumAndIds() {
368 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700369 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
370 // Excludes hidden secure cameras
371 mNumberOfCameras =
372 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
373 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800374 mNormalDeviceIds =
375 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700376 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800377}
378
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700379void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700380 // To claim to be S Performance primary cameras, the cameras must be
381 // backward compatible. So performance class primary camera Ids must be API1
382 // compatible.
383 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
384 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
385 int facing = -1;
386 int orientation = 0;
387 String8 cameraId8(cameraId.c_str());
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800388 int portraitRotation;
389 getDeviceVersion(cameraId8, /*overrideToPortrait*/false, /*out*/&portraitRotation,
390 /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700391 if (facing == -1) {
392 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
393 return;
394 }
395
396 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
397 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700398 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
399 if (res == OK) {
400 mPerfClassPrimaryCameraIds.insert(cameraId);
401 } else {
402 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
403 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
404 break;
405 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700406
407 if (facing == hardware::CAMERA_FACING_BACK) {
408 firstRearCameraSeen = true;
409 }
410 if (facing == hardware::CAMERA_FACING_FRONT) {
411 firstFrontCameraSeen = true;
412 }
413 }
414
415 if (firstRearCameraSeen && firstFrontCameraSeen) {
416 break;
417 }
418 }
419}
420
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100421void CameraService::addStates(const String8 id) {
422 std::string cameraId(id.c_str());
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700423 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100424 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
425 if (res != OK) {
426 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
427 return;
428 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000429 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700430 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
431 if (res != OK) {
432 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
433 return;
434 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000435 std::vector<std::string> physicalCameraIds;
436 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100437 std::set<String8> conflicting;
438 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
439 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
440 }
441
442 {
443 Mutex::Autolock lock(mCameraStatesLock);
444 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000445 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100446 }
447
448 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100449 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100450 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800451
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700452 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100453 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800454
455 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100456 logDeviceAdded(id, "Device added");
457}
458
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100459void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800460 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100461 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100462 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100463 mTorchStatusMap.removeItem(id);
464 }
465
466 {
467 Mutex::Autolock lock(mCameraStatesLock);
468 mCameraStates.erase(id);
469 }
470}
471
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800472void CameraService::onDeviceStatusChanged(const String8& id,
473 CameraDeviceStatus newHalStatus) {
474 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
475 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700476
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800477 StatusInternal newStatus = mapToInternal(newHalStatus);
478
Ruben Brunkcc776712015-02-17 20:18:47 -0800479 std::shared_ptr<CameraState> state = getCameraState(id);
480
481 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700482 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100483 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700484 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100485
486 // First add as absent to make sure clients are notified below
487 addStates(id);
488
489 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700490 } else {
491 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
492 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700493 return;
494 }
495
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800496 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800497
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800498 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800499 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700500 return;
501 }
502
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800503 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700504 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
505 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800506
507 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
508 // to this device until the status changes
509 updateStatus(StatusInternal::NOT_PRESENT, id);
510
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800511 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700512 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800513 // Don't do this in updateStatus to avoid deadlock over mServiceLock
514 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700515
Ruben Brunkcc776712015-02-17 20:18:47 -0800516 // Remove cached shim parameters
517 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700518
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800519 // Remove online as well as offline client from the list of active clients,
520 // if they are present
521 clientToDisconnectOnline = removeClientLocked(id);
522 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700523 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800524
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800525 disconnectClient(id, clientToDisconnectOnline);
526 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700527
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100528 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800529 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800530 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700531 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
532 newStatus));
533 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800534 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700535 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800536}
Igor Murashkincba2c162013-03-20 15:56:31 -0700537
Shuzhen Wang43858162020-01-10 13:42:15 -0800538void CameraService::onDeviceStatusChanged(const String8& id,
539 const String8& physicalId,
540 CameraDeviceStatus newHalStatus) {
541 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
542 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
543
544 StatusInternal newStatus = mapToInternal(newHalStatus);
545
546 std::shared_ptr<CameraState> state = getCameraState(id);
547
548 if (state == nullptr) {
549 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000550 __FUNCTION__, physicalId.string(), id.string());
Shuzhen Wang43858162020-01-10 13:42:15 -0800551 return;
552 }
553
554 StatusInternal logicalCameraStatus = state->getStatus();
555 if (logicalCameraStatus != StatusInternal::PRESENT &&
556 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
557 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
558 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
559 return;
560 }
561
562 bool updated = false;
563 if (newStatus == StatusInternal::PRESENT) {
564 updated = state->removeUnavailablePhysicalId(physicalId);
565 } else {
566 updated = state->addUnavailablePhysicalId(physicalId);
567 }
568
569 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800570 String8 idCombo = id + " : " + physicalId;
571 if (newStatus == StatusInternal::PRESENT) {
572 logDeviceAdded(idCombo,
573 String8::format("Device status changed to %d", newStatus));
574 } else {
575 logDeviceRemoved(idCombo,
576 String8::format("Device status changed to %d", newStatus));
577 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700578 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
579 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
580 if (getSystemCameraKind(id, &deviceKind) != OK) {
581 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
582 return;
583 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800584 String16 id16(id), physicalId16(physicalId);
585 Mutex::Autolock lock(mStatusListenerLock);
586 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700587 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
588 listener->getListenerPid(), listener->getListenerUid())) {
589 ALOGV("Skipping discovery callback for system-only camera device %s",
590 id.c_str());
591 continue;
592 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700593 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
594 mapToInterface(newStatus), id16, physicalId16);
595 listener->handleBinderStatus(ret,
596 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
597 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
598 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800599 }
600 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700601}
602
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800603void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
604 if (clientToDisconnect.get() != nullptr) {
605 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
606 __FUNCTION__, id.string());
607 // Notify the client of disconnection
608 clientToDisconnect->notifyError(
609 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
610 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800611 clientToDisconnect->disconnect();
612 }
613}
614
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800615void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800616 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700617 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
618 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
619 if (res != OK) {
620 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
621 cameraId.string());
622 return;
623 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800624 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700625 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800626}
627
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700628
629void CameraService::onTorchStatusChanged(const String8& cameraId,
630 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
631 Mutex::Autolock al(mTorchStatusMutex);
632 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
633}
634
Rucha Katakwar38284522021-11-10 11:25:21 -0800635void CameraService::broadcastTorchStrengthLevel(const String8& cameraId,
636 int32_t newStrengthLevel) {
637 Mutex::Autolock lock(mStatusListenerLock);
638 for (auto& i : mListenerList) {
Austin Borgere8e2c422022-05-12 13:45:24 -0700639 auto ret = i->getListener()->onTorchStrengthLevelChanged(String16{cameraId},
Rucha Katakwar38284522021-11-10 11:25:21 -0800640 newStrengthLevel);
Austin Borgere8e2c422022-05-12 13:45:24 -0700641 i->handleBinderStatus(ret,
642 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
643 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800644 }
645}
646
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800647void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700648 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800649 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
650 __FUNCTION__, cameraId.string(), newStatus);
651
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800652 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800653 status_t res = getTorchStatusLocked(cameraId, &status);
654 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700655 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
656 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800657 return;
658 }
659 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800660 return;
661 }
662
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800663 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800664 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800665 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
666 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800667 return;
668 }
669
Ruben Brunkcc776712015-02-17 20:18:47 -0800670 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700671 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700672 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700673 auto iter = mTorchUidMap.find(cameraId);
674 if (iter != mTorchUidMap.end()) {
675 int oldUid = iter->second.second;
676 int newUid = iter->second.first;
677 BatteryNotifier& notifier(BatteryNotifier::getInstance());
678 if (oldUid != newUid) {
679 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800680 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700681 notifier.noteFlashlightOff(cameraId, oldUid);
682 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800683 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700684 notifier.noteFlashlightOn(cameraId, newUid);
685 }
686 iter->second.second = newUid;
687 } else {
688 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800689 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700690 notifier.noteFlashlightOn(cameraId, oldUid);
691 } else {
692 notifier.noteFlashlightOff(cameraId, oldUid);
693 }
694 }
695 }
696 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700697 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800698}
699
Joanne Chung02c13d02023-01-16 12:58:05 +0000700static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
701 permission::PermissionChecker permissionChecker;
702 AttributionSourceState attributionSource{};
703 attributionSource.pid = callingPid;
704 attributionSource.uid = callingUid;
705 bool checkPermissionForSystemCamera = permissionChecker.checkPermissionForPreflight(
706 sSystemCameraPermission, attributionSource, String16(), AppOpsManager::OP_NONE)
707 != permission::PermissionChecker::PERMISSION_HARD_DENIED;
708 bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
709 sCameraPermission, attributionSource, String16(), AppOpsManager::OP_NONE)
710 != permission::PermissionChecker::PERMISSION_HARD_DENIED;
711 return checkPermissionForSystemCamera && checkPermissionForCamera;
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700712}
713
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800714Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700715 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100716 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700717 bool hasSystemCameraPermissions =
718 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
719 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700720 switch (type) {
721 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700722 if (hasSystemCameraPermissions) {
723 *numCameras = static_cast<int>(mNormalDeviceIds.size());
724 } else {
725 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
726 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800727 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700728 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700729 if (hasSystemCameraPermissions) {
730 *numCameras = mNumberOfCameras;
731 } else {
732 *numCameras = mNumberOfCamerasWithoutSystemCamera;
733 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800734 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700735 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800736 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700737 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800738 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
739 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700740 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800741 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700742}
743
Austin Borger18b30a72022-10-27 12:20:29 -0700744Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800745 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700746 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100747 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700748 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
749 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
750 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
751 "characteristics for system only device %s: ", cameraIdStr.c_str());
752 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100753
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800754 if (!mInitialized) {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700755 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800756 return STATUS_ERROR(ERROR_DISCONNECTED,
757 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700758 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700759 bool hasSystemCameraPermissions =
760 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
761 CameraThreadState::getCallingUid());
762 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
763 if (hasSystemCameraPermissions) {
764 cameraIdBound = mNumberOfCameras;
765 }
766 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800767 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
768 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700769 }
770
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800771 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -0700772 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800773 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borger18b30a72022-10-27 12:20:29 -0700774 cameraIdStr.c_str(), overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100775 if (err != OK) {
776 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
777 "Error retrieving camera info from device %d: %s (%d)", cameraId,
778 strerror(-err), err);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700779 logServiceError(String8::format("Error retrieving camera info from device %d",cameraId),
780 ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -0800781 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100782
Ruben Brunkcc776712015-02-17 20:18:47 -0800783 return ret;
784}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700785
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800786std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700787 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
788 auto callingPid = CameraThreadState::getCallingPid();
789 auto callingUid = CameraThreadState::getCallingUid();
Joanne Chung02c13d02023-01-16 12:58:05 +0000790 permission::PermissionChecker permissionChecker;
791 AttributionSourceState attributionSource{};
792 attributionSource.pid = callingPid;
793 attributionSource.uid = callingUid;
794 bool checkPermissionForSystemCamera = permissionChecker.checkPermissionForPreflight(
795 sSystemCameraPermission, attributionSource, String16(), AppOpsManager::OP_NONE)
796 != permission::PermissionChecker::PERMISSION_HARD_DENIED;
797 if (checkPermissionForSystemCamera || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700798 deviceIds = &mNormalDeviceIds;
799 }
800 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800801 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700802 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800803 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800804 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800805
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700806 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800807}
808
809String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
810 Mutex::Autolock lock(mServiceLock);
811 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800812}
813
814Status CameraService::getCameraCharacteristics(const String16& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -0700815 int targetSdkVersion, bool overrideToPortrait, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700816 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700817 if (!cameraInfo) {
818 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800819 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700820 }
821
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800822 if (!mInitialized) {
823 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700824 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800825 return STATUS_ERROR(ERROR_DISCONNECTED,
826 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700827 }
828
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700829 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
830 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
831 "characteristics for system only device %s: ", String8(cameraId).string());
832 }
833
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800834 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800835
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700836
837 std::string cameraIdStr = String8(cameraId).string();
838 bool overrideForPerfClass =
839 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
840 cameraIdStr, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100841 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borger18b30a72022-10-27 12:20:29 -0700842 cameraIdStr, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100843 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700844 if (res == NAME_NOT_FOUND) {
845 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
846 "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
847 strerror(-res), res);
848 } else {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700849 logServiceError(String8::format("Unable to retrieve camera characteristics for "
850 "device %s.", String8(cameraId).string()),ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700851 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
852 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
853 strerror(-res), res);
854 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700855 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700856 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
857 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
858 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
859 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
860 "for device %s", String8(cameraId).string());
861 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700862 int callingPid = CameraThreadState::getCallingPid();
863 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100864 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700865 // If it's not calling from cameraserver, check the permission only if
866 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
867 // it would've already been checked in shouldRejectSystemCameraConnection.
Joanne Chung02c13d02023-01-16 12:58:05 +0000868 permission::PermissionChecker permissionChecker;
869 AttributionSourceState attributionSource{};
870 attributionSource.pid = callingPid;
871 attributionSource.uid = callingUid;
872 bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
873 sCameraPermission, attributionSource, String16(), AppOpsManager::OP_NONE)
874 != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Emilian Peeve20c6372018-08-14 18:45:53 +0100875 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700876 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Joanne Chung02c13d02023-01-16 12:58:05 +0000877 !checkPermissionForCamera) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100878 res = cameraInfo->removePermissionEntries(
879 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
880 &tagsRemoved);
881 if (res != OK) {
882 cameraInfo->clear();
883 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
884 " characteristics needing camera permission for device %s: %s (%d)",
885 String8(cameraId).string(), strerror(-res), res);
886 }
887 }
888
889 if (!tagsRemoved.empty()) {
890 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
891 tagsRemoved.data(), tagsRemoved.size());
892 if (res != OK) {
893 cameraInfo->clear();
894 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
895 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
896 strerror(-res), res);
897 }
898 }
899
Zhijun He2b59be82013-09-25 10:14:30 -0700900 return ret;
901}
902
Rucha Katakwar38284522021-11-10 11:25:21 -0800903Status CameraService::getTorchStrengthLevel(const String16& cameraId,
904 int32_t* torchStrength) {
905 ATRACE_CALL();
906 Mutex::Autolock l(mServiceLock);
907 if (!mInitialized) {
908 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
909 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
910 }
911
912 if(torchStrength == NULL) {
913 ALOGE("%s: strength level must not be null.", __FUNCTION__);
914 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
915 }
916
917 status_t res = mCameraProviderManager->getTorchStrengthLevel(String8(cameraId).string(),
918 torchStrength);
919 if (res != OK) {
920 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
921 "strength level for device %s: %s (%d)", String8(cameraId).string(),
922 strerror(-res), res);
923 }
924 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
925 return Status::ok();
926}
927
Ruben Brunkcc776712015-02-17 20:18:47 -0800928String8 CameraService::getFormattedCurrentTime() {
929 time_t now = time(nullptr);
930 char formattedTime[64];
931 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
932 return String8(formattedTime);
933}
934
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800935Status CameraService::getCameraVendorTagDescriptor(
936 /*out*/
937 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700938 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800939 if (!mInitialized) {
940 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800941 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800942 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800943 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
944 if (globalDescriptor != nullptr) {
945 *desc = *(globalDescriptor.get());
946 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800947 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800948}
949
Emilian Peev71c73a22017-03-21 16:35:51 +0000950Status CameraService::getCameraVendorTagCache(
951 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
952 ATRACE_CALL();
953 if (!mInitialized) {
954 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
955 return STATUS_ERROR(ERROR_DISCONNECTED,
956 "Camera subsystem not available");
957 }
958 sp<VendorTagDescriptorCache> globalCache =
959 VendorTagDescriptorCache::getGlobalVendorTagCache();
960 if (globalCache != nullptr) {
961 *cache = *(globalCache.get());
962 }
963 return Status::ok();
964}
965
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700966void CameraService::clearCachedVariables() {
967 BasicClient::BasicClient::sCameraService = nullptr;
968}
969
Austin Borger18b30a72022-10-27 12:20:29 -0700970std::pair<int, IPCTransport> CameraService::getDeviceVersion(const String8& cameraId,
971 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700972 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800973
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800974 int deviceVersion = 0;
975
Emilian Peevf53f66e2017-04-11 14:29:43 +0100976 status_t res;
977 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +0000978 IPCTransport transport = IPCTransport::INVALID;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100979 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +0000980 &maxVersion, &transport);
981 if (res != OK || transport == IPCTransport::INVALID) {
982 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
983 cameraId.string());
984 return std::make_pair(-1, IPCTransport::INVALID) ;
985 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100986 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800987
Emilian Peevf53f66e2017-04-11 14:29:43 +0100988 hardware::CameraInfo info;
989 if (facing) {
Austin Borger18b30a72022-10-27 12:20:29 -0700990 res = mCameraProviderManager->getCameraInfo(cameraId.string(), overrideToPortrait,
991 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +0000992 if (res != OK) {
993 return std::make_pair(-1, IPCTransport::INVALID);
994 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100995 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -0700996 if (orientation) {
997 *orientation = info.orientation;
998 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800999 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001000
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001001 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001002}
1003
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001004Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001005 switch(err) {
1006 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001007 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001008 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001009 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1010 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001011 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001012 return STATUS_ERROR(ERROR_DISCONNECTED,
1013 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001014 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001015 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1016 "Camera HAL encountered error %d: %s",
1017 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001018 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001019}
1020
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001021Status CameraService::makeClient(const sp<CameraService>& cameraService,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001022 const sp<IInterface>& cameraCb, const String16& packageName, bool systemNativeClient,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001023 const std::optional<String16>& featureId, const String8& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001024 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001025 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001026 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
1027 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001028 // For HIDL devices
1029 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1030 // Create CameraClient based on device version reported by the HAL.
1031 int deviceVersion = deviceVersionAndTransport.first;
1032 switch(deviceVersion) {
1033 case CAMERA_DEVICE_API_VERSION_1_0:
1034 ALOGE("Camera using old HAL version: %d", deviceVersion);
1035 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1036 "Camera device \"%s\" HAL version %d no longer supported",
1037 cameraId.string(), deviceVersion);
1038 break;
1039 case CAMERA_DEVICE_API_VERSION_3_0:
1040 case CAMERA_DEVICE_API_VERSION_3_1:
1041 case CAMERA_DEVICE_API_VERSION_3_2:
1042 case CAMERA_DEVICE_API_VERSION_3_3:
1043 case CAMERA_DEVICE_API_VERSION_3_4:
1044 case CAMERA_DEVICE_API_VERSION_3_5:
1045 case CAMERA_DEVICE_API_VERSION_3_6:
1046 case CAMERA_DEVICE_API_VERSION_3_7:
1047 break;
1048 default:
1049 // Should not be reachable
1050 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1051 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1052 "Camera device \"%s\" has unknown HAL version %d",
1053 cameraId.string(), deviceVersion);
1054 }
1055 }
1056 if (effectiveApiLevel == API_1) { // Camera1 API route
1057 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001058 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
1059 packageName, featureId, cameraId, api1CameraId, facing, sensorOrientation,
Austin Borger18b30a72022-10-27 12:20:29 -07001060 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait);
1061 ALOGI("%s: Camera1 API (legacy), override to portrait %d", __FUNCTION__,
1062 overrideToPortrait);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001063 } else { // Camera2 API route
1064 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1065 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001066 *client = new CameraDeviceClient(cameraService, tmp,
1067 cameraService->mCameraServiceProxyWrapper, packageName, systemNativeClient,
1068 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
Austin Borger18b30a72022-10-27 12:20:29 -07001069 overrideForPerfClass, overrideToPortrait);
1070 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001071 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001072 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001073}
1074
Ruben Brunk6267b532015-04-30 17:44:07 -07001075String8 CameraService::toString(std::set<userid_t> intSet) {
1076 String8 s("");
1077 bool first = true;
1078 for (userid_t i : intSet) {
1079 if (first) {
1080 s.appendFormat("%d", i);
1081 first = false;
1082 } else {
1083 s.appendFormat(", %d", i);
1084 }
1085 }
1086 return s;
1087}
1088
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001089int32_t CameraService::mapToInterface(TorchModeStatus status) {
1090 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1091 switch (status) {
1092 case TorchModeStatus::NOT_AVAILABLE:
1093 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1094 break;
1095 case TorchModeStatus::AVAILABLE_OFF:
1096 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1097 break;
1098 case TorchModeStatus::AVAILABLE_ON:
1099 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1100 break;
1101 default:
1102 ALOGW("Unknown new flash status: %d", status);
1103 }
1104 return serviceStatus;
1105}
1106
1107CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1108 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1109 switch (status) {
1110 case CameraDeviceStatus::NOT_PRESENT:
1111 serviceStatus = StatusInternal::NOT_PRESENT;
1112 break;
1113 case CameraDeviceStatus::PRESENT:
1114 serviceStatus = StatusInternal::PRESENT;
1115 break;
1116 case CameraDeviceStatus::ENUMERATING:
1117 serviceStatus = StatusInternal::ENUMERATING;
1118 break;
1119 default:
1120 ALOGW("Unknown new HAL device status: %d", status);
1121 }
1122 return serviceStatus;
1123}
1124
1125int32_t CameraService::mapToInterface(StatusInternal status) {
1126 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1127 switch (status) {
1128 case StatusInternal::NOT_PRESENT:
1129 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1130 break;
1131 case StatusInternal::PRESENT:
1132 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1133 break;
1134 case StatusInternal::ENUMERATING:
1135 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1136 break;
1137 case StatusInternal::NOT_AVAILABLE:
1138 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1139 break;
1140 case StatusInternal::UNKNOWN:
1141 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1142 break;
1143 default:
1144 ALOGW("Unknown new internal device status: %d", status);
1145 }
1146 return serviceStatus;
1147}
1148
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001149Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001150 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001151
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001152 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -08001153 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001154 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001155 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001156 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001157 sp<ICameraClient>{nullptr}, id, cameraId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001158 internalPackageName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001159 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Austin Borger18b30a72022-10-27 12:20:29 -07001160 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001161 ).isOk()) {
1162 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001163 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001164 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001165}
1166
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001167Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001168 /*out*/
1169 CameraParameters* parameters) {
1170
1171 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1172
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001173 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001174
1175 if (parameters == NULL) {
1176 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001177 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001178 }
1179
Ruben Brunkcc776712015-02-17 20:18:47 -08001180 String8 id = String8::format("%d", cameraId);
1181
1182 // Check if we already have parameters
1183 {
1184 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001185 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001186 auto cameraState = getCameraState(id);
1187 if (cameraState == nullptr) {
1188 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001189 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1190 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001191 }
1192 CameraParameters p = cameraState->getShimParams();
1193 if (!p.isEmpty()) {
1194 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001195 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001196 }
1197 }
1198
Jayant Chowdhary12361932018-08-27 14:46:13 -07001199 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001200 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001201 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001202 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001203 // Error already logged by callee
1204 return ret;
1205 }
1206
1207 // Check for parameters again
1208 {
1209 // Scope for service lock
1210 Mutex::Autolock lock(mServiceLock);
1211 auto cameraState = getCameraState(id);
1212 if (cameraState == nullptr) {
1213 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001214 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1215 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001216 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001217 CameraParameters p = cameraState->getShimParams();
1218 if (!p.isEmpty()) {
1219 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001220 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001221 }
1222 }
1223
Ruben Brunkcc776712015-02-17 20:18:47 -08001224 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1225 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001226 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001227}
1228
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001229// Can camera service trust the caller based on the calling UID?
1230static bool isTrustedCallingUid(uid_t uid) {
1231 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001232 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001233 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001234 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001235 return true;
1236 default:
1237 return false;
1238 }
1239}
1240
Nicholas Sauera3620332019-04-03 14:05:17 -07001241static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1242 PermissionController pc;
1243 uid = pc.getPackageUid(packageName, 0);
1244 if (uid <= 0) {
1245 ALOGE("Unknown package: '%s'", String8(packageName).string());
1246 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1247 return BAD_VALUE;
1248 }
1249
1250 if (userId < 0) {
1251 ALOGE("Invalid user: %d", userId);
1252 dprintf(err, "Invalid user: %d\n", userId);
1253 return BAD_VALUE;
1254 }
1255
1256 uid = multiuser_get_uid(userId, uid);
1257 return NO_ERROR;
1258}
1259
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001260Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001261 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1262 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001263
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001264#ifdef __BRILLO__
1265 UNUSED(clientName8);
1266 UNUSED(clientUid);
1267 UNUSED(clientPid);
1268 UNUSED(originalClientPid);
1269#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001270 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1271 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001272 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001273 return allowed;
1274 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001275#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001276
Jayant Chowdhary12361932018-08-27 14:46:13 -07001277 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001278
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001279 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001280 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1281 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001282 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1283 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001284 }
1285
Ruben Brunkcc776712015-02-17 20:18:47 -08001286 if (getCameraState(cameraId) == nullptr) {
1287 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1288 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001289 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1290 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001291 }
1292
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001293 status_t err = checkIfDeviceIsUsable(cameraId);
1294 if (err != NO_ERROR) {
1295 switch(err) {
1296 case -ENODEV:
1297 case -EBUSY:
1298 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1299 "No camera device with ID \"%s\" currently available", cameraId.string());
1300 default:
1301 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1302 "Unknown error connecting to ID \"%s\"", cameraId.string());
1303 }
1304 }
1305 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001306}
1307
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001308Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001309 const String8& clientName8, int& clientUid, int& clientPid,
1310 /*out*/int& originalClientPid) const {
Joanne Chung02c13d02023-01-16 12:58:05 +00001311 permission::PermissionChecker permissionChecker;
1312 AttributionSourceState attributionSource{};
1313
Jayant Chowdhary12361932018-08-27 14:46:13 -07001314 int callingPid = CameraThreadState::getCallingPid();
1315 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001316
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001317 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001318 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001319 clientUid = callingUid;
1320 } else if (!isTrustedCallingUid(callingUid)) {
1321 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1322 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001323 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1324 "Untrusted caller (calling PID %d, UID %d) trying to "
1325 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1326 callingPid, callingUid, cameraId.string(),
1327 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001328 }
1329
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001330 // Check if we can trust clientPid
1331 if (clientPid == USE_CALLING_PID) {
1332 clientPid = callingPid;
1333 } else if (!isTrustedCallingUid(callingUid)) {
1334 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1335 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001336 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1337 "Untrusted caller (calling PID %d, UID %d) trying to "
1338 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1339 callingPid, callingUid, cameraId.string(),
1340 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001341 }
1342
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001343 if (shouldRejectSystemCameraConnection(cameraId)) {
1344 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1345 cameraId.c_str());
1346 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1347 "available", cameraId.string());
1348 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001349 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1350 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1351 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1352 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1353 "found while trying to query device kind", cameraId.string());
1354
1355 }
1356
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001357 // If it's not calling from cameraserver, check the permission if the
1358 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1359 // android.permission.SYSTEM_CAMERA for system only camera devices).
Joanne Chung02c13d02023-01-16 12:58:05 +00001360 attributionSource.pid = clientPid;
1361 attributionSource.uid = clientUid;
1362 attributionSource.packageName = clientName8;
1363 bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
1364 sCameraPermission, attributionSource, String16(), AppOpsManager::OP_NONE)
1365 != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001366 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001367 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001368 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001369 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1370 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1371 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001372 }
1373
Svet Ganova453d0d2018-01-11 15:37:58 -08001374 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001375 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001376 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001377 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1378 clientPid, clientUid);
1379 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001380 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1381 "calling UID %d proc state %" PRId32 ")",
1382 clientName8.string(), clientUid, clientPid, cameraId.string(),
1383 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001384 }
1385
Michael Grooverd1d435a2018-12-18 17:39:42 -08001386 // If sensor privacy is enabled then prevent access to the camera
1387 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1388 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1389 return STATUS_ERROR_FMT(ERROR_DISABLED,
1390 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1391 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1392 }
1393
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001394 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1395 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001396 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001397 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001398
Ruben Brunk6267b532015-04-30 17:44:07 -07001399 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001400
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001401 // For non-system clients : Only allow clients who are being used by the current foreground
1402 // device user, unless calling from our own process.
1403 if (!doesClientHaveSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001404 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001405 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1406 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1407 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001408 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1409 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1410 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001411 }
1412
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001413 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001414}
1415
1416status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1417 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001418 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001419 if (cameraState == nullptr) {
1420 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1421 cameraId.string());
1422 return -ENODEV;
1423 }
1424
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001425 StatusInternal currentStatus = cameraState->getStatus();
1426 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001427 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1428 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001429 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001430 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001431 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1432 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001433 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001434 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001435
Ruben Brunkcc776712015-02-17 20:18:47 -08001436 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001437}
1438
Ruben Brunkcc776712015-02-17 20:18:47 -08001439void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001440 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001441
Ruben Brunkcc776712015-02-17 20:18:47 -08001442 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001443 auto clientDescriptor =
1444 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001445 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001446 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1447
1448 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1449 String8(client->getPackageName()));
1450
1451 if (evicted.size() > 0) {
1452 // This should never happen - clients should already have been removed in disconnect
1453 for (auto& i : evicted) {
1454 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1455 __FUNCTION__, i->getKey().string());
1456 }
1457
1458 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1459 __FUNCTION__);
1460 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001461
1462 // And register a death notification for the client callback. Do
1463 // this last to avoid Binder policy where a nested Binder
1464 // transaction might be pre-empted to service the client death
1465 // notification if the client process dies before linkToDeath is
1466 // invoked.
1467 sp<IBinder> remoteCallback = client->getRemote();
1468 if (remoteCallback != nullptr) {
1469 remoteCallback->linkToDeath(this);
1470 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001471}
1472
1473status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1474 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001475 int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001476 /*out*/
1477 sp<BasicClient>* client,
1478 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001479 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001480 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001481 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001482 DescriptorPtr clientDescriptor;
1483 {
1484 if (effectiveApiLevel == API_1) {
1485 // If we are using API1, any existing client for this camera ID with the same remote
1486 // should be returned rather than evicted to allow MediaRecorder to work properly.
1487
1488 auto current = mActiveClientManager.get(cameraId);
1489 if (current != nullptr) {
1490 auto clientSp = current->getValue();
1491 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001492 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001493 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001494 " API level, evicting prior client...");
1495 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001496 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001497 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001498 *client = clientSp;
1499 return NO_ERROR;
1500 }
1501 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001502 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001503 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001504
Ruben Brunkcc776712015-02-17 20:18:47 -08001505 // Get current active client PIDs
1506 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1507 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001508
Emilian Peev8131a262017-02-01 12:33:43 +00001509 std::vector<int> priorityScores(ownerPids.size());
1510 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001511
Emilian Peev8131a262017-02-01 12:33:43 +00001512 // Get priority scores of all active PIDs
1513 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1514 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1515 /*out*/&priorityScores[0]);
1516 if (err != OK) {
1517 ALOGE("%s: Priority score query failed: %d",
1518 __FUNCTION__, err);
1519 return err;
1520 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001521
Ruben Brunkcc776712015-02-17 20:18:47 -08001522 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001523 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001524 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001525 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001526 resource_policy::ClientPriority(priorityScores[i], states[i],
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001527 /* isVendorClient won't get copied over*/ false,
1528 /* oomScoreOffset won't get copied over*/ 0));
Ruben Brunkcc776712015-02-17 20:18:47 -08001529 }
1530 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001531
Ruben Brunkcc776712015-02-17 20:18:47 -08001532 // Get state for the given cameraId
1533 auto state = getCameraState(cameraId);
1534 if (state == nullptr) {
1535 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1536 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001537 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001538 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001539 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001540
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001541 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1542 int32_t actualState = states[states.size() - 1];
1543
1544 // Make descriptor for incoming client. We store the oomScoreOffset
1545 // since we might need it later on new handleEvictionsLocked and
1546 // ProcessInfoService would not take that into account.
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001547 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001548 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001549 state->getConflicting(), actualScore, clientPid, actualState,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001550 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001551
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001552 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1553
Ruben Brunkcc776712015-02-17 20:18:47 -08001554 // Find clients that would be evicted
1555 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1556
1557 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1558 // background, so we cannot do evictions
1559 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1560 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1561 " priority).", clientPid);
1562
1563 sp<BasicClient> clientSp = clientDescriptor->getValue();
1564 String8 curTime = getFormattedCurrentTime();
1565 auto incompatibleClients =
1566 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1567
1568 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001569 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001570 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001571 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001572
1573 for (auto& i : incompatibleClients) {
1574 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001575 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1576 i->getKey().string(),
1577 String8{i->getValue()->getPackageName()}.string(),
1578 i->getOwnerId(), i->getPriority().getScore(),
1579 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001580 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001581 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001582 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001583 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001584 }
1585
1586 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001587 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001588 mEventLog.add(msg);
1589
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001590 auto current = mActiveClientManager.get(cameraId);
1591 if (current != nullptr) {
1592 return -EBUSY; // CAMERA_IN_USE
1593 } else {
1594 return -EUSERS; // MAX_CAMERAS_IN_USE
1595 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001596 }
1597
1598 for (auto& i : evicted) {
1599 sp<BasicClient> clientSp = i->getValue();
1600 if (clientSp.get() == nullptr) {
1601 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1602
1603 // TODO: Remove this
1604 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1605 __FUNCTION__);
1606 mActiveClientManager.remove(i);
1607 continue;
1608 }
1609
1610 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1611 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001612 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001613
Ruben Brunkcc776712015-02-17 20:18:47 -08001614 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001615 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001616 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1617 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001618 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001619 i->getOwnerId(), i->getPriority().getScore(),
1620 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001621 packageName.string(), clientPid, clientPriority.getScore(),
1622 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001623
1624 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001625 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001626 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001627 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001628 }
1629
Ruben Brunkcc776712015-02-17 20:18:47 -08001630 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1631 // other clients from connecting in mServiceLockWrapper if held
1632 mServiceLock.unlock();
1633
1634 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001635 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001636
1637 // Destroy evicted clients
1638 for (auto& i : evictedClients) {
1639 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001640 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001641 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001642
Jayant Chowdhary12361932018-08-27 14:46:13 -07001643 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001644
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001645 for (const auto& i : evictedClients) {
1646 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1647 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1648 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1649 if (ret == TIMED_OUT) {
1650 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1651 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1652 mActiveClientManager.toString().string());
1653 return -EBUSY;
1654 }
1655 if (ret != NO_ERROR) {
1656 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1657 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1658 ret, mActiveClientManager.toString().string());
1659 return ret;
1660 }
1661 }
1662
1663 evictedClients.clear();
1664
Ruben Brunkcc776712015-02-17 20:18:47 -08001665 // Once clients have been disconnected, relock
1666 mServiceLock.lock();
1667
1668 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1669 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1670 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001671 }
1672
Ruben Brunkcc776712015-02-17 20:18:47 -08001673 *partial = clientDescriptor;
1674 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001675}
1676
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001677Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001678 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001679 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001680 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001681 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001682 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001683 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001684 bool overrideToPortrait,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001685 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001686 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001687
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001688 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001689 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001690
1691 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001692 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001693 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001694 clientPackageName,/*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07001695 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
1696 overrideToPortrait, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001697
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001698 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001699 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001700 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001701 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001702 }
1703
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001704 *device = client;
1705 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001706}
1707
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001708bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1709 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001710 // If the client is not a vendor client, don't add listener if
1711 // a) the camera is a publicly hidden secure camera OR
1712 // b) the camera is a system only camera and the client doesn't
1713 // have android.permission.SYSTEM_CAMERA permissions.
1714 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1715 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1716 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001717 return true;
1718 }
1719 return false;
1720}
1721
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001722bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1723 // Rules for rejection:
1724 // 1) If cameraserver tries to access this camera device, accept the
1725 // connection.
1726 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001727 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001728 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1729 // and the serving thread is a non hwbinder thread, the client must have
1730 // android.permission.SYSTEM_CAMERA permissions to connect.
1731
1732 int cPid = CameraThreadState::getCallingPid();
1733 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001734 bool systemClient = doesClientHaveSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001735 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1736 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001737 // This isn't a known camera ID, so it's not a system camera
1738 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1739 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001740 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001741
1742 // (1) Cameraserver trying to connect, accept.
1743 if (CameraThreadState::getCallingPid() == getpid()) {
1744 return false;
1745 }
1746 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001747 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001748 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1749 return true;
1750 }
1751 // (3) Here we only check for permissions if it is a system only camera device. This is since
1752 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1753 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1754 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001755 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001756 !hasPermissionsForSystemCamera(cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001757 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1758 cameraId.c_str());
1759 return true;
1760 }
1761
1762 return false;
1763}
1764
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001765Status CameraService::connectDevice(
1766 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001767 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001768 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001769 const std::optional<String16>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001770 int clientUid, int oomScoreOffset, int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001771 bool overrideToPortrait,
Ruben Brunkcc776712015-02-17 20:18:47 -08001772 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001773 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001774
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001775 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001776 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001777 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001778 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001779 String16 clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001780 int callingPid = CameraThreadState::getCallingPid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001781 bool systemNativeClient = false;
1782 if (doesClientHaveSystemUid() && (clientPackageNameAdj.size() == 0)) {
1783 std::string systemClient =
1784 StringPrintf("client.pid<%d>", CameraThreadState::getCallingPid());
1785 clientPackageNameAdj = String16(systemClient.c_str());
1786 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001787 }
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001788
1789 if (oomScoreOffset < 0) {
1790 String8 msg =
1791 String8::format("Cannot increase the priority of a client %s pid %d for "
1792 "camera id %s", String8(clientPackageNameAdj).string(), callingPid,
1793 id.string());
1794 ALOGE("%s: %s", __FUNCTION__, msg.string());
1795 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1796 }
1797
Austin Borger9bfa0a72022-08-03 17:50:40 -07001798 userid_t clientUserId = multiuser_get_user_id(clientUid);
1799 int callingUid = CameraThreadState::getCallingUid();
1800 if (clientUid == USE_CALLING_UID) {
1801 clientUserId = multiuser_get_user_id(callingUid);
1802 }
1803
1804 if (mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borger5f7abe22022-04-26 15:55:10 -07001805 String8 msg =
1806 String8::format("Camera disabled by device policy");
1807 ALOGE("%s: %s", __FUNCTION__, msg.string());
1808 return STATUS_ERROR(ERROR_DISABLED, msg.string());
1809 }
1810
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001811 // enforce system camera permissions
1812 if (oomScoreOffset > 0 &&
Austin Borger86a588e2022-05-23 12:41:58 -07001813 !hasPermissionsForSystemCamera(callingPid, CameraThreadState::getCallingUid()) &&
1814 !isTrustedCallingUid(CameraThreadState::getCallingUid())) {
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001815 String8 msg =
1816 String8::format("Cannot change the priority of a client %s pid %d for "
1817 "camera id %s without SYSTEM_CAMERA permissions",
1818 String8(clientPackageNameAdj).string(), callingPid, id.string());
1819 ALOGE("%s: %s", __FUNCTION__, msg.string());
1820 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.string());
1821 }
1822
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001823 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001824 /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient,clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001825 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
Austin Borger18b30a72022-10-27 12:20:29 -07001826 targetSdkVersion, overrideToPortrait, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001827
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001828 if(!ret.isOk()) {
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001829 logRejected(id, callingPid, String8(clientPackageNameAdj), ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001830 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001831 }
1832
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001833 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07001834 Mutex::Autolock lock(mServiceLock);
1835
1836 // Clear the previous cached logs and reposition the
1837 // file offset to beginning of the file to log new data.
1838 // If either truncate or lseek fails, close the previous file and create a new one.
1839 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
1840 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
1841 // Close the previous memfd.
1842 close(mMemFd);
1843 // If failure to wipe the data, then create a new file and
1844 // assign the new value to mMemFd.
1845 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
1846 if (mMemFd == -1) {
1847 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
1848 }
1849 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001850 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001851}
1852
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001853String16 CameraService::getPackageNameFromUid(int clientUid) {
1854 String16 packageName("");
1855
1856 sp<IServiceManager> sm = defaultServiceManager();
1857 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
1858 if (binder == 0) {
1859 ALOGE("Cannot get permission service");
1860 // Return empty package name and the further interaction
1861 // with camera will likely fail
1862 return packageName;
1863 }
1864
1865 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
1866 Vector<String16> packages;
1867
1868 permCtrl->getPackagesForUid(clientUid, packages);
1869
1870 if (packages.isEmpty()) {
1871 ALOGE("No packages for calling UID %d", clientUid);
1872 // Return empty package name and the further interaction
1873 // with camera will likely fail
1874 return packageName;
1875 }
1876
1877 // Arbitrarily pick the first name in the list
1878 packageName = packages[0];
1879
1880 return packageName;
1881}
1882
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001883template<class CALLBACK, class CLIENT>
1884Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001885 int api1CameraId, const String16& clientPackageNameMaybe, bool systemNativeClient,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001886 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001887 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001888 bool overrideToPortrait, /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001889 binder::Status ret = binder::Status::ok();
1890
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001891 bool isNonSystemNdk = false;
1892 String16 clientPackageName;
1893 if (clientPackageNameMaybe.size() <= 0) {
1894 // NDK calls don't come with package names, but we need one for various cases.
1895 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
1896 // do exist. For all authentication cases, all packages under the same UID get the
1897 // same permissions, so picking any associated package name is sufficient. For some
1898 // other cases, this may give inaccurate names for clients in logs.
1899 isNonSystemNdk = true;
1900 int packageUid = (clientUid == USE_CALLING_UID) ?
1901 CameraThreadState::getCallingUid() : clientUid;
1902 clientPackageName = getPackageNameFromUid(packageUid);
1903 } else {
1904 clientPackageName = clientPackageNameMaybe;
1905 }
1906
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001907 String8 clientName8(clientPackageName);
1908
1909 int originalClientPid = 0;
1910
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001911 int packagePid = (clientPid == USE_CALLING_PID) ?
1912 CameraThreadState::getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001913 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001914 "Camera API version %d", packagePid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001915 static_cast<int>(effectiveApiLevel));
1916
Shuzhen Wang316781a2020-08-18 18:11:01 -07001917 nsecs_t openTimeNs = systemTime();
1918
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001919 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001920 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07001921 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07001922
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001923 {
1924 // Acquire mServiceLock and prevent other clients from connecting
1925 std::unique_ptr<AutoConditionLock> lock =
1926 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1927
1928 if (lock == nullptr) {
1929 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1930 , clientPid);
1931 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1932 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1933 cameraId.string(), clientName8.string(), clientPid);
1934 }
1935
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001936 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001937 if(!(ret = validateConnectLocked(cameraId, clientName8,
1938 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1939 return ret;
1940 }
1941
1942 // Check the shim parameters after acquiring lock, if they have already been updated and
1943 // we were doing a shim update, return immediately
1944 if (shimUpdateOnly) {
1945 auto cameraState = getCameraState(cameraId);
1946 if (cameraState != nullptr) {
1947 if (!cameraState->getShimParams().isEmpty()) return ret;
1948 }
1949 }
1950
1951 status_t err;
1952
1953 sp<BasicClient> clientTmp = nullptr;
1954 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1955 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001956 IInterface::asBinder(cameraCb), clientName8, oomScoreOffset, systemNativeClient,
1957 /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001958 switch (err) {
1959 case -ENODEV:
1960 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1961 "No camera device with ID \"%s\" currently available",
1962 cameraId.string());
1963 case -EBUSY:
1964 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1965 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1966 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001967 case -EUSERS:
1968 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1969 "Too many cameras already open, cannot open camera \"%s\"",
1970 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001971 default:
1972 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1973 "Unexpected error %s (%d) opening camera \"%s\"",
1974 strerror(-err), err, cameraId.string());
1975 }
1976 }
1977
1978 if (clientTmp.get() != nullptr) {
1979 // Handle special case for API1 MediaRecorder where the existing client is returned
1980 device = static_cast<CLIENT*>(clientTmp.get());
1981 return ret;
1982 }
1983
1984 // give flashlight a chance to close devices if necessary.
1985 mFlashlight->prepareDeviceOpen(cameraId);
1986
Austin Borger18b30a72022-10-27 12:20:29 -07001987 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001988 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07001989 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
1990 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001991 if (facing == -1) {
1992 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1993 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1994 "Unable to get camera device \"%s\" facing", cameraId.string());
1995 }
1996
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001997 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001998 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1999 mPerfClassPrimaryCameraIds, cameraId.string(), targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002000 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
2001 clientFeatureId, cameraId, api1CameraId, facing, orientation,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07002002 clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002003 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
Austin Borger18b30a72022-10-27 12:20:29 -07002004 overrideToPortrait, /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002005 return ret;
2006 }
2007 client = static_cast<CLIENT*>(tmp.get());
2008
2009 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2010 __FUNCTION__);
2011
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002012 String8 monitorTags = isClientWatched(client.get()) ? mMonitorTags : String8("");
2013 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002014 if (err != OK) {
2015 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002016 // Errors could be from the HAL module open call or from AppOpsManager
2017 switch(err) {
2018 case BAD_VALUE:
2019 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2020 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
2021 case -EBUSY:
2022 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2023 "Camera \"%s\" is already open", cameraId.string());
2024 case -EUSERS:
2025 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2026 "Too many cameras already open, cannot open camera \"%s\"",
2027 cameraId.string());
2028 case PERMISSION_DENIED:
2029 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2030 "No permission to open camera \"%s\"", cameraId.string());
2031 case -EACCES:
2032 return STATUS_ERROR_FMT(ERROR_DISABLED,
2033 "Camera \"%s\" disabled by policy", cameraId.string());
2034 case -ENODEV:
2035 default:
2036 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2037 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
2038 strerror(-err), err);
2039 }
2040 }
2041
2042 // Update shim paremeters for legacy clients
2043 if (effectiveApiLevel == API_1) {
2044 // Assume we have always received a Client subclass for API1
2045 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2046 String8 rawParams = shimClient->getParameters();
2047 CameraParameters params(rawParams);
2048
2049 auto cameraState = getCameraState(cameraId);
2050 if (cameraState != nullptr) {
2051 cameraState->setShimParams(params);
2052 } else {
2053 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
2054 __FUNCTION__, cameraId.string());
2055 }
2056 }
2057
Ravneetaeb20dc2022-03-30 05:33:03 +00002058 // Enable/disable camera service watchdog
2059 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2060
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002061 // Set rotate-and-crop override behavior
2062 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2063 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Austin Borger18b30a72022-10-27 12:20:29 -07002064 } else if (overrideToPortrait && portraitRotation != 0) {
2065 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2066 switch (portraitRotation) {
2067 case 90:
2068 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2069 break;
2070 case 180:
2071 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2072 break;
2073 case 270:
2074 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2075 break;
2076 default:
2077 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2078 break;
2079 }
2080 client->setRotateAndCropOverride(rotateAndCropMode);
Emilian Peev13f35ad2022-04-27 11:28:48 -07002081 } else {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002082 client->setRotateAndCropOverride(
2083 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2084 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2085 }
2086
2087 // Set autoframing override behaviour
2088 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2089 client->setAutoframingOverride(mOverrideAutoframingMode);
2090 } else {
2091 client->setAutoframingOverride(
2092 mCameraServiceProxyWrapper->getAutoframingOverride(
2093 clientPackageName));
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002094 }
2095
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002096 // Set camera muting behavior
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002097 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08002098 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002099 if (client->supportsCameraMute()) {
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002100 client->setCameraMute(
2101 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2102 } else if (isCameraPrivacyEnabled) {
2103 // no camera mute supported, but privacy is on! => disconnect
2104 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2105 String8(client->getPackageName()).string(), cameraId.string());
2106 // Do not hold mServiceLock while disconnecting clients, but
2107 // retain the condition blocking other clients from connecting
2108 // in mServiceLockWrapper if held.
2109 mServiceLock.unlock();
2110 // Clear caller identity temporarily so client disconnect PID
2111 // checks work correctly
2112 int64_t token = CameraThreadState::clearCallingIdentity();
2113 // Note AppOp to trigger the "Unblock" dialog
2114 client->noteAppOp();
2115 client->disconnect();
2116 CameraThreadState::restoreCallingIdentity(token);
2117 // Reacquire mServiceLock
2118 mServiceLock.lock();
2119
2120 return STATUS_ERROR_FMT(ERROR_DISABLED,
2121 "Camera \"%s\" disabled due to camera mute", cameraId.string());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002122 }
2123
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002124 if (shimUpdateOnly) {
2125 // If only updating legacy shim parameters, immediately disconnect client
2126 mServiceLock.unlock();
2127 client->disconnect();
2128 mServiceLock.lock();
2129 } else {
2130 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002131 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002132 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002133
2134 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002135 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002136 } // lock is destroyed, allow further connect calls
2137
2138 // Important: release the mutex here so the client can call back into the service from its
2139 // destructor (can be at the end of the call)
2140 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002141
2142 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002143 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002144 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002145
Cliff Wud3a05312021-04-26 23:07:31 +08002146 {
2147 Mutex::Autolock lock(mInjectionParametersLock);
2148 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2149 mInjectionInitPending = false;
2150 status_t res = NO_ERROR;
2151 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2152 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002153 sp<BasicClient> clientSp = clientDescriptor->getValue();
2154 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2155 if(res != OK) {
2156 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2157 "No camera device with ID \"%s\" currently available",
2158 mInjectionExternalCamId.string());
2159 }
2160 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002161 if (res != OK) {
2162 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2163 }
2164 } else {
2165 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
2166 __FUNCTION__, mInjectionInternalCamId.string());
2167 res = NO_INIT;
2168 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2169 }
2170 }
2171 }
2172
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002173 return ret;
2174}
2175
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002176status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
2177 if (offlineClient.get() == nullptr) {
2178 return BAD_VALUE;
2179 }
2180
2181 {
2182 // Acquire mServiceLock and prevent other clients from connecting
2183 std::unique_ptr<AutoConditionLock> lock =
2184 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2185
2186 if (lock == nullptr) {
2187 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2188 , __FUNCTION__, offlineClient->getClientPid());
2189 return TIMED_OUT;
2190 }
2191
2192 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2193 if (onlineClientDesc.get() == nullptr) {
2194 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2195 cameraId.c_str());
2196 return BAD_VALUE;
2197 }
2198
2199 // Offline clients do not evict or conflict with other online devices. Resource sharing
2200 // conflicts are handled by the camera provider which will either succeed or fail before
2201 // reaching this method.
2202 const auto& onlinePriority = onlineClientDesc->getPriority();
2203 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2204 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
2205 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002206 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002207 // native clients don't have offline processing support.
2208 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002209 if (offlineClientDesc == nullptr) {
2210 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2211 return BAD_VALUE;
2212 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002213
2214 // Allow only one offline device per camera
2215 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2216 if (!incompatibleClients.empty()) {
2217 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2218 return BAD_VALUE;
2219 }
2220
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002221 String8 monitorTags = isClientWatched(offlineClient.get()) ? mMonitorTags : String8("");
2222 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002223 if (err != OK) {
2224 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2225 return err;
2226 }
2227
2228 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2229 if (evicted.size() > 0) {
2230 for (auto& i : evicted) {
2231 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
2232 __FUNCTION__, i->getKey().string());
2233 }
2234
2235 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2236 "properly", __FUNCTION__);
2237
2238 return BAD_VALUE;
2239 }
2240
2241 logConnectedOffline(offlineClientDesc->getKey(),
2242 static_cast<int>(offlineClientDesc->getOwnerId()),
2243 String8(offlineClient->getPackageName()));
2244
2245 sp<IBinder> remoteCallback = offlineClient->getRemote();
2246 if (remoteCallback != nullptr) {
2247 remoteCallback->linkToDeath(this);
2248 }
2249 } // lock is destroyed, allow further connect calls
2250
2251 return OK;
2252}
2253
Rucha Katakwar38284522021-11-10 11:25:21 -08002254Status CameraService::turnOnTorchWithStrengthLevel(const String16& cameraId, int32_t torchStrength,
2255 const sp<IBinder>& clientBinder) {
2256 Mutex::Autolock lock(mServiceLock);
2257
2258 ATRACE_CALL();
2259 if (clientBinder == nullptr) {
2260 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2261 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2262 "Torch client binder in null.");
2263 }
2264
2265 String8 id = String8(cameraId.string());
2266 int uid = CameraThreadState::getCallingUid();
2267
2268 if (shouldRejectSystemCameraConnection(id)) {
2269 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
2270 "for system only device %s: ", id.string());
2271 }
2272
2273 // verify id is valid
2274 auto state = getCameraState(id);
2275 if (state == nullptr) {
2276 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
2277 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2278 "Camera ID \"%s\" is a not valid camera ID", id.string());
2279 }
2280
2281 StatusInternal cameraStatus = state->getStatus();
2282 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2283 cameraStatus != StatusInternal::PRESENT) {
2284 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(),
2285 (int)cameraStatus);
2286 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2287 "Camera ID \"%s\" is a not valid camera ID", id.string());
2288 }
2289
2290 {
2291 Mutex::Autolock al(mTorchStatusMutex);
2292 TorchModeStatus status;
2293 status_t err = getTorchStatusLocked(id, &status);
2294 if (err != OK) {
2295 if (err == NAME_NOT_FOUND) {
2296 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2297 "Camera \"%s\" does not have a flash unit", id.string());
2298 }
2299 ALOGE("%s: getting current torch status failed for camera %s",
2300 __FUNCTION__, id.string());
2301 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2302 "Error changing torch strength level for camera \"%s\": %s (%d)",
2303 id.string(), strerror(-err), err);
2304 }
2305
2306 if (status == TorchModeStatus::NOT_AVAILABLE) {
2307 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2308 ALOGE("%s: torch mode of camera %s is not available because "
2309 "camera is in use.", __FUNCTION__, id.string());
2310 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2311 "Torch for camera \"%s\" is not available due to an existing camera user",
2312 id.string());
2313 } else {
2314 ALOGE("%s: torch mode of camera %s is not available due to "
2315 "insufficient resources", __FUNCTION__, id.string());
2316 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2317 "Torch for camera \"%s\" is not available due to insufficient resources",
2318 id.string());
2319 }
2320 }
2321 }
2322
2323 {
2324 Mutex::Autolock al(mTorchUidMapMutex);
2325 updateTorchUidMapLocked(cameraId, uid);
2326 }
2327 // Check if the current torch strength level is same as the new one.
2328 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
2329 id.string(), torchStrength);
2330
2331 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(id, torchStrength);
2332
2333 if (err != OK) {
2334 int32_t errorCode;
2335 String8 msg;
2336 switch (err) {
2337 case -ENOSYS:
2338 msg = String8::format("Camera \"%s\" has no flashlight.",
2339 id.string());
2340 errorCode = ERROR_ILLEGAL_ARGUMENT;
2341 break;
2342 case -EBUSY:
2343 msg = String8::format("Camera \"%s\" is in use",
2344 id.string());
2345 errorCode = ERROR_CAMERA_IN_USE;
2346 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002347 case -EINVAL:
2348 msg = String8::format("Torch strength level %d is not within the "
2349 "valid range.", torchStrength);
2350 errorCode = ERROR_ILLEGAL_ARGUMENT;
2351 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002352 default:
2353 msg = String8::format("Changing torch strength level failed.");
2354 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002355 }
2356 ALOGE("%s: %s", __FUNCTION__, msg.string());
2357 return STATUS_ERROR(errorCode, msg.string());
2358 }
2359
2360 {
2361 // update the link to client's death
2362 // Store the last client that turns on each camera's torch mode.
2363 Mutex::Autolock al(mTorchClientMapMutex);
2364 ssize_t index = mTorchClientMap.indexOfKey(id);
2365 if (index == NAME_NOT_FOUND) {
2366 mTorchClientMap.add(id, clientBinder);
2367 } else {
2368 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2369 mTorchClientMap.replaceValueAt(index, clientBinder);
2370 }
2371 clientBinder->linkToDeath(this);
2372 }
2373
2374 int clientPid = CameraThreadState::getCallingPid();
2375 const char *id_cstr = id.c_str();
2376 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
2377 __FUNCTION__, id_cstr, torchStrength, clientPid);
2378 if (!shouldSkipTorchStrengthUpdates) {
2379 broadcastTorchStrengthLevel(id, torchStrength);
2380 }
2381 return Status::ok();
2382}
2383
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002384Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002385 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002386 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002387
2388 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002389 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002390 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002391 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2392 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002393 }
2394
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002395 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07002396 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002397
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002398 if (shouldRejectSystemCameraConnection(id)) {
2399 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
2400 " for system only device %s: ", id.string());
2401 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002402 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08002403 auto state = getCameraState(id);
2404 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002405 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002406 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2407 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002408 }
2409
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002410 StatusInternal cameraStatus = state->getStatus();
2411 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002412 cameraStatus != StatusInternal::NOT_AVAILABLE) {
2413 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002414 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2415 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002416 }
2417
2418 {
2419 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002420 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002421 status_t err = getTorchStatusLocked(id, &status);
2422 if (err != OK) {
2423 if (err == NAME_NOT_FOUND) {
2424 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2425 "Camera \"%s\" does not have a flash unit", id.string());
2426 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002427 ALOGE("%s: getting current torch status failed for camera %s",
2428 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002429 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2430 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
2431 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002432 }
2433
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002434 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002435 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002436 ALOGE("%s: torch mode of camera %s is not available because "
2437 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002438 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2439 "Torch for camera \"%s\" is not available due to an existing camera user",
2440 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002441 } else {
2442 ALOGE("%s: torch mode of camera %s is not available due to "
2443 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002444 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2445 "Torch for camera \"%s\" is not available due to insufficient resources",
2446 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002447 }
2448 }
2449 }
2450
Ruben Brunk99e69712015-05-26 17:25:07 -07002451 {
2452 // Update UID map - this is used in the torch status changed callbacks, so must be done
2453 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002454 Mutex::Autolock al(mTorchUidMapMutex);
Rucha Katakwar38284522021-11-10 11:25:21 -08002455 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07002456 }
2457
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002458 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002459
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002460 if (err != OK) {
2461 int32_t errorCode;
2462 String8 msg;
2463 switch (err) {
2464 case -ENOSYS:
2465 msg = String8::format("Camera \"%s\" has no flashlight",
2466 id.string());
2467 errorCode = ERROR_ILLEGAL_ARGUMENT;
2468 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08002469 case -EBUSY:
2470 msg = String8::format("Camera \"%s\" is in use",
2471 id.string());
2472 errorCode = ERROR_CAMERA_IN_USE;
2473 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002474 default:
2475 msg = String8::format(
2476 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
2477 id.string(), enabled, strerror(-err), err);
2478 errorCode = ERROR_INVALID_OPERATION;
2479 }
2480 ALOGE("%s: %s", __FUNCTION__, msg.string());
Rucha Katakward9ea6452021-05-06 11:57:16 -07002481 logServiceError(msg,errorCode);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002482 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002483 }
2484
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002485 {
2486 // update the link to client's death
2487 Mutex::Autolock al(mTorchClientMapMutex);
2488 ssize_t index = mTorchClientMap.indexOfKey(id);
2489 if (enabled) {
2490 if (index == NAME_NOT_FOUND) {
2491 mTorchClientMap.add(id, clientBinder);
2492 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07002493 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002494 mTorchClientMap.replaceValueAt(index, clientBinder);
2495 }
2496 clientBinder->linkToDeath(this);
2497 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07002498 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002499 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002500 }
2501
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002502 int clientPid = CameraThreadState::getCallingPid();
2503 const char *id_cstr = id.c_str();
2504 const char *torchState = enabled ? "on" : "off";
2505 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
2506 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002507 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002508}
2509
Rucha Katakwar38284522021-11-10 11:25:21 -08002510void CameraService::updateTorchUidMapLocked(const String16& cameraId, int uid) {
2511 String8 id = String8(cameraId.string());
2512 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
2513 mTorchUidMap[id].first = uid;
2514 mTorchUidMap[id].second = uid;
2515 } else {
2516 // Set the pending UID
2517 mTorchUidMap[id].first = uid;
2518 }
2519}
2520
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002521Status CameraService::notifySystemEvent(int32_t eventId,
2522 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002523 const int pid = CameraThreadState::getCallingPid();
2524 const int selfPid = getpid();
2525
2526 // Permission checks
2527 if (pid != selfPid) {
2528 // Ensure we're being called by system_server, or similar process with
2529 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002530 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002531 const int uid = CameraThreadState::getCallingUid();
2532 ALOGE("Permission Denial: cannot send updates to camera service about system"
2533 " events from pid=%d, uid=%d", pid, uid);
2534 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09002535 "No permission to send updates to camera service about system events"
2536 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002537 }
2538 }
2539
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002540 ATRACE_CALL();
2541
Ruben Brunk36597b22015-03-20 22:15:57 -07002542 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002543 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002544 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002545 // from a system server crash
2546 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002547 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002548 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002549 break;
2550 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02002551 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
2552 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
2553 // Notify CameraProviderManager for lazy HALs
2554 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
2555 std::to_string(args[0]));
2556 break;
2557 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002558 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002559 default: {
2560 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2561 eventId);
2562 break;
2563 }
2564 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002565 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002566}
2567
Emilian Peev53722fa2019-02-22 17:47:20 -08002568void CameraService::notifyMonitoredUids() {
2569 Mutex::Autolock lock(mStatusListenerLock);
2570
2571 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002572 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07002573 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
2574 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08002575 }
2576}
2577
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002578Status CameraService::notifyDeviceStateChange(int64_t newState) {
2579 const int pid = CameraThreadState::getCallingPid();
2580 const int selfPid = getpid();
2581
2582 // Permission checks
2583 if (pid != selfPid) {
2584 // Ensure we're being called by system_server, or similar process with
2585 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002586 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002587 const int uid = CameraThreadState::getCallingUid();
2588 ALOGE("Permission Denial: cannot send updates to camera service about device"
2589 " state changes from pid=%d, uid=%d", pid, uid);
2590 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2591 "No permission to send updates to camera service about device state"
2592 " changes from pid=%d, uid=%d", pid, uid);
2593 }
2594 }
2595
2596 ATRACE_CALL();
2597
Austin Borger18b30a72022-10-27 12:20:29 -07002598 {
2599 Mutex::Autolock lock(mServiceLock);
2600 mDeviceState = newState;
2601 }
2602
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07002603 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002604
2605 return Status::ok();
2606}
2607
Emilian Peev8b64f282021-03-25 16:49:57 -07002608Status CameraService::notifyDisplayConfigurationChange() {
2609 ATRACE_CALL();
2610 const int callingPid = CameraThreadState::getCallingPid();
2611 const int selfPid = getpid();
2612
2613 // Permission checks
2614 if (callingPid != selfPid) {
2615 // Ensure we're being called by system_server, or similar process with
2616 // permissions to notify the camera service about system events
2617 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2618 const int uid = CameraThreadState::getCallingUid();
2619 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2620 " changes from pid=%d, uid=%d", callingPid, uid);
2621 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2622 "No permission to send updates to camera service about orientation"
2623 " changes from pid=%d, uid=%d", callingPid, uid);
2624 }
2625 }
2626
2627 Mutex::Autolock lock(mServiceLock);
2628
2629 // Don't do anything if rotate-and-crop override via cmd is active
2630 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2631
2632 const auto clients = mActiveClientManager.getAll();
2633 for (auto& current : clients) {
2634 if (current != nullptr) {
2635 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07002636 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
2637 basicClient->setRotateAndCropOverride(
2638 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2639 basicClient->getPackageName(),
2640 basicClient->getCameraFacing(),
2641 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07002642 }
2643 }
2644 }
2645
2646 return Status::ok();
2647}
2648
2649Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002650 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2651 ATRACE_CALL();
2652 if (!concurrentCameraIds) {
2653 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2654 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2655 }
2656
2657 if (!mInitialized) {
2658 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002659 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002660 return STATUS_ERROR(ERROR_DISCONNECTED,
2661 "Camera subsystem is not available");
2662 }
2663 // First call into the provider and get the set of concurrent camera
2664 // combinations
2665 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002666 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002667 for (auto &combination : concurrentCameraCombinations) {
2668 std::vector<std::string> validCombination;
2669 for (auto &cameraId : combination) {
2670 // if the camera state is not present, skip
2671 String8 cameraIdStr(cameraId.c_str());
2672 auto state = getCameraState(cameraIdStr);
2673 if (state == nullptr) {
2674 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2675 continue;
2676 }
2677 StatusInternal status = state->getStatus();
2678 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2679 continue;
2680 }
2681 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2682 continue;
2683 }
2684 validCombination.push_back(cameraId);
2685 }
2686 if (validCombination.size() != 0) {
2687 concurrentCameraIds->push_back(std::move(validCombination));
2688 }
2689 }
2690 return Status::ok();
2691}
2692
2693Status CameraService::isConcurrentSessionConfigurationSupported(
2694 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002695 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002696 if (!isSupported) {
2697 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2698 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2699 }
2700
2701 if (!mInitialized) {
2702 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2703 return STATUS_ERROR(ERROR_DISCONNECTED,
2704 "Camera subsystem is not available");
2705 }
2706
2707 // Check for camera permissions
2708 int callingPid = CameraThreadState::getCallingPid();
2709 int callingUid = CameraThreadState::getCallingUid();
Joanne Chung02c13d02023-01-16 12:58:05 +00002710 permission::PermissionChecker permissionChecker;
2711 AttributionSourceState attributionSource{};
2712 attributionSource.pid = callingPid;
2713 attributionSource.uid = callingUid;
2714 bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
2715 sCameraPermission, attributionSource, String16(), AppOpsManager::OP_NONE)
2716 != permission::PermissionChecker::PERMISSION_HARD_DENIED;
2717 if ((callingPid != getpid()) && !checkPermissionForCamera) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002718 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2719 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2720 "android.permission.CAMERA needed to call"
2721 "isConcurrentSessionConfigurationSupported");
2722 }
2723
2724 status_t res =
2725 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002726 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
2727 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002728 if (res != OK) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07002729 logServiceError(String8::format("Unable to query session configuration support"),
2730 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002731 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2732 "support %s (%d)", strerror(-res), res);
2733 }
2734 return Status::ok();
2735}
2736
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002737Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2738 /*out*/
2739 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002740 return addListenerHelper(listener, cameraStatuses);
2741}
2742
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002743binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2744 std::vector<hardware::CameraStatus>* cameraStatuses) {
2745 return addListenerHelper(listener, cameraStatuses, false, true);
2746}
2747
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002748Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2749 /*out*/
2750 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002751 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002752
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002753 ATRACE_CALL();
2754
Igor Murashkinbfc99152013-02-27 12:55:20 -08002755 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002756
Ruben Brunk3450ba72015-06-16 11:00:37 -07002757 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002758 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002759 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002760 }
2761
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002762 auto clientUid = CameraThreadState::getCallingUid();
2763 auto clientPid = CameraThreadState::getCallingPid();
Joanne Chung02c13d02023-01-16 12:58:05 +00002764 permission::PermissionChecker permissionChecker;
2765 AttributionSourceState attributionSource{};
2766 attributionSource.uid = clientUid;
2767 attributionSource.pid = clientPid;
2768 bool openCloseCallbackAllowed = permissionChecker.checkPermissionForPreflight(
2769 sCameraOpenCloseListenerPermission, attributionSource, String16(),
2770 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002771
Igor Murashkinbfc99152013-02-27 12:55:20 -08002772 Mutex::Autolock lock(mServiceLock);
2773
Ruben Brunkcc776712015-02-17 20:18:47 -08002774 {
2775 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002776 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002777 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002778 ALOGW("%s: Tried to add listener %p which was already subscribed",
2779 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002780 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002781 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002782 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002783
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002784 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002785 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2786 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002787 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08002788 if (ret != NO_ERROR) {
2789 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2790 strerror(-ret), ret);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002791 logServiceError(msg,ERROR_ILLEGAL_ARGUMENT);
Emilian Peev53722fa2019-02-22 17:47:20 -08002792 ALOGE("%s: %s", __FUNCTION__, msg.string());
2793 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2794 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002795 // The listener still needs to be added to the list of listeners, regardless of what
2796 // permissions the listener process has / whether it is a vendor listener. Since it might be
2797 // eligible to listen to other camera ids.
2798 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002799 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002800 }
2801
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002802 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002803 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002804 Mutex::Autolock lock(mCameraStatesLock);
2805 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002806 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07002807 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
2808 openCloseCallbackAllowed ? i.second->getClientPackage() : String8::empty());
Igor Murashkincba2c162013-03-20 15:56:31 -07002809 }
2810 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002811 // Remove the camera statuses that should be hidden from the client, we do
2812 // this after collecting the states in order to avoid holding
2813 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2814 // the same time.
2815 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2816 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2817 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2818 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2819 ALOGE("%s: Invalid camera id %s, skipping status update",
2820 __FUNCTION__, s.cameraId.c_str());
2821 return true;
2822 }
2823 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2824 clientUid);}), cameraStatuses->end());
2825
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002826 //cameraStatuses will have non-eligible camera ids removed.
2827 std::set<String16> idsChosenForCallback;
2828 for (const auto &s : *cameraStatuses) {
2829 idsChosenForCallback.insert(String16(s.cameraId));
2830 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002831
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002832 /*
2833 * Immediately signal current torch status to this listener only
2834 * This may be a subset of all the devices, so don't include it in the response directly
2835 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002836 {
2837 Mutex::Autolock al(mTorchStatusMutex);
2838 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002839 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002840 // The camera id is visible to the client. Fine to send torch
2841 // callback.
2842 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2843 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2844 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002845 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002846 }
2847
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002848 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002849}
Ruben Brunkcc776712015-02-17 20:18:47 -08002850
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002851Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002852 ATRACE_CALL();
2853
Igor Murashkinbfc99152013-02-27 12:55:20 -08002854 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2855
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002856 if (listener == 0) {
2857 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002858 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002859 }
2860
Igor Murashkinbfc99152013-02-27 12:55:20 -08002861 Mutex::Autolock lock(mServiceLock);
2862
Ruben Brunkcc776712015-02-17 20:18:47 -08002863 {
2864 Mutex::Autolock lock(mStatusListenerLock);
2865 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002866 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2867 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2868 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002869 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002870 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002871 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002872 }
2873 }
2874
2875 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2876 __FUNCTION__, listener.get());
2877
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002878 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002879}
2880
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002881Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002882
2883 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002884 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2885
2886 if (parameters == NULL) {
2887 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002888 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002889 }
2890
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002891 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002892
2893 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002894 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002895 // Error logged by caller
2896 return ret;
2897 }
2898
2899 String8 shimParamsString8 = shimParams.flatten();
2900 String16 shimParamsString16 = String16(shimParamsString8);
2901
2902 *parameters = shimParamsString16;
2903
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002904 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002905}
2906
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002907Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2908 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002909 ATRACE_CALL();
2910
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002911 const String8 id = String8(cameraId);
2912
2913 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002914
2915 switch (apiVersion) {
2916 case API_VERSION_1:
2917 case API_VERSION_2:
2918 break;
2919 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002920 String8 msg = String8::format("Unknown API version %d", apiVersion);
2921 ALOGE("%s: %s", __FUNCTION__, msg.string());
2922 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002923 }
2924
Austin Borger18b30a72022-10-27 12:20:29 -07002925 int portraitRotation;
2926 auto deviceVersionAndTransport = getDeviceVersion(id, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002927 if (deviceVersionAndTransport.first == -1) {
2928 String8 msg = String8::format("Unknown camera ID %s", id.string());
2929 ALOGE("%s: %s", __FUNCTION__, msg.string());
2930 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2931 }
2932 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
2933 int deviceVersion = deviceVersionAndTransport.first;
2934 switch (deviceVersion) {
2935 case CAMERA_DEVICE_API_VERSION_1_0:
2936 case CAMERA_DEVICE_API_VERSION_3_0:
2937 case CAMERA_DEVICE_API_VERSION_3_1:
2938 if (apiVersion == API_VERSION_2) {
2939 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
2940 "shim", __FUNCTION__, id.string(), deviceVersion);
2941 *isSupported = false;
2942 } else { // if (apiVersion == API_VERSION_1) {
2943 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
2944 "supported", __FUNCTION__, id.string());
2945 *isSupported = true;
2946 }
2947 break;
2948 case CAMERA_DEVICE_API_VERSION_3_2:
2949 case CAMERA_DEVICE_API_VERSION_3_3:
2950 case CAMERA_DEVICE_API_VERSION_3_4:
2951 case CAMERA_DEVICE_API_VERSION_3_5:
2952 case CAMERA_DEVICE_API_VERSION_3_6:
2953 case CAMERA_DEVICE_API_VERSION_3_7:
2954 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002955 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002956 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002957 break;
2958 default: {
2959 String8 msg = String8::format("Unknown device version %x for device %s",
2960 deviceVersion, id.string());
2961 ALOGE("%s: %s", __FUNCTION__, msg.string());
2962 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002963 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002964 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002965 } else {
2966 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002967 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002968 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002969}
2970
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002971Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2972 /*out*/ bool *isSupported) {
2973 ATRACE_CALL();
2974
2975 const String8 id = String8(cameraId);
2976
2977 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2978 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2979
2980 return Status::ok();
2981}
2982
Cliff Wud8cae102021-03-11 01:37:42 +08002983Status CameraService::injectCamera(
2984 const String16& packageName, const String16& internalCamId,
2985 const String16& externalCamId,
2986 const sp<ICameraInjectionCallback>& callback,
2987 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08002988 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08002989 ATRACE_CALL();
2990
2991 if (!checkCallingPermission(sCameraInjectExternalCameraPermission)) {
2992 const int pid = CameraThreadState::getCallingPid();
2993 const int uid = CameraThreadState::getCallingUid();
2994 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
2995 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2996 "Permission Denial: no permission to inject camera");
2997 }
2998
2999 ALOGV(
3000 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3001 "%s",
3002 __FUNCTION__, String8(packageName).string(),
3003 String8(internalCamId).string(), String8(externalCamId).string());
3004
Cliff Wud3a05312021-04-26 23:07:31 +08003005 {
3006 Mutex::Autolock lock(mInjectionParametersLock);
3007 mInjectionInternalCamId = String8(internalCamId);
3008 mInjectionExternalCamId = String8(externalCamId);
Cliff Wu646bd612021-11-23 23:21:29 +08003009 mInjectionStatusListener->addListener(callback);
3010 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003011 status_t res = NO_ERROR;
3012 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3013 // If the client already exists, we can directly connect to the camera device through the
3014 // client's injectCamera(), otherwise we need to wait until the client is established
3015 // (execute connectHelper()) before injecting the camera to the camera device.
3016 if (clientDescriptor != nullptr) {
3017 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003018 sp<BasicClient> clientSp = clientDescriptor->getValue();
3019 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3020 if(res != OK) {
3021 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3022 "No camera device with ID \"%s\" currently available",
3023 mInjectionExternalCamId.string());
3024 }
3025 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08003026 if(res != OK) {
3027 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3028 }
3029 } else {
3030 mInjectionInitPending = true;
3031 }
3032 }
Cliff Wud8cae102021-03-11 01:37:42 +08003033
Cliff Wud3a05312021-04-26 23:07:31 +08003034 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003035}
3036
Ruben Brunkcc776712015-02-17 20:18:47 -08003037void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003038 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003039 for (auto& i : mActiveClientManager.getAll()) {
3040 auto clientSp = i->getValue();
3041 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003042 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003043 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003044 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003045 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003046 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003047}
3048
Ruben Brunkcc776712015-02-17 20:18:47 -08003049bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003050 bool ret = false;
3051 {
3052 // Acquire mServiceLock and prevent other clients from connecting
3053 std::unique_ptr<AutoConditionLock> lock =
3054 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003055
Igor Murashkin634a5152013-02-20 17:15:11 -08003056
Ruben Brunkcc776712015-02-17 20:18:47 -08003057 std::vector<sp<BasicClient>> evicted;
3058 for (auto& i : mActiveClientManager.getAll()) {
3059 auto clientSp = i->getValue();
3060 if (clientSp.get() == nullptr) {
3061 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3062 mActiveClientManager.remove(i);
3063 continue;
3064 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003065 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003066 mActiveClientManager.remove(i);
3067 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003068
Ruben Brunkcc776712015-02-17 20:18:47 -08003069 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003070 clientSp->notifyError(
3071 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003072 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003073 }
3074 }
3075
Ruben Brunkcc776712015-02-17 20:18:47 -08003076 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3077 // other clients from connecting in mServiceLockWrapper if held
3078 mServiceLock.unlock();
3079
Ruben Brunk36597b22015-03-20 22:15:57 -07003080 // Do not clear caller identity, remote caller should be client proccess
3081
Ruben Brunkcc776712015-02-17 20:18:47 -08003082 for (auto& i : evicted) {
3083 if (i.get() != nullptr) {
3084 i->disconnect();
3085 ret = true;
3086 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003087 }
3088
Ruben Brunkcc776712015-02-17 20:18:47 -08003089 // Reacquire mServiceLock
3090 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003091
Ruben Brunkcc776712015-02-17 20:18:47 -08003092 } // lock is destroyed, allow further connect calls
3093
3094 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003095}
3096
Ruben Brunkcc776712015-02-17 20:18:47 -08003097std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
3098 const String8& cameraId) const {
3099 std::shared_ptr<CameraState> state;
3100 {
3101 Mutex::Autolock lock(mCameraStatesLock);
3102 auto iter = mCameraStates.find(cameraId);
3103 if (iter != mCameraStates.end()) {
3104 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003105 }
3106 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003107 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003108}
3109
Ruben Brunkcc776712015-02-17 20:18:47 -08003110sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
3111 // Remove from active clients list
3112 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3113 if (clientDescriptorPtr == nullptr) {
3114 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
3115 cameraId.string());
3116 return sp<BasicClient>{nullptr};
3117 }
3118
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003119 sp<BasicClient> client = clientDescriptorPtr->getValue();
3120 if (client.get() != nullptr) {
3121 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3122 }
3123 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003124}
3125
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003126void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003127 // Acquire mServiceLock and prevent other clients from connecting
3128 std::unique_ptr<AutoConditionLock> lock =
3129 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3130
Ruben Brunk6267b532015-04-30 17:44:07 -07003131 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003132 for (size_t i = 0; i < newUserIds.size(); i++) {
3133 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003134 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003135 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003136 return;
3137 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003138 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003139 }
3140
Ruben Brunka8ca9152015-04-07 14:23:40 -07003141
Ruben Brunk6267b532015-04-30 17:44:07 -07003142 if (newAllowedUsers == mAllowedUsers) {
3143 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3144 return;
3145 }
3146
3147 logUserSwitch(mAllowedUsers, newAllowedUsers);
3148
3149 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003150
3151 // Current user has switched, evict all current clients.
3152 std::vector<sp<BasicClient>> evicted;
3153 for (auto& i : mActiveClientManager.getAll()) {
3154 auto clientSp = i->getValue();
3155
3156 if (clientSp.get() == nullptr) {
3157 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3158 continue;
3159 }
3160
Ruben Brunk6267b532015-04-30 17:44:07 -07003161 // Don't evict clients that are still allowed.
3162 uid_t clientUid = clientSp->getClientUid();
3163 userid_t clientUserId = multiuser_get_user_id(clientUid);
3164 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3165 continue;
3166 }
3167
Ruben Brunk36597b22015-03-20 22:15:57 -07003168 evicted.push_back(clientSp);
3169
3170 String8 curTime = getFormattedCurrentTime();
3171
3172 ALOGE("Evicting conflicting client for camera ID %s due to user change",
3173 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003174
Ruben Brunk36597b22015-03-20 22:15:57 -07003175 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07003176 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003177 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
3178 " to user switch.", i->getKey().string(),
3179 String8{clientSp->getPackageName()}.string(),
3180 i->getOwnerId(), i->getPriority().getScore(),
3181 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003182
3183 }
3184
3185 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3186 // blocking other clients from connecting in mServiceLockWrapper if held.
3187 mServiceLock.unlock();
3188
3189 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07003190 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003191
3192 for (auto& i : evicted) {
3193 i->disconnect();
3194 }
3195
Jayant Chowdhary12361932018-08-27 14:46:13 -07003196 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003197
3198 // Reacquire mServiceLock
3199 mServiceLock.lock();
3200}
Ruben Brunkcc776712015-02-17 20:18:47 -08003201
Ruben Brunka8ca9152015-04-07 14:23:40 -07003202void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003203 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003204 Mutex::Autolock l(mLogLock);
Rucha Katakward9ea6452021-05-06 11:57:16 -07003205 String8 msg = String8::format("%s : %s", curTime.string(), event);
3206 // For service error events, print the msg only once.
3207 if(!msg.contains("SERVICE ERROR")) {
3208 mEventLog.add(msg);
3209 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3210 // Error event not added to the dumpsys log before
3211 mEventLog.add(msg);
3212 sServiceErrorEventSet.insert(msg);
3213 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003214}
3215
Ruben Brunka8ca9152015-04-07 14:23:40 -07003216void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003217 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003218 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07003219 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003220 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003221}
3222
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003223void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
3224 const char* clientPackage) {
3225 // Log the clients evicted
3226 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
3227 cameraId, clientPackage, clientPid));
3228}
3229
Ruben Brunka8ca9152015-04-07 14:23:40 -07003230void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003231 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003232 // Log the clients evicted
3233 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003234 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003235}
3236
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003237void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
3238 const char* clientPackage) {
3239 // Log the clients evicted
3240 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
3241 clientPackage, clientPid));
3242}
3243
Ruben Brunka8ca9152015-04-07 14:23:40 -07003244void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003245 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003246 // Log the client rejected
3247 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003248 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003249}
3250
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003251void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
3252 // Log torch event
3253 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
3254 torchState, clientPid));
3255}
3256
Ruben Brunk6267b532015-04-30 17:44:07 -07003257void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3258 const std::set<userid_t>& newUserIds) {
3259 String8 newUsers = toString(newUserIds);
3260 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003261 if (oldUsers.size() == 0) {
3262 oldUsers = "<None>";
3263 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003264 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003265 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07003266 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003267}
3268
3269void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
3270 // Log the device removal
3271 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
3272}
3273
3274void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
3275 // Log the device removal
3276 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
3277}
3278
3279void CameraService::logClientDied(int clientPid, const char* reason) {
3280 // Log the device removal
3281 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003282}
3283
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003284void CameraService::logServiceError(const char* msg, int errorCode) {
3285 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003286 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003287}
3288
Ruben Brunk36597b22015-03-20 22:15:57 -07003289status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3290 uint32_t flags) {
3291
Mathias Agopian65ab4712010-07-14 17:59:35 -07003292 // Permission checks
3293 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003294 case SHELL_COMMAND_TRANSACTION: {
3295 int in = data.readFileDescriptor();
3296 int out = data.readFileDescriptor();
3297 int err = data.readFileDescriptor();
3298 int argc = data.readInt32();
3299 Vector<String16> args;
3300 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3301 args.add(data.readString16());
3302 }
3303 sp<IBinder> unusedCallback;
3304 sp<IResultReceiver> resultReceiver;
3305 status_t status;
3306 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3307 return status;
3308 }
3309 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3310 return status;
3311 }
3312 status = shellCommand(in, out, err, args);
3313 if (resultReceiver != nullptr) {
3314 resultReceiver->send(status);
3315 }
3316 return NO_ERROR;
3317 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003318 }
3319
3320 return BnCameraService::onTransact(code, data, reply, flags);
3321}
3322
Mathias Agopian65ab4712010-07-14 17:59:35 -07003323// We share the media players for shutter and recording sound for all clients.
3324// A reference count is kept to determine when we will actually release the
3325// media players.
3326
Jaekyun Seokef498052018-03-23 13:09:44 +09003327sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3328 sp<MediaPlayer> mp = new MediaPlayer();
3329 status_t error;
3330 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003331 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003332 error = mp->prepare();
3333 }
3334 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003335 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003336 mp->disconnect();
3337 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003338 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003339 }
3340 return mp;
3341}
3342
username5755fea2018-12-27 09:48:08 +08003343void CameraService::increaseSoundRef() {
3344 Mutex::Autolock lock(mSoundLock);
3345 mSoundRef++;
3346}
3347
3348void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003349 ATRACE_CALL();
3350
username5755fea2018-12-27 09:48:08 +08003351 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3352 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3353 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3354 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3355 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3356 }
3357 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3358 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3359 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3360 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003361 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003362 }
3363 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3364 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3365 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3366 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3367 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003368 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003369}
3370
username5755fea2018-12-27 09:48:08 +08003371void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003372 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003373 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003374 if (--mSoundRef) return;
3375
3376 for (int i = 0; i < NUM_SOUNDS; i++) {
3377 if (mSoundPlayer[i] != 0) {
3378 mSoundPlayer[i]->disconnect();
3379 mSoundPlayer[i].clear();
3380 }
3381 }
3382}
3383
3384void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003385 ATRACE_CALL();
3386
Mathias Agopian65ab4712010-07-14 17:59:35 -07003387 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07003388 if (kind < 0 || kind >= NUM_SOUNDS) {
3389 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
3390 return;
3391 }
3392
Mathias Agopian65ab4712010-07-14 17:59:35 -07003393 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003394 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003395 sp<MediaPlayer> player = mSoundPlayer[kind];
3396 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08003397 player->seekTo(0);
3398 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003399 }
3400}
3401
3402// ----------------------------------------------------------------------------
3403
3404CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07003405 const sp<ICameraClient>& cameraClient,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003406 const String16& clientPackageName, bool systemNativeClient,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003407 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003408 const String8& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003409 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003410 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003411 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003412 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003413 IInterface::asBinder(cameraClient),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003414 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003415 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003416 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003417 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003418 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003419{
Jayant Chowdhary12361932018-08-27 14:46:13 -07003420 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003421 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003422
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003423 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003424
username5755fea2018-12-27 09:48:08 +08003425 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003426
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003427 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003428}
3429
Mathias Agopian65ab4712010-07-14 17:59:35 -07003430// tear down the client
3431CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003432 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08003433 mDestructionStarted = true;
3434
username5755fea2018-12-27 09:48:08 +08003435 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003436 // unconditionally disconnect. function is idempotent
3437 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003438}
3439
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003440sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
3441
Igor Murashkin634a5152013-02-20 17:15:11 -08003442CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003443 const sp<IBinder>& remoteCallback,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003444 const String16& clientPackageName, bool nativeClient,
3445 const std::optional<String16>& clientFeatureId, const String8& cameraIdStr,
3446 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003447 int servicePid, bool overrideToPortrait):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003448 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07003449 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003450 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
3451 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003452 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003453 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07003454 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07003455 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003456 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003457 mRemoteBinder(remoteCallback),
3458 mOpsActive(false),
3459 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08003460{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003461 if (sCameraService == nullptr) {
3462 sCameraService = cameraService;
3463 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08003464
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003465 // There are 2 scenarios in which a client won't have AppOps operations
3466 // (both scenarios : native clients)
3467 // 1) It's an system native client*, the package name will be empty
3468 // and it will return from this function in the previous if condition
3469 // (This is the same as the previously existing behavior).
3470 // 2) It is a system native client, but its package name has been
3471 // modified for debugging, however it still must not use AppOps since
3472 // the package name is not a real one.
3473 //
3474 // * system native client - native client with UID < AID_APP_START. It
3475 // doesn't exclude clients not on the system partition.
3476 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003477 mAppOpsManager = std::make_unique<AppOpsManager>();
3478 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07003479
3480 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08003481}
3482
3483CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003484 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08003485 mDestructionStarted = true;
3486}
3487
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003488binder::Status CameraService::BasicClient::disconnect() {
3489 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003490 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003491 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07003492 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07003493 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08003494
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003495 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003496 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07003497 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
3498 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003499
3500 sp<IBinder> remote = getRemote();
3501 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003502 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08003503 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003504
3505 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07003506 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003507 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
3508 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
3509 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003510
Igor Murashkincba2c162013-03-20 15:56:31 -07003511 // client shouldn't be able to call into us anymore
3512 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003513
3514 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08003515}
3516
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003517status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
3518 // No dumping of clients directly over Binder,
3519 // must go through CameraService::dump
3520 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003521 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003522 return OK;
3523}
3524
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07003525status_t CameraService::BasicClient::startWatchingTags(const String8&, int) {
3526 // Can't watch tags directly, must go through CameraService::startWatchingTags
3527 return OK;
3528}
3529
3530status_t CameraService::BasicClient::stopWatchingTags(int) {
3531 // Can't watch tags directly, must go through CameraService::stopWatchingTags
3532 return OK;
3533}
3534
3535status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
3536 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
3537 return OK;
3538}
3539
Ruben Brunkcc776712015-02-17 20:18:47 -08003540String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003541 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08003542}
3543
Emilian Peev8b64f282021-03-25 16:49:57 -07003544int CameraService::BasicClient::getCameraFacing() const {
3545 return mCameraFacing;
3546}
3547
3548int CameraService::BasicClient::getCameraOrientation() const {
3549 return mOrientation;
3550}
Ruben Brunkcc776712015-02-17 20:18:47 -08003551
3552int CameraService::BasicClient::getClientPid() const {
3553 return mClientPid;
3554}
3555
Ruben Brunk6267b532015-04-30 17:44:07 -07003556uid_t CameraService::BasicClient::getClientUid() const {
3557 return mClientUid;
3558}
3559
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003560bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
3561 // Defaults to API2.
3562 return level == API_2;
3563}
3564
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003565status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003566 {
3567 Mutex::Autolock l(mAudioRestrictionLock);
3568 mAudioRestriction = mode;
3569 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003570 sCameraService->updateAudioRestriction();
3571 return OK;
3572}
3573
3574int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003575 return sCameraService->updateAudioRestriction();
3576}
3577
3578int32_t CameraService::BasicClient::getAudioRestriction() const {
3579 Mutex::Autolock l(mAudioRestrictionLock);
3580 return mAudioRestriction;
3581}
3582
3583bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
3584 switch (mode) {
3585 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
3586 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
3587 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
3588 return true;
3589 default:
3590 return false;
3591 }
3592}
3593
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003594status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
3595 if (mode == AppOpsManager::MODE_ERRORED) {
3596 ALOGI("Camera %s: Access for \"%s\" has been revoked",
3597 mCameraIdStr.string(), String8(mClientPackageName).string());
3598 return PERMISSION_DENIED;
3599 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
3600 // If the calling Uid is trusted (a native service), the AppOpsManager could
3601 // return MODE_IGNORED. Do not treat such case as error.
3602 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
3603 mClientPackageName);
3604 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08003605 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayana8143e572023-01-09 08:46:49 -08003606 // We don't want to return EACCESS if the CameraPrivacy is enabled.
3607 // We prefer to successfully open the camera and perform camera muting
3608 // or blocking in connectHelper as handleAppOpMode can be called before the
3609 // connection has been fully established and at that time camera muting
3610 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003611 if (!isUidActive || !isCameraPrivacyEnabled) {
3612 ALOGI("Camera %s: Access for \"%s\" has been restricted",
3613 mCameraIdStr.string(), String8(mClientPackageName).string());
3614 // Return the same error as for device policy manager rejection
3615 return -EACCES;
3616 }
3617 }
3618 return OK;
3619}
3620
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003621status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003622 ATRACE_CALL();
3623
Igor Murashkine6800ce2013-03-04 17:25:57 -08003624 {
3625 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003626 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003627 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003628 if (mAppOpsManager != nullptr) {
3629 // Notify app ops that the camera is not available
3630 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003631 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
3632 mClientPackageName, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003633
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003634 // Just check for camera acccess here on open - delay startOp until
3635 // camera frames start streaming in startCameraStreamingOps
3636 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
3637 mClientPackageName);
3638 status_t res = handleAppOpMode(mode);
3639 if (res != OK) {
3640 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003641 }
Svetoslav28e8ef72015-05-11 19:21:31 -07003642 }
3643
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003644 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003645
3646 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003647 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003648
Emilian Peev53722fa2019-02-22 17:47:20 -08003649 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
3650
Shuzhen Wang695044d2020-03-06 09:02:23 -08003651 // Notify listeners of camera open/close status
3652 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
3653
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003654 return OK;
3655}
3656
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003657status_t CameraService::BasicClient::startCameraStreamingOps() {
3658 ATRACE_CALL();
3659
3660 if (!mOpsActive) {
3661 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3662 return INVALID_OPERATION;
3663 }
3664 if (mOpsStreaming) {
3665 ALOGV("%s: Streaming already active!", __FUNCTION__);
3666 return OK;
3667 }
3668
3669 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
3670 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3671
3672 if (mAppOpsManager != nullptr) {
3673 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
3674 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
3675 String16("start camera ") + String16(mCameraIdStr));
3676 status_t res = handleAppOpMode(mode);
3677 if (res != OK) {
3678 return res;
3679 }
3680 }
3681
3682 mOpsStreaming = true;
3683
3684 return OK;
3685}
3686
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003687status_t CameraService::BasicClient::noteAppOp() {
3688 ATRACE_CALL();
3689
3690 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
3691 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3692
3693 // noteAppOp is only used for when camera mute is not supported, in order
3694 // to trigger the sensor privacy "Unblock" dialog
3695 if (mAppOpsManager != nullptr) {
3696 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
3697 mClientPackageName, mClientFeatureId,
3698 String16("start camera ") + String16(mCameraIdStr));
3699 status_t res = handleAppOpMode(mode);
3700 if (res != OK) {
3701 return res;
3702 }
3703 }
3704
3705 return OK;
3706}
3707
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003708status_t CameraService::BasicClient::finishCameraStreamingOps() {
3709 ATRACE_CALL();
3710
3711 if (!mOpsActive) {
3712 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3713 return INVALID_OPERATION;
3714 }
3715 if (!mOpsStreaming) {
3716 ALOGV("%s: Streaming not active!", __FUNCTION__);
3717 return OK;
3718 }
3719
3720 if (mAppOpsManager != nullptr) {
3721 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
3722 mClientPackageName, mClientFeatureId);
3723 mOpsStreaming = false;
3724 }
3725
3726 return OK;
3727}
3728
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003729status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003730 ATRACE_CALL();
3731
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003732 if (mOpsStreaming) {
3733 // Make sure we've notified everyone about camera stopping
3734 finishCameraStreamingOps();
3735 }
3736
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003737 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003738 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003739 mOpsActive = false;
3740
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003741 // This function is called when a client disconnects. This should
3742 // release the camera, but actually only if it was in a proper
3743 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003744 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003745 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003746
Ruben Brunkcc776712015-02-17 20:18:47 -08003747 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003748 sCameraService->updateStatus(StatusInternal::PRESENT,
3749 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003750 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003751 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003752 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3753 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003754 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003755 mOpsCallback.clear();
3756
Emilian Peev53722fa2019-02-22 17:47:20 -08003757 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3758
Shuzhen Wang695044d2020-03-06 09:02:23 -08003759 // Notify listeners of camera open/close status
3760 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3761
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003762 return OK;
3763}
3764
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003765void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003766 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003767 if (mAppOpsManager == nullptr) {
3768 return;
3769 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003770 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003771 if (op != AppOpsManager::OP_CAMERA) {
3772 ALOGW("Unexpected app ops notification received: %d", op);
3773 return;
3774 }
3775
3776 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003777 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003778 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003779 ALOGV("checkOp returns: %d, %s ", res,
3780 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3781 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3782 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3783 "UNKNOWN");
3784
Shuzhen Wang64900852021-02-05 09:03:29 -08003785 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003786 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003787 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003788 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003789 } else if (res == AppOpsManager::MODE_IGNORED) {
3790 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08003791 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08003792 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Shuzhen Wang64900852021-02-05 09:03:29 -08003793 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3794 mCameraIdStr.string(), String8(mClientPackageName).string(),
3795 mUidIsTrusted, isUidActive);
3796 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3797 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3798 // error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003799 if (!mUidIsTrusted) {
3800 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
3801 setCameraMute(true);
3802 } else if (!isUidActive
3803 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
3804 block();
3805 }
Shuzhen Wang64900852021-02-05 09:03:29 -08003806 }
Evan Severson09ab4002021-02-10 14:15:19 -08003807 } else if (res == AppOpsManager::MODE_ALLOWED) {
3808 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003809 }
3810}
3811
Svet Ganova453d0d2018-01-11 15:37:58 -08003812void CameraService::BasicClient::block() {
3813 ATRACE_CALL();
3814
3815 // Reset the client PID to allow server-initiated disconnect,
3816 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003817 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003818 CaptureResultExtras resultExtras; // a dummy result (invalid)
3819 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3820 disconnect();
3821}
3822
Mathias Agopian65ab4712010-07-14 17:59:35 -07003823// ----------------------------------------------------------------------------
3824
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003825void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08003826 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003827 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003828 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3829 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3830 api1ErrorCode = CAMERA_ERROR_DISABLED;
3831 }
3832 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003833 } else {
3834 ALOGE("mRemoteCallback is NULL!!");
3835 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003836}
3837
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003838// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003839binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003840 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003841 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003842}
3843
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003844bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3845 return level == API_1;
3846}
3847
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003848CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3849 mClient(client) {
3850}
3851
3852void CameraService::Client::OpsCallback::opChanged(int32_t op,
3853 const String16& packageName) {
3854 sp<BasicClient> client = mClient.promote();
3855 if (client != NULL) {
3856 client->opChanged(op, packageName);
3857 }
3858}
3859
Mathias Agopian65ab4712010-07-14 17:59:35 -07003860// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003861// UidPolicy
3862// ----------------------------------------------------------------------------
3863
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08003864void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003865 Mutex::Autolock _l(mUidLock);
3866
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003867 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003868 status_t res = mAm.linkToDeath(this);
3869 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003870 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00003871 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
3872 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08003873 ActivityManager::PROCESS_STATE_UNKNOWN,
3874 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003875 if (res == OK) {
3876 mRegistered = true;
3877 ALOGV("UidPolicy: Registered with ActivityManager");
3878 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003879}
3880
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08003881void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
3882 if (name != String16(kActivityServiceName)) {
3883 return;
3884 }
3885
3886 registerWithActivityManager();
3887}
3888
3889void CameraService::UidPolicy::registerSelf() {
3890 // Use check service to see if the activity service is available
3891 // If not available then register for notifications, instead of blocking
3892 // till the service is ready
3893 sp<IServiceManager> sm = defaultServiceManager();
3894 sp<IBinder> binder = sm->checkService(String16(kActivityServiceName));
3895 if (!binder) {
3896 sm->registerForNotifications(String16(kActivityServiceName), this);
3897 } else {
3898 registerWithActivityManager();
3899 }
3900}
3901
Svet Ganova453d0d2018-01-11 15:37:58 -08003902void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003903 Mutex::Autolock _l(mUidLock);
3904
Steven Moreland2f348142019-07-02 15:59:07 -07003905 mAm.unregisterUidObserver(this);
3906 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003907 mRegistered = false;
3908 mActiveUids.clear();
3909 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003910}
3911
3912void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3913 onUidIdle(uid, disabled);
3914}
3915
3916void CameraService::UidPolicy::onUidActive(uid_t uid) {
3917 Mutex::Autolock _l(mUidLock);
3918 mActiveUids.insert(uid);
3919}
3920
3921void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3922 bool deleted = false;
3923 {
3924 Mutex::Autolock _l(mUidLock);
3925 if (mActiveUids.erase(uid) > 0) {
3926 deleted = true;
3927 }
3928 }
3929 if (deleted) {
3930 sp<CameraService> service = mService.promote();
3931 if (service != nullptr) {
3932 service->blockClientsForUid(uid);
3933 }
3934 }
3935}
3936
Emilian Peev53722fa2019-02-22 17:47:20 -08003937void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003938 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00003939 bool procStateChange = false;
3940 {
3941 Mutex::Autolock _l(mUidLock);
3942 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
3943 mMonitoredUids[uid].procState != procState) {
3944 mMonitoredUids[uid].procState = procState;
3945 procStateChange = true;
3946 }
3947 }
3948
3949 if (procStateChange) {
3950 sp<CameraService> service = mService.promote();
3951 if (service != nullptr) {
3952 service->notifyMonitoredUids();
3953 }
Emilian Peev53722fa2019-02-22 17:47:20 -08003954 }
3955}
3956
Austin Borger65577682022-02-17 00:25:43 +00003957void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid) {
3958 bool procAdjChange = false;
3959 {
3960 Mutex::Autolock _l(mUidLock);
3961 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3962 procAdjChange = true;
3963 }
3964 }
3965
3966 if (procAdjChange) {
3967 sp<CameraService> service = mService.promote();
3968 if (service != nullptr) {
3969 service->notifyMonitoredUids();
3970 }
3971 }
3972}
3973
Emilian Peev53722fa2019-02-22 17:47:20 -08003974void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3975 Mutex::Autolock _l(mUidLock);
3976 auto it = mMonitoredUids.find(uid);
3977 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00003978 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08003979 } else {
Austin Borger65577682022-02-17 00:25:43 +00003980 MonitoredUid monitoredUid;
3981 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
3982 monitoredUid.refCount = 1;
3983 mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid));
Emilian Peev53722fa2019-02-22 17:47:20 -08003984 }
3985}
3986
3987void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3988 Mutex::Autolock _l(mUidLock);
3989 auto it = mMonitoredUids.find(uid);
3990 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00003991 it->second.refCount--;
3992 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003993 mMonitoredUids.erase(it);
3994 }
3995 } else {
3996 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3997 }
3998}
3999
Svet Ganov7b4ab782018-03-25 12:48:10 -07004000bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004001 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004002 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004003}
4004
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004005static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4006static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004007
Svet Ganov7b4ab782018-03-25 12:48:10 -07004008bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004009 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004010 // If activity manager is unreachable, assume everything is active
4011 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004012 return true;
4013 }
4014 auto it = mOverrideUids.find(uid);
4015 if (it != mOverrideUids.end()) {
4016 return it->second;
4017 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004018 bool active = mActiveUids.find(uid) != mActiveUids.end();
4019 if (!active) {
4020 // We want active UIDs to always access camera with their first attempt since
4021 // there is no guarantee the app is robustly written and would retry getting
4022 // the camera on failure. The inverse case is not a problem as we would take
4023 // camera away soon once we get the callback that the uid is no longer active.
4024 ActivityManager am;
4025 // Okay to access with a lock held as UID changes are dispatched without
4026 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004027 int64_t startTimeMillis = 0;
4028 do {
4029 // TODO: Fix this b/109950150!
4030 // Okay this is a hack. There is a race between the UID turning active and
4031 // activity being resumed. The proper fix is very risky, so we temporary add
4032 // some polling which should happen pretty rarely anyway as the race is hard
4033 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004034 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00004035 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07004036 if (active) {
4037 break;
4038 }
4039 if (startTimeMillis <= 0) {
4040 startTimeMillis = uptimeMillis();
4041 }
4042 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004043 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004044 if (remainingTimeMillis <= 0) {
4045 break;
4046 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004047 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4048
4049 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004050 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004051 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004052 } while (true);
4053
Svet Ganov7b4ab782018-03-25 12:48:10 -07004054 if (active) {
4055 // Now that we found out the UID is actually active, cache that
4056 mActiveUids.insert(uid);
4057 }
4058 }
4059 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004060}
4061
Varun Shahb42f1eb2019-04-16 14:45:13 -07004062int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4063 Mutex::Autolock _l(mUidLock);
4064 return getProcStateLocked(uid);
4065}
4066
4067int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4068 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4069 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004070 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004071 }
4072 return procState;
4073}
4074
Svet Ganov7b4ab782018-03-25 12:48:10 -07004075void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
4076 String16 callingPackage, bool active) {
4077 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004078}
4079
Svet Ganov7b4ab782018-03-25 12:48:10 -07004080void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
4081 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004082}
4083
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004084void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4085 Mutex::Autolock _l(mUidLock);
4086 ALOGV("UidPolicy: ActivityManager has died");
4087 mRegistered = false;
4088 mActiveUids.clear();
4089}
4090
Svet Ganov7b4ab782018-03-25 12:48:10 -07004091void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
4092 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004093 bool wasActive = false;
4094 bool isActive = false;
4095 {
4096 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004097 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004098 mOverrideUids.erase(uid);
4099 if (insert) {
4100 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4101 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004102 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004103 }
4104 if (wasActive != isActive && !isActive) {
4105 sp<CameraService> service = mService.promote();
4106 if (service != nullptr) {
4107 service->blockClientsForUid(uid);
4108 }
4109 }
4110}
4111
4112// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004113// SensorPrivacyPolicy
4114// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004115
4116void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4117{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004118 Mutex::Autolock _l(mSensorPrivacyLock);
4119 if (mRegistered) {
4120 return;
4121 }
Evan Severson09ab4002021-02-10 14:15:19 -08004122 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004123 mSpm.addSensorPrivacyListener(this);
4124 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
4125 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004126 if (res == OK) {
4127 mRegistered = true;
4128 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4129 }
4130}
4131
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004132void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4133 const sp<IBinder>&) {
4134 if (name != String16(kSensorPrivacyServiceName)) {
4135 return;
4136 }
4137
4138 registerWithSensorPrivacyManager();
4139}
4140
4141void CameraService::SensorPrivacyPolicy::registerSelf() {
4142 // Use checkservice to see if the sensor_privacy service is available
4143 // If service is not available then register for notification
4144 sp<IServiceManager> sm = defaultServiceManager();
4145 sp<IBinder> binder = sm->checkService(String16(kSensorPrivacyServiceName));
4146 if (!binder) {
4147 sm->registerForNotifications(String16(kSensorPrivacyServiceName),this);
4148 } else {
4149 registerWithSensorPrivacyManager();
4150 }
4151}
4152
Michael Grooverd1d435a2018-12-18 17:39:42 -08004153void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4154 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004155 mSpm.removeSensorPrivacyListener(this);
4156 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004157 mRegistered = false;
4158 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4159}
4160
4161bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004162 if (!mRegistered) {
4163 registerWithSensorPrivacyManager();
4164 }
4165
Michael Grooverd1d435a2018-12-18 17:39:42 -08004166 Mutex::Autolock _l(mSensorPrivacyLock);
4167 return mSensorPrivacyEnabled;
4168}
4169
Evan Seversond0b69922022-01-27 10:47:34 -08004170bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004171 if (!hasCameraPrivacyFeature()) {
4172 return false;
4173 }
Evan Seversond0b69922022-01-27 10:47:34 -08004174 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004175}
4176
Evan Seversond0b69922022-01-27 10:47:34 -08004177binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
4178 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08004179 {
4180 Mutex::Autolock _l(mSensorPrivacyLock);
Kwangkyu Parke3af2992022-11-05 02:46:52 +09004181 mSensorPrivacyEnabled = enabled;
Michael Grooverd1d435a2018-12-18 17:39:42 -08004182 }
4183 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08004184 if (enabled) {
4185 sp<CameraService> service = mService.promote();
4186 if (service != nullptr) {
4187 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004188 }
4189 }
4190 return binder::Status::ok();
4191}
4192
4193void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4194 Mutex::Autolock _l(mSensorPrivacyLock);
4195 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
4196 mRegistered = false;
4197}
4198
Evan Severson09ab4002021-02-10 14:15:19 -08004199bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08004200 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
4201 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4202 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
4203 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4204 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08004205}
4206
Michael Grooverd1d435a2018-12-18 17:39:42 -08004207// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004208// CameraState
4209// ----------------------------------------------------------------------------
4210
4211CameraService::CameraState::CameraState(const String8& id, int cost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004212 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind,
4213 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004214 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004215 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08004216
4217CameraService::CameraState::~CameraState() {}
4218
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004219CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004220 Mutex::Autolock lock(mStatusLock);
4221 return mStatus;
4222}
4223
Shuzhen Wang43858162020-01-10 13:42:15 -08004224std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
4225 Mutex::Autolock lock(mStatusLock);
4226 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
4227 return res;
4228}
4229
Ruben Brunkcc776712015-02-17 20:18:47 -08004230CameraParameters CameraService::CameraState::getShimParams() const {
4231 return mShimParams;
4232}
4233
4234void CameraService::CameraState::setShimParams(const CameraParameters& params) {
4235 mShimParams = params;
4236}
4237
4238int CameraService::CameraState::getCost() const {
4239 return mCost;
4240}
4241
4242std::set<String8> CameraService::CameraState::getConflicting() const {
4243 return mConflicting;
4244}
4245
4246String8 CameraService::CameraState::getId() const {
4247 return mId;
4248}
4249
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004250SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
4251 return mSystemCameraKind;
4252}
4253
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004254bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
4255 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
4256 != mPhysicalCameras.end();
4257}
4258
Shuzhen Wang43858162020-01-10 13:42:15 -08004259bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
4260 Mutex::Autolock lock(mStatusLock);
4261 auto result = mUnavailablePhysicalIds.insert(physicalId);
4262 return result.second;
4263}
4264
4265bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
4266 Mutex::Autolock lock(mStatusLock);
4267 auto count = mUnavailablePhysicalIds.erase(physicalId);
4268 return count > 0;
4269}
4270
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004271void CameraService::CameraState::setClientPackage(const String8& clientPackage) {
4272 Mutex::Autolock lock(mStatusLock);
4273 mClientPackage = clientPackage;
4274}
4275
4276String8 CameraService::CameraState::getClientPackage() const {
4277 Mutex::Autolock lock(mStatusLock);
4278 return mClientPackage;
4279}
4280
Ruben Brunkcc776712015-02-17 20:18:47 -08004281// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07004282// ClientEventListener
4283// ----------------------------------------------------------------------------
4284
4285void CameraService::ClientEventListener::onClientAdded(
4286 const resource_policy::ClientDescriptor<String8,
4287 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004288 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004289 if (basicClient.get() != nullptr) {
4290 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4291 notifier.noteStartCamera(descriptor.getKey(),
4292 static_cast<int>(basicClient->getClientUid()));
4293 }
4294}
4295
4296void CameraService::ClientEventListener::onClientRemoved(
4297 const resource_policy::ClientDescriptor<String8,
4298 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004299 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004300 if (basicClient.get() != nullptr) {
4301 BatteryNotifier& notifier(BatteryNotifier::getInstance());
4302 notifier.noteStopCamera(descriptor.getKey(),
4303 static_cast<int>(basicClient->getClientUid()));
4304 }
4305}
4306
4307
4308// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004309// CameraClientManager
4310// ----------------------------------------------------------------------------
4311
Ruben Brunk99e69712015-05-26 17:25:07 -07004312CameraService::CameraClientManager::CameraClientManager() {
4313 setListener(std::make_shared<ClientEventListener>());
4314}
4315
Ruben Brunkcc776712015-02-17 20:18:47 -08004316CameraService::CameraClientManager::~CameraClientManager() {}
4317
4318sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
4319 const String8& id) const {
4320 auto descriptor = get(id);
4321 if (descriptor == nullptr) {
4322 return sp<BasicClient>{nullptr};
4323 }
4324 return descriptor->getValue();
4325}
4326
4327String8 CameraService::CameraClientManager::toString() const {
4328 auto all = getAll();
4329 String8 ret("[");
4330 bool hasAny = false;
4331 for (auto& i : all) {
4332 hasAny = true;
4333 String8 key = i->getKey();
4334 int32_t cost = i->getCost();
4335 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00004336 int32_t score = i->getPriority().getScore();
4337 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08004338 auto conflicting = i->getConflicting();
4339 auto clientSp = i->getValue();
4340 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07004341 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08004342 if (clientSp.get() != nullptr) {
4343 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07004344 uid_t clientUid = clientSp->getClientUid();
4345 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004346 }
Emilian Peev8131a262017-02-01 12:33:43 +00004347 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
4348 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08004349
Ruben Brunk6267b532015-04-30 17:44:07 -07004350 if (clientSp.get() != nullptr) {
4351 ret.appendFormat("User Id: %d, ", clientUserId);
4352 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004353 if (packageName.size() != 0) {
4354 ret.appendFormat("Client Package Name: %s", packageName.string());
4355 }
4356
4357 ret.append(", Conflicting Client Devices: {");
4358 for (auto& j : conflicting) {
4359 ret.appendFormat("%s, ", j.string());
4360 }
4361 ret.append("})");
4362 }
4363 if (hasAny) ret.append("\n");
4364 ret.append("]\n");
4365 return ret;
4366}
4367
4368CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
4369 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00004370 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004371 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004372
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004373 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
4374 int32_t state_adj = systemNativeClient ? kSystemNativeClientState: state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07004375
Ruben Brunkcc776712015-02-17 20:18:47 -08004376 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004377 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
4378 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08004379}
4380
4381CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004382 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004383 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004384 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00004385 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004386 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
4387 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08004388}
4389
4390// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08004391// InjectionStatusListener
4392// ----------------------------------------------------------------------------
4393
4394void CameraService::InjectionStatusListener::addListener(
4395 const sp<ICameraInjectionCallback>& callback) {
4396 Mutex::Autolock lock(mListenerLock);
4397 if (mCameraInjectionCallback) return;
4398 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
4399 if (res == OK) {
4400 mCameraInjectionCallback = callback;
4401 }
4402}
4403
4404void CameraService::InjectionStatusListener::removeListener() {
4405 Mutex::Autolock lock(mListenerLock);
4406 if (mCameraInjectionCallback == nullptr) {
4407 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4408 return;
4409 }
4410 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
4411 mCameraInjectionCallback = nullptr;
4412}
4413
4414void CameraService::InjectionStatusListener::notifyInjectionError(
Cliff Wud3a05312021-04-26 23:07:31 +08004415 String8 injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08004416 if (mCameraInjectionCallback == nullptr) {
4417 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4418 return;
4419 }
Cliff Wud3a05312021-04-26 23:07:31 +08004420
4421 switch (err) {
4422 case -ENODEV:
4423 mCameraInjectionCallback->onInjectionError(
4424 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4425 ALOGE("No camera device with ID \"%s\" currently available!",
4426 injectedCamId.string());
4427 break;
4428 case -EBUSY:
4429 mCameraInjectionCallback->onInjectionError(
4430 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4431 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
4432 injectedCamId.string());
4433 break;
4434 case DEAD_OBJECT:
4435 mCameraInjectionCallback->onInjectionError(
4436 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4437 ALOGE("Camera ID \"%s\" object is dead!",
4438 injectedCamId.string());
4439 break;
4440 case INVALID_OPERATION:
4441 mCameraInjectionCallback->onInjectionError(
4442 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4443 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
4444 injectedCamId.string());
4445 break;
4446 case UNKNOWN_TRANSACTION:
4447 mCameraInjectionCallback->onInjectionError(
4448 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
4449 ALOGE("Camera ID \"%s\" method doesn't support!",
4450 injectedCamId.string());
4451 break;
4452 default:
4453 mCameraInjectionCallback->onInjectionError(
4454 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
4455 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
4456 strerror(-err), err, injectedCamId.string());
4457 }
Cliff Wud8cae102021-03-11 01:37:42 +08004458}
4459
4460void CameraService::InjectionStatusListener::binderDied(
4461 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08004462 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
4463 auto parent = mParent.promote();
4464 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08004465 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4466 if (clientDescriptor != nullptr) {
4467 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4468 baseClientPtr->stopInjection();
4469 }
Cliff Wu3b268182021-07-06 15:44:43 +08004470 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004471 }
4472}
4473
4474// ----------------------------------------------------------------------------
4475// CameraInjectionSession
4476// ----------------------------------------------------------------------------
4477
4478binder::Status CameraService::CameraInjectionSession::stopInjection() {
4479 Mutex::Autolock lock(mInjectionSessionLock);
4480 auto parent = mParent.promote();
4481 if (parent == nullptr) {
4482 ALOGE("CameraInjectionSession: Parent is gone");
4483 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
4484 "Camera service encountered error");
4485 }
Cliff Wud3a05312021-04-26 23:07:31 +08004486
4487 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08004488 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4489 if (clientDescriptor != nullptr) {
4490 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4491 res = baseClientPtr->stopInjection();
4492 if (res != OK) {
4493 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
4494 " ret != NO_ERROR: %d", res);
4495 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
4496 "Camera session encountered error");
4497 }
4498 }
Cliff Wu3b268182021-07-06 15:44:43 +08004499 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004500 return binder::Status::ok();
4501}
4502
4503// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07004504
4505static const int kDumpLockRetries = 50;
4506static const int kDumpLockSleep = 60000;
4507
4508static bool tryLock(Mutex& mutex)
4509{
4510 bool locked = false;
4511 for (int i = 0; i < kDumpLockRetries; ++i) {
4512 if (mutex.tryLock() == NO_ERROR) {
4513 locked = true;
4514 break;
4515 }
4516 usleep(kDumpLockSleep);
4517 }
4518 return locked;
4519}
4520
Rucha Katakwardf223072021-06-15 10:21:00 -07004521void CameraService::cacheDump() {
4522 if (mMemFd != -1) {
4523 const Vector<String16> args;
4524 ATRACE_CALL();
4525 // Acquiring service lock here will avoid the deadlock since
4526 // cacheDump will not be called during the second disconnect.
4527 Mutex::Autolock lock(mServiceLock);
4528
4529 Mutex::Autolock l(mCameraStatesLock);
4530 // Start collecting the info for open sessions and store it in temp file.
4531 for (const auto& state : mCameraStates) {
4532 String8 cameraId = state.first;
4533 auto clientDescriptor = mActiveClientManager.get(cameraId);
4534 if (clientDescriptor != nullptr) {
4535 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.string());
4536 // Log the current open session info before device is disconnected.
4537 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
4538 }
4539 }
4540 }
4541}
4542
Mathias Agopian65ab4712010-07-14 17:59:35 -07004543status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004544 ATRACE_CALL();
4545
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004546 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004547 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004548 CameraThreadState::getCallingPid(),
4549 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004550 return NO_ERROR;
4551 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004552 bool locked = tryLock(mServiceLock);
4553 // failed to lock - CameraService is probably deadlocked
4554 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004555 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004556 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004557
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004558 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004559 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07004560
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004561 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004562 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08004563
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004564 if (locked) mServiceLock.unlock();
4565 return NO_ERROR;
4566 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004567 dprintf(fd, "\n== Service global info: ==\n\n");
4568 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004569 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07004570 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
4571 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004572 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
4573 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
4574 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004575 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004576 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
4577 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Shuzhen Wang16610a62022-12-15 22:38:07 -08004578 if (mStreamUseCaseOverrides.size() > 0) {
4579 dprintf(fd, "Active stream use case overrides:");
4580 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
4581 dprintf(fd, " %" PRId64, useCaseOverride);
4582 }
4583 dprintf(fd, "\n");
4584 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004585
4586 dumpEventLog(fd);
4587
4588 bool stateLocked = tryLock(mCameraStatesLock);
4589 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004590 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004591 }
4592
Emilian Peevbd8c5032018-02-14 23:05:40 +00004593 int argSize = args.size();
4594 for (int i = 0; i < argSize; i++) {
4595 if (args[i] == TagMonitor::kMonitorOption) {
4596 if (i + 1 < argSize) {
4597 mMonitorTags = String8(args[i + 1]);
4598 }
4599 break;
4600 }
4601 }
4602
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004603 for (auto& state : mCameraStates) {
4604 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004605
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004606 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004607
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004608 CameraParameters p = state.second->getShimParams();
4609 if (!p.isEmpty()) {
4610 dprintf(fd, " Camera1 API shim is using parameters:\n ");
4611 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004612 }
4613
4614 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004615 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004616 // log the current open session info
4617 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004618 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07004619 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004620 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004621
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004622 }
4623
4624 if (stateLocked) mCameraStatesLock.unlock();
4625
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004626 if (locked) mServiceLock.unlock();
4627
Emilian Peevf53f66e2017-04-11 14:29:43 +01004628 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004629
4630 dprintf(fd, "\n== Vendor tags: ==\n\n");
4631
4632 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
4633 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00004634 sp<VendorTagDescriptorCache> cache =
4635 VendorTagDescriptorCache::getGlobalVendorTagCache();
4636 if (cache == NULL) {
4637 dprintf(fd, "No vendor tags.\n");
4638 } else {
4639 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
4640 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004641 } else {
4642 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
4643 }
4644
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004645 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004646 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004647 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004648
4649 // Process dump arguments, if any
4650 int n = args.size();
4651 String16 verboseOption("-v");
4652 String16 unreachableOption("--unreachable");
4653 for (int i = 0; i < n; i++) {
4654 if (args[i] == verboseOption) {
4655 // change logging level
4656 if (i + 1 >= n) continue;
4657 String8 levelStr(args[i+1]);
4658 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004659 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004660 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004661 } else if (args[i] == unreachableOption) {
4662 // Dump memory analysis
4663 // TODO - should limit be an argument parameter?
4664 UnreachableMemoryInfo info;
4665 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
4666 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004667 dprintf(fd, "\n== Unable to dump unreachable memory. "
4668 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004669 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004670 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004671 std::string s = info.ToString(/*log_contents*/ true);
4672 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004673 }
4674 }
4675 }
Rucha Katakwardf223072021-06-15 10:21:00 -07004676
4677 bool serviceLocked = tryLock(mServiceLock);
4678
4679 // Dump info from previous open sessions.
4680 // Reposition the offset to beginning of the file before reading
4681
4682 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
4683 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
4684 ssize_t size_read;
4685 char buf[4096];
4686 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
4687 // Read data from file to a small buffer and write it to fd.
4688 write(fd, buf, size_read);
4689 if (size_read == -1) {
4690 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4691 break;
4692 }
4693 }
4694 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
4695 } else {
4696 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4697 }
4698
4699 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004700 return NO_ERROR;
4701}
4702
Rucha Katakwardf223072021-06-15 10:21:00 -07004703void CameraService::dumpOpenSessionClientLogs(int fd,
4704 const Vector<String16>& args, const String8& cameraId) {
4705 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07004706 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
4707 getFormattedCurrentTime().string(),
4708 cameraId.string());
Rucha Katakwardf223072021-06-15 10:21:00 -07004709 dprintf(fd, " Client priority score: %d state: %d\n",
4710 clientDescriptor->getPriority().getScore(),
4711 clientDescriptor->getPriority().getState());
4712 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
4713
4714 auto client = clientDescriptor->getValue();
4715 dprintf(fd, " Client package: %s\n",
4716 String8(client->getPackageName()).string());
4717
4718 client->dumpClient(fd, args);
4719}
4720
4721void CameraService::dumpClosedSessionClientLogs(int fd, const String8& cameraId) {
4722 dprintf(fd, " Device %s is closed, no client instance\n",
4723 cameraId.string());
4724}
4725
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004726void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004727 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004728
4729 Mutex::Autolock l(mLogLock);
4730 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004731 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004732 }
4733
4734 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004735 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004736 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004737 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004738 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004739 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004740}
4741
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004742void CameraService::cacheClientTagDumpIfNeeded(const char *cameraId, BasicClient* client) {
4743 Mutex::Autolock lock(mLogLock);
4744 if (!isClientWatchedLocked(client)) { return; }
4745
4746 std::vector<std::string> dumpVector;
4747 client->dumpWatchedEventsToVector(dumpVector);
4748
4749 if (dumpVector.empty()) { return; }
4750
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004751 std::string dumpString;
4752
4753 String8 currentTime = getFormattedCurrentTime();
4754 dumpString += "Cached @ ";
4755 dumpString += currentTime.string();
4756 dumpString += "\n"; // First line is the timestamp of when client is cached.
4757
4758
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004759 const String16 &packageName = client->getPackageName();
4760
4761 String8 packageName8 = String8(packageName);
4762 const char *printablePackageName = packageName8.lockBuffer(packageName.size());
4763
Avichal Rakesh882c08b2021-12-09 17:47:07 -08004764
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004765 size_t i = dumpVector.size();
4766
4767 // Store the string in reverse order (latest last)
4768 while (i > 0) {
4769 i--;
4770 dumpString += cameraId;
4771 dumpString += ":";
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004772 dumpString += printablePackageName;
4773 dumpString += " ";
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004774 dumpString += dumpVector[i]; // implicitly ends with '\n'
4775 }
4776
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004777 packageName8.unlockBuffer();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004778 mWatchedClientsDumpCache[packageName] = dumpString;
4779}
4780
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004781void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004782 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004783 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
4784 if (mTorchClientMap[i] == who) {
4785 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004786 String8 cameraId = mTorchClientMap.keyAt(i);
4787 status_t res = mFlashlight->setTorchMode(cameraId, false);
4788 if (res) {
4789 ALOGE("%s: torch client died but couldn't turn off torch: "
4790 "%s (%d)", __FUNCTION__, strerror(-res), res);
4791 return;
4792 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004793 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004794 break;
4795 }
4796 }
4797}
4798
Ruben Brunkcc776712015-02-17 20:18:47 -08004799/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07004800
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004801 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07004802 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
4803 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004804 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08004805 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004806 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004807
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004808 // check torch client
4809 handleTorchClientBinderDied(who);
4810
4811 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08004812 if(!evictClientIdByRemote(who)) {
4813 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004814 return;
4815 }
4816
Ruben Brunkcc776712015-02-17 20:18:47 -08004817 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
4818 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004819}
4820
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004821void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004822 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08004823}
4824
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004825void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
4826 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004827 // Do not lock mServiceLock here or can get into a deadlock from
4828 // connect() -> disconnect -> updateStatus
4829
4830 auto state = getCameraState(cameraId);
4831
4832 if (state == nullptr) {
4833 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4834 cameraId.string());
4835 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07004836 }
4837
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004838 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
4839 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
4840 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
4841 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
4842 return;
4843 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004844
4845 // Collect the logical cameras without holding mStatusLock in updateStatus
4846 // as that can lead to a deadlock(b/162192331).
4847 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08004848 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08004849 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07004850 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004851 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004852 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004853
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004854 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004855 // Update torch status if it has a flash unit.
4856 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004857 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004858 if (getTorchStatusLocked(cameraId, &torchStatus) !=
4859 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004860 TorchModeStatus newTorchStatus =
4861 status == StatusInternal::PRESENT ?
4862 TorchModeStatus::AVAILABLE_OFF :
4863 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004864 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07004865 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004866 }
4867 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004868 }
4869
4870 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004871 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
4872 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08004873
Ruben Brunkcc776712015-02-17 20:18:47 -08004874 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07004875 bool isVendorListener = listener->isVendorListener();
4876 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
4877 listener->getListenerPid(), listener->getListenerUid()) ||
Shuzhen Wangb8259792021-05-27 09:27:06 -07004878 isVendorListener) {
4879 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004880 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08004881 continue;
4882 }
Austin Borgere8e2c422022-05-12 13:45:24 -07004883 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08004884 String16(cameraId));
Austin Borgere8e2c422022-05-12 13:45:24 -07004885 listener->handleBinderStatus(ret,
4886 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
4887 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
4888 ret.exceptionCode());
Ruben Brunkcc776712015-02-17 20:18:47 -08004889 }
4890 });
Igor Murashkincba2c162013-03-20 15:56:31 -07004891}
4892
Shuzhen Wang695044d2020-03-06 09:02:23 -08004893void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
4894 const String16& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004895 auto state = getCameraState(cameraId);
4896 if (state == nullptr) {
4897 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4898 cameraId.string());
4899 return;
4900 }
4901 if (open) {
4902 state->setClientPackage(String8(clientPackageName));
4903 } else {
4904 state->setClientPackage(String8::empty());
4905 }
4906
Shuzhen Wang695044d2020-03-06 09:02:23 -08004907 Mutex::Autolock lock(mStatusListenerLock);
4908
4909 for (const auto& it : mListenerList) {
4910 if (!it->isOpenCloseCallbackAllowed()) {
4911 continue;
4912 }
4913
4914 binder::Status ret;
4915 String16 cameraId64(cameraId);
4916 if (open) {
4917 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
4918 } else {
4919 ret = it->getListener()->onCameraClosed(cameraId64);
4920 }
Austin Borgere8e2c422022-05-12 13:45:24 -07004921
4922 it->handleBinderStatus(ret,
4923 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
4924 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08004925 }
4926}
4927
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004928template<class Func>
4929void CameraService::CameraState::updateStatus(StatusInternal status,
4930 const String8& cameraId,
4931 std::initializer_list<StatusInternal> rejectSourceStates,
4932 Func onStatusUpdatedLocked) {
4933 Mutex::Autolock lock(mStatusLock);
4934 StatusInternal oldStatus = mStatus;
4935 mStatus = status;
4936
4937 if (oldStatus == status) {
4938 return;
4939 }
4940
4941 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
4942 cameraId.string(), oldStatus, status);
4943
4944 if (oldStatus == StatusInternal::NOT_PRESENT &&
4945 (status != StatusInternal::PRESENT &&
4946 status != StatusInternal::ENUMERATING)) {
4947
4948 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
4949 __FUNCTION__);
4950 mStatus = oldStatus;
4951 return;
4952 }
4953
4954 /**
4955 * Sometimes we want to conditionally do a transition.
4956 * For example if a client disconnects, we want to go to PRESENT
4957 * only if we weren't already in NOT_PRESENT or ENUMERATING.
4958 */
4959 for (auto& rejectStatus : rejectSourceStates) {
4960 if (oldStatus == rejectStatus) {
4961 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
4962 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
4963 mStatus = oldStatus;
4964 return;
4965 }
4966 }
4967
4968 onStatusUpdatedLocked(cameraId, status);
4969}
4970
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004971status_t CameraService::getTorchStatusLocked(
4972 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004973 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004974 if (!status) {
4975 return BAD_VALUE;
4976 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004977 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4978 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004979 // invalid camera ID or the camera doesn't have a flash unit
4980 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004981 }
4982
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004983 *status = mTorchStatusMap.valueAt(index);
4984 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004985}
4986
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004987status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004988 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004989 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4990 if (index == NAME_NOT_FOUND) {
4991 return BAD_VALUE;
4992 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004993 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004994
4995 return OK;
4996}
4997
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004998std::list<String16> CameraService::getLogicalCameras(
4999 const String8& physicalCameraId) {
5000 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005001 Mutex::Autolock lock(mCameraStatesLock);
5002 for (const auto& state : mCameraStates) {
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005003 if (state.second->containsPhysicalCamera(physicalCameraId.c_str())) {
5004 retList.emplace_back(String16(state.first));
Shuzhen Wang43858162020-01-10 13:42:15 -08005005 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005006 }
5007 return retList;
5008}
5009
5010void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
5011 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
5012 SystemCameraKind deviceKind) {
5013 // mStatusListenerLock is expected to be locked
5014 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005015 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005016 // Note: we check only the deviceKind of the physical camera id
5017 // since, logical camera ids and their physical camera ids are
5018 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005019 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5020 listener->getListenerPid(), listener->getListenerUid())) {
5021 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005022 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005023 continue;
5024 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005025 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005026 logicalCameraId, physicalCameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005027 listener->handleBinderStatus(ret,
5028 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5029 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5030 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005031 }
5032 }
5033}
5034
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005035
Svet Ganova453d0d2018-01-11 15:37:58 -08005036void CameraService::blockClientsForUid(uid_t uid) {
5037 const auto clients = mActiveClientManager.getAll();
5038 for (auto& current : clients) {
5039 if (current != nullptr) {
5040 const auto basicClient = current->getValue();
5041 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5042 basicClient->block();
5043 }
5044 }
5045 }
5046}
5047
Michael Grooverd1d435a2018-12-18 17:39:42 -08005048void CameraService::blockAllClients() {
5049 const auto clients = mActiveClientManager.getAll();
5050 for (auto& current : clients) {
5051 if (current != nullptr) {
5052 const auto basicClient = current->getValue();
5053 if (basicClient.get() != nullptr) {
5054 basicClient->block();
5055 }
5056 }
5057 }
5058}
5059
Svet Ganova453d0d2018-01-11 15:37:58 -08005060// NOTE: This is a remote API - make sure all args are validated
5061status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
5062 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
5063 return PERMISSION_DENIED;
5064 }
5065 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5066 return BAD_VALUE;
5067 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005068 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005069 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07005070 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005071 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07005072 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005073 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005074 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
5075 return handleSetRotateAndCrop(args);
5076 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
5077 return handleGetRotateAndCrop(out);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005078 } else if (args.size() >= 2 && args[0] == String16("set-autoframing")) {
5079 return handleSetAutoframing(args);
5080 } else if (args.size() >= 1 && args[0] == String16("get-autoframing")) {
5081 return handleGetAutoframing(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005082 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
5083 return handleSetImageDumpMask(args);
5084 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
5085 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005086 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
5087 return handleSetCameraMute(args);
Shuzhen Wang16610a62022-12-15 22:38:07 -08005088 } else if (args.size() >= 2 && args[0] == String16("set-stream-use-case-override")) {
5089 return handleSetStreamUseCaseOverrides(args);
5090 } else if (args.size() >= 1 && args[0] == String16("clear-stream-use-case-override")) {
5091 handleClearStreamUseCaseOverrides();
5092 return OK;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005093 } else if (args.size() >= 2 && args[0] == String16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005094 return handleWatchCommand(args, in, out);
Ravneetaeb20dc2022-03-30 05:33:03 +00005095 } else if (args.size() >= 2 && args[0] == String16("set-watchdog")) {
5096 return handleSetCameraServiceWatchdog(args);
Svet Ganova453d0d2018-01-11 15:37:58 -08005097 } else if (args.size() == 1 && args[0] == String16("help")) {
5098 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005099 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005100 }
5101 printHelp(err);
5102 return BAD_VALUE;
5103}
5104
5105status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07005106 String16 packageName = args[1];
5107
Svet Ganova453d0d2018-01-11 15:37:58 -08005108 bool active = false;
5109 if (args[2] == String16("active")) {
5110 active = true;
5111 } else if ((args[2] != String16("idle"))) {
5112 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
5113 return BAD_VALUE;
5114 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005115
5116 int userId = 0;
5117 if (args.size() >= 5 && args[3] == String16("--user")) {
5118 userId = atoi(String8(args[4]));
5119 }
5120
5121 uid_t uid;
5122 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5123 return BAD_VALUE;
5124 }
5125
5126 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005127 return NO_ERROR;
5128}
5129
5130status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07005131 String16 packageName = args[1];
5132
5133 int userId = 0;
5134 if (args.size() >= 4 && args[2] == String16("--user")) {
5135 userId = atoi(String8(args[3]));
5136 }
5137
5138 uid_t uid;
5139 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005140 return BAD_VALUE;
5141 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005142
5143 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005144 return NO_ERROR;
5145}
5146
5147status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07005148 String16 packageName = args[1];
5149
5150 int userId = 0;
5151 if (args.size() >= 4 && args[2] == String16("--user")) {
5152 userId = atoi(String8(args[3]));
5153 }
5154
5155 uid_t uid;
5156 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005157 return BAD_VALUE;
5158 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005159
5160 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005161 return dprintf(out, "active\n");
5162 } else {
5163 return dprintf(out, "idle\n");
5164 }
5165}
5166
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005167status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
5168 int rotateValue = atoi(String8(args[1]));
5169 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
5170 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
5171 Mutex::Autolock lock(mServiceLock);
5172
5173 mOverrideRotateAndCropMode = rotateValue;
5174
5175 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
5176
5177 const auto clients = mActiveClientManager.getAll();
5178 for (auto& current : clients) {
5179 if (current != nullptr) {
5180 const auto basicClient = current->getValue();
5181 if (basicClient.get() != nullptr) {
5182 basicClient->setRotateAndCropOverride(rotateValue);
5183 }
5184 }
5185 }
5186
5187 return OK;
5188}
5189
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005190status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
5191 char* end;
5192 int autoframingValue = (int) strtol(String8(args[1]), &end, /*base=*/10);
5193 if ((*end != '\0') ||
5194 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
5195 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
5196 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
5197 return BAD_VALUE;
5198 }
5199
5200 Mutex::Autolock lock(mServiceLock);
5201 mOverrideAutoframingMode = autoframingValue;
5202
5203 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
5204
5205 const auto clients = mActiveClientManager.getAll();
5206 for (auto& current : clients) {
5207 if (current != nullptr) {
5208 const auto basicClient = current->getValue();
5209 if (basicClient.get() != nullptr) {
5210 basicClient->setAutoframingOverride(autoframingValue);
5211 }
5212 }
5213 }
5214
5215 return OK;
5216}
5217
Ravneetaeb20dc2022-03-30 05:33:03 +00005218status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
5219 int enableWatchdog = atoi(String8(args[1]));
5220
5221 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
5222
5223 Mutex::Autolock lock(mServiceLock);
5224
5225 mCameraServiceWatchdogEnabled = enableWatchdog;
5226
5227 const auto clients = mActiveClientManager.getAll();
5228 for (auto& current : clients) {
5229 if (current != nullptr) {
5230 const auto basicClient = current->getValue();
5231 if (basicClient.get() != nullptr) {
5232 basicClient->setCameraServiceWatchdog(enableWatchdog);
5233 }
5234 }
5235 }
5236
5237 return OK;
5238}
5239
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005240status_t CameraService::handleGetRotateAndCrop(int out) {
5241 Mutex::Autolock lock(mServiceLock);
5242
5243 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
5244}
5245
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005246status_t CameraService::handleGetAutoframing(int out) {
5247 Mutex::Autolock lock(mServiceLock);
5248
5249 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
5250}
5251
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005252status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
5253 char *endPtr;
5254 errno = 0;
5255 String8 maskString8 = String8(args[1]);
5256 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
5257
5258 if (errno != 0) return BAD_VALUE;
5259 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
5260 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
5261
5262 Mutex::Autolock lock(mServiceLock);
5263
5264 mImageDumpMask = maskValue;
5265
5266 return OK;
5267}
5268
5269status_t CameraService::handleGetImageDumpMask(int out) {
5270 Mutex::Autolock lock(mServiceLock);
5271
5272 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
5273}
5274
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005275status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
5276 int muteValue = strtol(String8(args[1]), nullptr, 10);
5277 if (errno != 0) return BAD_VALUE;
5278
5279 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
5280 Mutex::Autolock lock(mServiceLock);
5281
5282 mOverrideCameraMuteMode = (muteValue == 1);
5283
5284 const auto clients = mActiveClientManager.getAll();
5285 for (auto& current : clients) {
5286 if (current != nullptr) {
5287 const auto basicClient = current->getValue();
5288 if (basicClient.get() != nullptr) {
5289 if (basicClient->supportsCameraMute()) {
5290 basicClient->setCameraMute(mOverrideCameraMuteMode);
5291 }
5292 }
5293 }
5294 }
5295
5296 return OK;
5297}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005298
Shuzhen Wang16610a62022-12-15 22:38:07 -08005299status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
5300 std::vector<int64_t> useCasesOverride;
5301 for (size_t i = 1; i < args.size(); i++) {
5302 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
5303 String8 arg8 = String8(args[i]);
5304 if (arg8 == "DEFAULT") {
5305 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
5306 } else if (arg8 == "PREVIEW") {
5307 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
5308 } else if (arg8 == "STILL_CAPTURE") {
5309 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
5310 } else if (arg8 == "VIDEO_RECORD") {
5311 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
5312 } else if (arg8 == "PREVIEW_VIDEO_STILL") {
5313 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
5314 } else if (arg8 == "VIDEO_CALL") {
5315 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
5316 } else if (arg8 == "CROPPED_RAW") {
5317 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
5318 } else {
5319 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg8.c_str());
5320 return BAD_VALUE;
5321 }
5322 useCasesOverride.push_back(useCase);
5323 }
5324
5325 Mutex::Autolock lock(mServiceLock);
5326 mStreamUseCaseOverrides = std::move(useCasesOverride);
5327
5328 return OK;
5329}
5330
5331void CameraService::handleClearStreamUseCaseOverrides() {
5332 Mutex::Autolock lock(mServiceLock);
5333 mStreamUseCaseOverrides.clear();
5334}
5335
Avichal Rakesh84147132021-11-11 17:47:11 -08005336status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005337 if (args.size() >= 3 && args[1] == String16("start")) {
5338 return startWatchingTags(args, outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005339 } else if (args.size() == 2 && args[1] == String16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005340 return stopWatchingTags(outFd);
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005341 } else if (args.size() == 2 && args[1] == String16("dump")) {
5342 return printWatchedTags(outFd);
5343 } else if (args.size() >= 2 && args[1] == String16("live")) {
5344 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005345 } else if (args.size() == 2 && args[1] == String16("clear")) {
5346 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005347 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005348 dprintf(outFd, "Camera service watch commands:\n"
5349 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
5350 " starts watching the provided tags for clients with provided package\n"
5351 " recognizes tag shorthands like '3a'\n"
5352 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005353 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005354 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005355 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005356 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08005357 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005358 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005359 return BAD_VALUE;
5360}
5361
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005362status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
5363 Mutex::Autolock lock(mLogLock);
5364 size_t tagsIdx; // index of '-m'
5365 String16 tags("");
5366 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != String16("-m"); tagsIdx++);
5367 if (tagsIdx < args.size() - 1) {
5368 tags = args[tagsIdx + 1];
5369 } else {
5370 dprintf(outFd, "No tags provided.\n");
5371 return BAD_VALUE;
5372 }
5373
5374 size_t clientsIdx; // index of '-c'
5375 String16 clients = kWatchAllClientsFlag; // watch all clients if no clients are provided
5376 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != String16("-c");
5377 clientsIdx++);
5378 if (clientsIdx < args.size() - 1) {
5379 clients = args[clientsIdx + 1];
5380 }
5381 parseClientsToWatchLocked(String8(clients));
5382
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005383 // track tags to initialize future clients with the monitoring information
5384 mMonitorTags = String8(tags);
5385
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005386 bool serviceLock = tryLock(mServiceLock);
5387 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005388 auto cameraClients = mActiveClientManager.getAll();
5389 for (const auto &clientDescriptor: cameraClients) {
5390 if (clientDescriptor == nullptr) { continue; }
5391 sp<BasicClient> client = clientDescriptor->getValue();
5392 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005393
5394 if (isClientWatchedLocked(client.get())) {
5395 client->startWatchingTags(mMonitorTags, outFd);
5396 numWatchedClients++;
5397 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005398 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005399 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
5400
5401 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005402 return OK;
5403}
5404
5405status_t CameraService::stopWatchingTags(int outFd) {
5406 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005407 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005408 mMonitorTags = String8::empty();
5409
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005410 mWatchedClientPackages.clear();
5411 mWatchedClientsDumpCache.clear();
5412
5413 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005414 auto cameraClients = mActiveClientManager.getAll();
5415 for (const auto &clientDescriptor : cameraClients) {
5416 if (clientDescriptor == nullptr) { continue; }
5417 sp<BasicClient> client = clientDescriptor->getValue();
5418 if (client.get() == nullptr) { continue; }
5419 client->stopWatchingTags(outFd);
5420 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005421 dprintf(outFd, "Stopped watching all clients.\n");
5422 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005423 return OK;
5424}
5425
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005426status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
5427 Mutex::Autolock lock(mLogLock);
5428 size_t clearedSize = mWatchedClientsDumpCache.size();
5429 mWatchedClientsDumpCache.clear();
5430 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
5431 return OK;
5432}
5433
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005434status_t CameraService::printWatchedTags(int outFd) {
5435 Mutex::Autolock logLock(mLogLock);
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08005436 std::set<String16> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005437
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005438 bool printedSomething = false; // tracks if any monitoring information was printed
5439 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005440
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005441 bool serviceLock = tryLock(mServiceLock);
5442 // get all watched clients that are currently connected
5443 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
5444 if (clientDescriptor == nullptr) { continue; }
5445
5446 sp<BasicClient> client = clientDescriptor->getValue();
5447 if (client.get() == nullptr) { continue; }
5448 if (!isClientWatchedLocked(client.get())) { continue; }
5449
5450 std::vector<std::string> dumpVector;
5451 client->dumpWatchedEventsToVector(dumpVector);
5452
5453 size_t printIdx = dumpVector.size();
5454 if (printIdx == 0) {
5455 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005456 }
5457
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005458 // Print tag dumps for active client
5459 const String8 &cameraId = clientDescriptor->getKey();
5460 String8 packageName8 = String8(client->getPackageName());
5461 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
5462 dprintf(outFd, "Client: %s (active)\n", printablePackageName);
5463 while(printIdx > 0) {
5464 printIdx--;
5465 dprintf(outFd, "%s:%s %s", cameraId.string(), printablePackageName,
5466 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005467 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005468 dprintf(outFd, "\n");
5469 packageName8.unlockBuffer();
5470 printedSomething = true;
5471
5472 connectedMonitoredClients.emplace(client->getPackageName());
5473 }
5474 if (serviceLock) { mServiceLock.unlock(); }
5475
5476 // Print entries in mWatchedClientsDumpCache for clients that are not connected
5477 for (const auto &kv: mWatchedClientsDumpCache) {
5478 const String16 &package = kv.first;
5479 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
5480 continue;
5481 }
5482
5483 dprintf(outFd, "Client: %s (cached)\n", String8(package).string());
5484 dprintf(outFd, "%s\n", kv.second.c_str());
5485 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005486 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005487
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005488 if (!printedSomething) {
5489 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005490 }
5491
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005492 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005493}
5494
Avichal Rakesh84147132021-11-11 17:47:11 -08005495// Print all events in vector `events' that came after lastPrintedEvent
5496void printNewWatchedEvents(int outFd,
5497 const char *cameraId,
5498 const String16 &packageName,
5499 const std::vector<std::string> &events,
5500 const std::string &lastPrintedEvent) {
5501 if (events.empty()) { return; }
5502
5503 // index of lastPrintedEvent in events.
5504 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
5505 size_t lastPrintedIdx;
5506 for (lastPrintedIdx = 0;
5507 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
5508 lastPrintedIdx++);
5509
5510 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
5511
5512 String8 packageName8(packageName);
5513 const char *printablePackageName = packageName8.lockBuffer(packageName8.size());
5514
5515 // print events in chronological order (latest event last)
5516 size_t idxToPrint = lastPrintedIdx;
5517 do {
5518 idxToPrint--;
5519 dprintf(outFd, "%s:%s %s", cameraId, printablePackageName, events[idxToPrint].c_str());
5520 } while (idxToPrint != 0);
5521
5522 packageName8.unlockBuffer();
5523}
5524
5525// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
5526// command should be interrupted if the user presses the return key, or if user loses any way to
5527// signal interrupt.
5528// If timeoutMs == 0, this function will always return false
5529bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
5530 struct timeval startTime;
5531 int startTimeError = gettimeofday(&startTime, nullptr);
5532 if (startTimeError) {
5533 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5534 return true;
5535 }
5536
5537 const nfds_t numFds = 1;
5538 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
5539
5540 struct timeval currTime;
5541 char buffer[2];
5542 while(true) {
5543 int currTimeError = gettimeofday(&currTime, nullptr);
5544 if (currTimeError) {
5545 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5546 return true;
5547 }
5548
5549 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
5550 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
5551 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
5552
5553 if (remainingTimeMs <= 0) {
5554 // No user interrupt within timeoutMs, don't interrupt watch command
5555 return false;
5556 }
5557
5558 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
5559 if (numFdsUpdated < 0) {
5560 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5561 return true;
5562 }
5563
5564 if (numFdsUpdated == 0) {
5565 // No user input within timeoutMs, don't interrupt watch command
5566 return false;
5567 }
5568
5569 if (!(pollFd.revents & POLLIN)) {
5570 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5571 return true;
5572 }
5573
5574 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
5575 if (sizeRead < 0) {
5576 dprintf(outFd, "Error reading user input. Exiting.\n");
5577 return true;
5578 }
5579
5580 if (sizeRead == 0) {
5581 // Reached end of input fd (can happen if input is piped)
5582 // User has no way to signal an interrupt, so interrupt here
5583 return true;
5584 }
5585
5586 if (buffer[0] == '\n') {
5587 // User pressed return, interrupt watch command.
5588 return true;
5589 }
5590 }
5591}
5592
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005593status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
5594 int inFd, int outFd) {
5595 // Figure out refresh interval, if present in args
5596 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005597 if (args.size() > 2) {
5598 size_t intervalIdx; // index of '-n'
5599 for (intervalIdx = 2; intervalIdx < args.size() && String16("-n") != args[intervalIdx];
5600 intervalIdx++);
5601
5602 size_t intervalValIdx = intervalIdx + 1;
5603 if (intervalValIdx < args.size()) {
5604 refreshTimeoutMs = strtol(String8(args[intervalValIdx].string()), nullptr, 10);
5605 if (errno) { return BAD_VALUE; }
5606 }
5607 }
5608
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005609 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
5610 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005611
Avichal Rakesh84147132021-11-11 17:47:11 -08005612 dprintf(outFd, "Press return to exit...\n\n");
Avichal Rakesha14d9832021-11-11 01:41:55 -08005613 std::map<String16, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005614
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005615 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005616 bool serviceLock = tryLock(mServiceLock);
5617 auto cameraClients = mActiveClientManager.getAll();
5618 if (serviceLock) { mServiceLock.unlock(); }
5619
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005620 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005621 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005622 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005623
5624 sp<BasicClient> client = clientDescriptor->getValue();
5625 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005626 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005627
Avichal Rakesha14d9832021-11-11 01:41:55 -08005628 const String16 &packageName = client->getPackageName();
5629 // This also initializes the map entries with an empty string
5630 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
5631
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005632 std::vector<std::string> latestEvents;
5633 client->dumpWatchedEventsToVector(latestEvents);
5634
5635 if (!latestEvents.empty()) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005636 String8 cameraId = clientDescriptor->getKey();
5637 const char *printableCameraId = cameraId.lockBuffer(cameraId.size());
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005638 printNewWatchedEvents(outFd,
Avichal Rakesha14d9832021-11-11 01:41:55 -08005639 printableCameraId,
5640 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005641 latestEvents,
5642 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08005643 packageNameToLastEvent[packageName] = latestEvents[0];
5644 cameraId.unlockBuffer();
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005645 }
5646 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005647 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005648 break;
5649 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005650 }
5651 return OK;
5652}
5653
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005654void CameraService::parseClientsToWatchLocked(String8 clients) {
5655 mWatchedClientPackages.clear();
5656
5657 const char *allSentinel = String8(kWatchAllClientsFlag).string();
5658
5659 char *tokenized = clients.lockBuffer(clients.size());
5660 char *savePtr;
5661 char *nextClient = strtok_r(tokenized, ",", &savePtr);
5662
5663 while (nextClient != nullptr) {
5664 if (strcmp(nextClient, allSentinel) == 0) {
5665 // Don't need to track any other package if 'all' is present
5666 mWatchedClientPackages.clear();
5667 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
5668 break;
5669 }
5670
5671 // track package names
5672 mWatchedClientPackages.emplace(nextClient);
5673 nextClient = strtok_r(nullptr, ",", &savePtr);
5674 }
5675 clients.unlockBuffer();
5676}
5677
Svet Ganova453d0d2018-01-11 15:37:58 -08005678status_t CameraService::printHelp(int out) {
5679 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07005680 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
5681 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
5682 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005683 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
5684 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
5685 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005686 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
5687 " Valid values 0=false, 1=true, 2=auto\n"
5688 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005689 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
5690 " Valid values 0=OFF, 1=ON for JPEG\n"
5691 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005692 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08005693 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
5694 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
5695 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
5696 " on. In case the number of usecases is smaller than the number of streams, the\n"
5697 " last use case is assigned to all the remaining streams. In case of multiple\n"
5698 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
5699 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
5700 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
5701 " clear-stream-use-case-override clear the stream use case override\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005702 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08005703 " help print this message\n");
5704}
5705
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005706bool CameraService::isClientWatched(const BasicClient *client) {
5707 Mutex::Autolock lock(mLogLock);
5708 return isClientWatchedLocked(client);
5709}
5710
5711bool CameraService::isClientWatchedLocked(const BasicClient *client) {
5712 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
5713 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
5714}
5715
Yin-Chia Yehdba03232019-08-19 15:54:28 -07005716int32_t CameraService::updateAudioRestriction() {
5717 Mutex::Autolock lock(mServiceLock);
5718 return updateAudioRestrictionLocked();
5719}
5720
5721int32_t CameraService::updateAudioRestrictionLocked() {
5722 int32_t mode = 0;
5723 // iterate through all active client
5724 for (const auto& i : mActiveClientManager.getAll()) {
5725 const auto clientSp = i->getValue();
5726 mode |= clientSp->getAudioRestriction();
5727 }
5728
5729 bool modeChanged = (mAudioRestriction != mode);
5730 mAudioRestriction = mode;
5731 if (modeChanged) {
5732 mAppOps.setCameraAudioRestriction(mode);
5733 }
5734 return mode;
5735}
5736
Cliff Wu646bd612021-11-23 23:21:29 +08005737status_t CameraService::checkIfInjectionCameraIsPresent(const String8& externalCamId,
5738 sp<BasicClient> clientSp) {
5739 std::unique_ptr<AutoConditionLock> lock =
5740 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
5741 status_t res = NO_ERROR;
5742 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
5743 ALOGW("Device %s is not usable!", externalCamId.string());
5744 mInjectionStatusListener->notifyInjectionError(
5745 externalCamId, UNKNOWN_TRANSACTION);
5746 clientSp->notifyError(
5747 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
5748 CaptureResultExtras());
5749
5750 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
5751 // other clients from connecting in mServiceLockWrapper if held
5752 mServiceLock.unlock();
5753
5754 // Clear caller identity temporarily so client disconnect PID checks work correctly
5755 int64_t token = CameraThreadState::clearCallingIdentity();
5756 clientSp->disconnect();
5757 CameraThreadState::restoreCallingIdentity(token);
5758
5759 // Reacquire mServiceLock
5760 mServiceLock.lock();
5761 }
5762
5763 return res;
5764}
5765
Cliff Wud3a05312021-04-26 23:07:31 +08005766void CameraService::clearInjectionParameters() {
5767 {
5768 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08005769 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08005770 mInjectionInternalCamId = "";
5771 }
5772 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08005773 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08005774}
5775
Mathias Agopian65ab4712010-07-14 17:59:35 -07005776}; // namespace android