blob: 4161f01669949ed455edd73aec6825b8e50eeec2 [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>
31
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080032#include <android/hardware/ICamera.h>
33#include <android/hardware/ICameraClient.h>
34
Alex Deymo9c2a2c22016-08-25 11:59:14 -070035#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080036#include <android-base/parseint.h>
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070037#include <android-base/stringprintf.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080038#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080039#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070040#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070041#include <binder/MemoryBase.h>
42#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080043#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080044#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080045#include <binderthreadstate/CallerUtils.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070047#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080048#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080049#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070050#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070051#include "hidl/HidlCameraService.h"
52#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080053#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070054#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070055#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080056#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070058#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000059#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070060#include <utils/Errors.h>
61#include <utils/Log.h>
62#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070063#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080064#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080065#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080066#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080067#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070068#include <system/camera_metadata.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080069
Ruben Brunkb2119af2014-05-09 19:57:56 -070070#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070071
72#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070073#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070074#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070075#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000076#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070077#include "utils/CameraThreadState.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070078#include "utils/CameraServiceProxyWrapper.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070079
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080080namespace {
81 const char* kPermissionServiceName = "permission";
82}; // namespace anonymous
83
Mathias Agopian65ab4712010-07-14 17:59:35 -070084namespace android {
85
Jayant Chowdharyb61526c2019-05-13 19:37:42 -070086using base::StringPrintf;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080087using binder::Status;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -070088using camera3::SessionConfigurationUtils;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070089using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -080090using hardware::ICamera;
91using hardware::ICameraClient;
92using hardware::ICameraServiceListener;
93using hardware::camera::common::V1_0::CameraDeviceStatus;
94using hardware::camera::common::V1_0::TorchModeStatus;
Cliff Wud8cae102021-03-11 01:37:42 +080095using hardware::camera2::ICameraInjectionCallback;
96using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080097using hardware::camera2::utils::CameraIdAndSessionConfiguration;
98using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080099
Mathias Agopian65ab4712010-07-14 17:59:35 -0700100// ----------------------------------------------------------------------------
101// Logging support -- this is for debugging only
102// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700103volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700104
Steve Blockb8a80522011-12-20 16:23:08 +0000105#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
106#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700107
108static void setLogLevel(int level) {
109 android_atomic_write(level, &gLogLevel);
110}
111
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800112// Convenience methods for constructing binder::Status objects for error returns
113
114#define STATUS_ERROR(errorCode, errorString) \
115 binder::Status::fromServiceSpecificError(errorCode, \
116 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
117
118#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
119 binder::Status::fromServiceSpecificError(errorCode, \
120 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \
121 __VA_ARGS__))
122
Mathias Agopian65ab4712010-07-14 17:59:35 -0700123// ----------------------------------------------------------------------------
124
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700125static const String16 sDumpPermission("android.permission.DUMP");
Svet Ganova453d0d2018-01-11 15:37:58 -0800126static const String16 sManageCameraPermission("android.permission.MANAGE_CAMERA");
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700127static const String16 sCameraPermission("android.permission.CAMERA");
128static const String16 sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
129static const String16
130 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Shuzhen Wang695044d2020-03-06 09:02:23 -0800131static const String16 sCameraOpenCloseListenerPermission(
132 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Cliff Wud8cae102021-03-11 01:37:42 +0800133static const String16
134 sCameraInjectExternalCameraPermission("android.permission.CAMERA_INJECT_EXTERNAL_CAMERA");
Rucha Katakwardf223072021-06-15 10:21:00 -0700135const char *sFileName = "lastOpenSessionDumpFile";
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700136static constexpr int32_t kVendorClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
137static constexpr int32_t kVendorClientState = ActivityManager::PROCESS_STATE_PERSISTENT_UI;
138
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800139const String8 CameraService::kOfflineDevice("offline-");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -0700140const String16 CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700141
Rucha Katakward9ea6452021-05-06 11:57:16 -0700142// Set to keep track of logged service error events.
143static std::set<String8> sServiceErrorEventSet;
144
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800145CameraService::CameraService() :
146 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800147 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700148 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700149 mSoundRef(0), mInitialized(false),
150 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000151 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800152 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700153 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
154 if (mMemFd == -1) {
155 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
156 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700157}
158
Iliyan Malchev8951a972011-04-14 16:55:59 -0700159void CameraService::onFirstRef()
160{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700161
Ruben Brunkcc776712015-02-17 20:18:47 -0800162 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800163
Iliyan Malchev8951a972011-04-14 16:55:59 -0700164 BnCameraService::onFirstRef();
165
Ruben Brunk99e69712015-05-26 17:25:07 -0700166 // Update battery life tracking if service is restarting
167 BatteryNotifier& notifier(BatteryNotifier::getInstance());
168 notifier.noteResetCamera();
169 notifier.noteResetFlashlight();
170
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800171 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800172
Emilian Peevf53f66e2017-04-11 14:29:43 +0100173 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800174 if (res == OK) {
175 mInitialized = true;
176 }
177
Svet Ganova453d0d2018-01-11 15:37:58 -0800178 mUidPolicy = new UidPolicy(this);
179 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800180 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
181 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800182 mInjectionStatusListener = new InjectionStatusListener(this);
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700183 mAppOps.setCameraAudioRestriction(mAudioRestriction);
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700184 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
185 if (hcs->registerAsService() != android::OK) {
186 ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
187 __FUNCTION__);
188 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700189
190 // This needs to be last call in this function, so that it's as close to
191 // ServiceManager::addService() as possible.
Shuzhen Wang316781a2020-08-18 18:11:01 -0700192 CameraServiceProxyWrapper::pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700193 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800194}
195
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800196status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800197 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100198
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800199 std::vector<std::string> deviceIds;
200 {
201 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800202
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800203 if (nullptr == mCameraProviderManager.get()) {
204 mCameraProviderManager = new CameraProviderManager();
205 res = mCameraProviderManager->initialize(this);
206 if (res != OK) {
207 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
208 __FUNCTION__, strerror(-res), res);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700209 logServiceError(String8::format("Unable to initialize camera provider manager"),
210 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800211 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100212 }
213 }
214
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800215
216 // Setup vendor tags before we call get_camera_info the first time
217 // because HAL might need to setup static vendor keys in get_camera_info
218 // TODO: maybe put this into CameraProviderManager::initialize()?
219 mCameraProviderManager->setUpVendorTags();
220
221 if (nullptr == mFlashlight.get()) {
222 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700223 }
224
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800225 res = mFlashlight->findFlashUnits();
226 if (res != OK) {
227 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
228 }
229
230 deviceIds = mCameraProviderManager->getCameraDeviceIds();
231 }
232
233
234 for (auto& cameraId : deviceIds) {
235 String8 id8 = String8(cameraId.c_str());
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800236 if (getCameraState(id8) == nullptr) {
237 onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
238 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800239 }
240
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700241 // Derive primary rear/front cameras, and filter their charactierstics.
242 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700243 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700244 // Assume internal cameras are advertised from the same
245 // provider. If multiple providers are registered at different time,
246 // and each provider contains multiple internal color cameras, the current
247 // logic may filter the characteristics of more than one front/rear color
248 // cameras.
249 Mutex::Autolock l(mServiceLock);
250 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700251 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700252
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800253 return OK;
254}
255
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700256void CameraService::broadcastTorchModeStatus(const String8& cameraId, TorchModeStatus status,
257 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800258 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800259 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700260 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
261 i->getListenerUid())) {
262 ALOGV("Skipping torch callback for system-only camera device %s",
263 cameraId.c_str());
264 continue;
265 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700266 i->getListener()->onTorchStatusChanged(mapToInterface(status), String16{cameraId});
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800267 }
268}
269
Mathias Agopian65ab4712010-07-14 17:59:35 -0700270CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800271 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800272 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800273 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800274 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700275}
276
Emilian Peevaee727d2017-05-04 16:35:48 +0100277void CameraService::onNewProviderRegistered() {
278 enumerateProviders();
279}
280
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700281void CameraService::filterAPI1SystemCameraLocked(
282 const std::vector<std::string> &normalDeviceIds) {
283 mNormalDeviceIdsWithoutSystemCamera.clear();
284 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700285 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
286 if (getSystemCameraKind(String8(deviceId.c_str()), &deviceKind) != OK) {
287 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
288 continue;
289 }
290 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700291 // All system camera ids will necessarily come after public camera
292 // device ids as per the HAL interface contract.
293 break;
294 }
295 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
296 }
297 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
298 mNormalDeviceIdsWithoutSystemCamera.size());
299}
300
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700301status_t CameraService::getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const {
302 auto state = getCameraState(cameraId);
303 if (state != nullptr) {
304 *kind = state->getSystemCameraKind();
305 return OK;
306 }
307 // Hidden physical camera ids won't have CameraState
308 return mCameraProviderManager->getSystemCameraKind(cameraId.c_str(), kind);
309}
310
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800311void CameraService::updateCameraNumAndIds() {
312 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700313 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
314 // Excludes hidden secure cameras
315 mNumberOfCameras =
316 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
317 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800318 mNormalDeviceIds =
319 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700320 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800321}
322
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700323void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700324 // To claim to be S Performance primary cameras, the cameras must be
325 // backward compatible. So performance class primary camera Ids must be API1
326 // compatible.
327 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
328 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
329 int facing = -1;
330 int orientation = 0;
331 String8 cameraId8(cameraId.c_str());
332 getDeviceVersion(cameraId8, /*out*/&facing, /*out*/&orientation);
333 if (facing == -1) {
334 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
335 return;
336 }
337
338 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
339 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700340 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
341 if (res == OK) {
342 mPerfClassPrimaryCameraIds.insert(cameraId);
343 } else {
344 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
345 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
346 break;
347 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700348
349 if (facing == hardware::CAMERA_FACING_BACK) {
350 firstRearCameraSeen = true;
351 }
352 if (facing == hardware::CAMERA_FACING_FRONT) {
353 firstFrontCameraSeen = true;
354 }
355 }
356
357 if (firstRearCameraSeen && firstFrontCameraSeen) {
358 break;
359 }
360 }
361}
362
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100363void CameraService::addStates(const String8 id) {
364 std::string cameraId(id.c_str());
365 hardware::camera::common::V1_0::CameraResourceCost cost;
366 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700367 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100368 if (res != OK) {
369 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
370 return;
371 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700372 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
373 if (res != OK) {
374 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
375 return;
376 }
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100377 std::set<String8> conflicting;
378 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
379 conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
380 }
381
382 {
383 Mutex::Autolock lock(mCameraStatesLock);
384 mCameraStates.emplace(id, std::make_shared<CameraState>(id, cost.resourceCost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700385 conflicting, deviceKind));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100386 }
387
388 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100389 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100390 mTorchStatusMap.add(id, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800391
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700392 broadcastTorchModeStatus(id, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100393 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800394
395 updateCameraNumAndIds();
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100396 logDeviceAdded(id, "Device added");
397}
398
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100399void CameraService::removeStates(const String8 id) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800400 updateCameraNumAndIds();
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100401 if (mFlashlight->hasFlashUnit(id)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100402 Mutex::Autolock al(mTorchStatusMutex);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100403 mTorchStatusMap.removeItem(id);
404 }
405
406 {
407 Mutex::Autolock lock(mCameraStatesLock);
408 mCameraStates.erase(id);
409 }
410}
411
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800412void CameraService::onDeviceStatusChanged(const String8& id,
413 CameraDeviceStatus newHalStatus) {
414 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
415 id.string(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700416
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800417 StatusInternal newStatus = mapToInternal(newHalStatus);
418
Ruben Brunkcc776712015-02-17 20:18:47 -0800419 std::shared_ptr<CameraState> state = getCameraState(id);
420
421 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700422 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100423 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700424 __FUNCTION__, id.string());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100425
426 // First add as absent to make sure clients are notified below
427 addStates(id);
428
429 updateStatus(newStatus, id);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700430 } else {
431 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string());
432 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700433 return;
434 }
435
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800436 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800437
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800438 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800439 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700440 return;
441 }
442
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800443 if (newStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700444 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
445 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800446
447 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
448 // to this device until the status changes
449 updateStatus(StatusInternal::NOT_PRESENT, id);
450
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800451 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700452 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800453 // Don't do this in updateStatus to avoid deadlock over mServiceLock
454 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700455
Ruben Brunkcc776712015-02-17 20:18:47 -0800456 // Remove cached shim parameters
457 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700458
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800459 // Remove online as well as offline client from the list of active clients,
460 // if they are present
461 clientToDisconnectOnline = removeClientLocked(id);
462 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + id);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700463 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800464
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800465 disconnectClient(id, clientToDisconnectOnline);
466 disconnectClient(kOfflineDevice + id, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700467
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100468 removeStates(id);
Ruben Brunkcc776712015-02-17 20:18:47 -0800469 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800470 if (oldStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunka8ca9152015-04-07 14:23:40 -0700471 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
472 newStatus));
473 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800474 updateStatus(newStatus, id);
Igor Murashkincba2c162013-03-20 15:56:31 -0700475 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800476}
Igor Murashkincba2c162013-03-20 15:56:31 -0700477
Shuzhen Wang43858162020-01-10 13:42:15 -0800478void CameraService::onDeviceStatusChanged(const String8& id,
479 const String8& physicalId,
480 CameraDeviceStatus newHalStatus) {
481 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
482 __FUNCTION__, id.string(), physicalId.string(), newHalStatus);
483
484 StatusInternal newStatus = mapToInternal(newHalStatus);
485
486 std::shared_ptr<CameraState> state = getCameraState(id);
487
488 if (state == nullptr) {
489 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
490 __FUNCTION__, id.string(), physicalId.string());
491 return;
492 }
493
494 StatusInternal logicalCameraStatus = state->getStatus();
495 if (logicalCameraStatus != StatusInternal::PRESENT &&
496 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
497 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
498 __FUNCTION__, physicalId.string(), newHalStatus, logicalCameraStatus);
499 return;
500 }
501
502 bool updated = false;
503 if (newStatus == StatusInternal::PRESENT) {
504 updated = state->removeUnavailablePhysicalId(physicalId);
505 } else {
506 updated = state->addUnavailablePhysicalId(physicalId);
507 }
508
509 if (updated) {
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800510 String8 idCombo = id + " : " + physicalId;
511 if (newStatus == StatusInternal::PRESENT) {
512 logDeviceAdded(idCombo,
513 String8::format("Device status changed to %d", newStatus));
514 } else {
515 logDeviceRemoved(idCombo,
516 String8::format("Device status changed to %d", newStatus));
517 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700518 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
519 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
520 if (getSystemCameraKind(id, &deviceKind) != OK) {
521 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.string());
522 return;
523 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800524 String16 id16(id), physicalId16(physicalId);
525 Mutex::Autolock lock(mStatusListenerLock);
526 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700527 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
528 listener->getListenerPid(), listener->getListenerUid())) {
529 ALOGV("Skipping discovery callback for system-only camera device %s",
530 id.c_str());
531 continue;
532 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800533 listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
534 id16, physicalId16);
535 }
536 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700537}
538
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800539void CameraService::disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect) {
540 if (clientToDisconnect.get() != nullptr) {
541 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
542 __FUNCTION__, id.string());
543 // Notify the client of disconnection
544 clientToDisconnect->notifyError(
545 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
546 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800547 clientToDisconnect->disconnect();
548 }
549}
550
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800551void CameraService::onTorchStatusChanged(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800552 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700553 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
554 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
555 if (res != OK) {
556 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
557 cameraId.string());
558 return;
559 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800560 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700561 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800562}
563
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700564
565void CameraService::onTorchStatusChanged(const String8& cameraId,
566 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
567 Mutex::Autolock al(mTorchStatusMutex);
568 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
569}
570
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800571void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700572 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800573 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
574 __FUNCTION__, cameraId.string(), newStatus);
575
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800576 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800577 status_t res = getTorchStatusLocked(cameraId, &status);
578 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700579 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
580 __FUNCTION__, cameraId.string(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800581 return;
582 }
583 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800584 return;
585 }
586
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800587 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800588 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800589 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
590 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800591 return;
592 }
593
Ruben Brunkcc776712015-02-17 20:18:47 -0800594 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700595 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700596 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700597 auto iter = mTorchUidMap.find(cameraId);
598 if (iter != mTorchUidMap.end()) {
599 int oldUid = iter->second.second;
600 int newUid = iter->second.first;
601 BatteryNotifier& notifier(BatteryNotifier::getInstance());
602 if (oldUid != newUid) {
603 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800604 if (status == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700605 notifier.noteFlashlightOff(cameraId, oldUid);
606 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800607 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700608 notifier.noteFlashlightOn(cameraId, newUid);
609 }
610 iter->second.second = newUid;
611 } else {
612 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800613 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Ruben Brunk99e69712015-05-26 17:25:07 -0700614 notifier.noteFlashlightOn(cameraId, oldUid);
615 } else {
616 notifier.noteFlashlightOff(cameraId, oldUid);
617 }
618 }
619 }
620 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700621 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800622}
623
Jayant Chowdharyc3198c32021-07-28 20:59:14 +0000624static bool hasPermissionsForSystemCamera(int callingPid, int callingUid,
625 bool logPermissionFailure = false) {
626 return checkPermission(sSystemCameraPermission, callingPid, callingUid,
627 logPermissionFailure) &&
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700628 checkPermission(sCameraPermission, callingPid, callingUid);
629}
630
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800631Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700632 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100633 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700634 bool hasSystemCameraPermissions =
635 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
636 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700637 switch (type) {
638 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700639 if (hasSystemCameraPermissions) {
640 *numCameras = static_cast<int>(mNormalDeviceIds.size());
641 } else {
642 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
643 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800644 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700645 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700646 if (hasSystemCameraPermissions) {
647 *numCameras = mNumberOfCameras;
648 } else {
649 *numCameras = mNumberOfCamerasWithoutSystemCamera;
650 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800651 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700652 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800653 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700654 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800655 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
656 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700657 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800658 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700659}
660
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800661Status CameraService::getCameraInfo(int cameraId,
662 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700663 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100664 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700665 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
666 if (shouldRejectSystemCameraConnection(String8(cameraIdStr.c_str()))) {
667 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
668 "characteristics for system only device %s: ", cameraIdStr.c_str());
669 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100670
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800671 if (!mInitialized) {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700672 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800673 return STATUS_ERROR(ERROR_DISCONNECTED,
674 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700675 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700676 bool hasSystemCameraPermissions =
677 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
678 CameraThreadState::getCallingUid());
679 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
680 if (hasSystemCameraPermissions) {
681 cameraIdBound = mNumberOfCameras;
682 }
683 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800684 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
685 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700686 }
687
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800688 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800689 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700690 cameraIdStr.c_str(), cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100691 if (err != OK) {
692 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
693 "Error retrieving camera info from device %d: %s (%d)", cameraId,
694 strerror(-err), err);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700695 logServiceError(String8::format("Error retrieving camera info from device %d",cameraId),
696 ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -0800697 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100698
Ruben Brunkcc776712015-02-17 20:18:47 -0800699 return ret;
700}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700701
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800702std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700703 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
704 auto callingPid = CameraThreadState::getCallingPid();
705 auto callingUid = CameraThreadState::getCallingUid();
Jayant Chowdharyc3198c32021-07-28 20:59:14 +0000706 if (checkPermission(sSystemCameraPermission, callingPid, callingUid,
707 /*logPermissionFailure*/false) || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700708 deviceIds = &mNormalDeviceIds;
709 }
710 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800711 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700712 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800713 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800714 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800715
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700716 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800717}
718
719String8 CameraService::cameraIdIntToStr(int cameraIdInt) {
720 Mutex::Autolock lock(mServiceLock);
721 return String8(cameraIdIntToStrLocked(cameraIdInt).c_str());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800722}
723
724Status CameraService::getCameraCharacteristics(const String16& cameraId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700725 int targetSdkVersion, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700726 ATRACE_CALL();
Zhijun He2b59be82013-09-25 10:14:30 -0700727 if (!cameraInfo) {
728 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800729 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700730 }
731
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800732 if (!mInitialized) {
733 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -0700734 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800735 return STATUS_ERROR(ERROR_DISCONNECTED,
736 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700737 }
738
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700739 if (shouldRejectSystemCameraConnection(String8(cameraId))) {
740 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
741 "characteristics for system only device %s: ", String8(cameraId).string());
742 }
743
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800744 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800745
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700746
747 std::string cameraIdStr = String8(cameraId).string();
748 bool overrideForPerfClass =
749 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
750 cameraIdStr, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100751 status_t res = mCameraProviderManager->getCameraCharacteristics(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700752 cameraIdStr, overrideForPerfClass, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100753 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700754 if (res == NAME_NOT_FOUND) {
755 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
756 "characteristics for unknown device %s: %s (%d)", String8(cameraId).string(),
757 strerror(-res), res);
758 } else {
Rucha Katakward9ea6452021-05-06 11:57:16 -0700759 logServiceError(String8::format("Unable to retrieve camera characteristics for "
760 "device %s.", String8(cameraId).string()),ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700761 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
762 "characteristics for device %s: %s (%d)", String8(cameraId).string(),
763 strerror(-res), res);
764 }
Ruben Brunkb2119af2014-05-09 19:57:56 -0700765 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700766 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
767 if (getSystemCameraKind(String8(cameraId), &deviceKind) != OK) {
768 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, String8(cameraId).string());
769 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
770 "for device %s", String8(cameraId).string());
771 }
Jayant Chowdhary12361932018-08-27 14:46:13 -0700772 int callingPid = CameraThreadState::getCallingPid();
773 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +0100774 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700775 // If it's not calling from cameraserver, check the permission only if
776 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
777 // it would've already been checked in shouldRejectSystemCameraConnection.
Emilian Peeve20c6372018-08-14 18:45:53 +0100778 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700779 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700780 !checkPermission(sCameraPermission, callingPid, callingUid)) {
Emilian Peeve20c6372018-08-14 18:45:53 +0100781 res = cameraInfo->removePermissionEntries(
782 mCameraProviderManager->getProviderTagIdLocked(String8(cameraId).string()),
783 &tagsRemoved);
784 if (res != OK) {
785 cameraInfo->clear();
786 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
787 " characteristics needing camera permission for device %s: %s (%d)",
788 String8(cameraId).string(), strerror(-res), res);
789 }
790 }
791
792 if (!tagsRemoved.empty()) {
793 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
794 tagsRemoved.data(), tagsRemoved.size());
795 if (res != OK) {
796 cameraInfo->clear();
797 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
798 "keys needing permission for device %s: %s (%d)", String8(cameraId).string(),
799 strerror(-res), res);
800 }
801 }
802
Zhijun He2b59be82013-09-25 10:14:30 -0700803 return ret;
804}
805
Ruben Brunkcc776712015-02-17 20:18:47 -0800806String8 CameraService::getFormattedCurrentTime() {
807 time_t now = time(nullptr);
808 char formattedTime[64];
809 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
810 return String8(formattedTime);
811}
812
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800813Status CameraService::getCameraVendorTagDescriptor(
814 /*out*/
815 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700816 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800817 if (!mInitialized) {
818 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800819 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800820 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -0800821 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
822 if (globalDescriptor != nullptr) {
823 *desc = *(globalDescriptor.get());
824 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800825 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800826}
827
Emilian Peev71c73a22017-03-21 16:35:51 +0000828Status CameraService::getCameraVendorTagCache(
829 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
830 ATRACE_CALL();
831 if (!mInitialized) {
832 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
833 return STATUS_ERROR(ERROR_DISCONNECTED,
834 "Camera subsystem not available");
835 }
836 sp<VendorTagDescriptorCache> globalCache =
837 VendorTagDescriptorCache::getGlobalVendorTagCache();
838 if (globalCache != nullptr) {
839 *cache = *(globalCache.get());
840 }
841 return Status::ok();
842}
843
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700844void CameraService::clearCachedVariables() {
845 BasicClient::BasicClient::sCameraService = nullptr;
846}
847
Emilian Peevb91f1802021-03-23 14:50:28 -0700848int CameraService::getDeviceVersion(const String8& cameraId, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700849 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -0800850
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800851 int deviceVersion = 0;
852
Emilian Peevf53f66e2017-04-11 14:29:43 +0100853 status_t res;
854 hardware::hidl_version maxVersion{0,0};
855 res = mCameraProviderManager->getHighestSupportedVersion(cameraId.string(),
856 &maxVersion);
857 if (res != OK) return -1;
858 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800859
Emilian Peevf53f66e2017-04-11 14:29:43 +0100860 hardware::CameraInfo info;
861 if (facing) {
862 res = mCameraProviderManager->getCameraInfo(cameraId.string(), &info);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -0800863 if (res != OK) return -1;
Emilian Peevf53f66e2017-04-11 14:29:43 +0100864 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -0700865 if (orientation) {
866 *orientation = info.orientation;
867 }
Igor Murashkin634a5152013-02-20 17:15:11 -0800868 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100869
Igor Murashkin634a5152013-02-20 17:15:11 -0800870 return deviceVersion;
871}
872
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800873Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700874 switch(err) {
875 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800876 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800877 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800878 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
879 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800880 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800881 return STATUS_ERROR(ERROR_DISCONNECTED,
882 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700883 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800884 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
885 "Camera HAL encountered error %d: %s",
886 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700887 }
Igor Murashkinbfc99152013-02-27 12:55:20 -0800888}
889
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800890Status CameraService::makeClient(const sp<CameraService>& cameraService,
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800891 const sp<IInterface>& cameraCb, const String16& packageName,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700892 const std::optional<String16>& featureId, const String8& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700893 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700894 int servicePid, int deviceVersion, apiLevel effectiveApiLevel, bool overrideForPerfClass,
Ruben Brunkcc776712015-02-17 20:18:47 -0800895 /*out*/sp<BasicClient>* client) {
896
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700897 // Create CameraClient based on device version reported by the HAL.
898 switch(deviceVersion) {
899 case CAMERA_DEVICE_API_VERSION_1_0:
900 ALOGE("Camera using old HAL version: %d", deviceVersion);
901 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
902 "Camera device \"%s\" HAL version %d no longer supported",
903 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800904 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700905 case CAMERA_DEVICE_API_VERSION_3_0:
906 case CAMERA_DEVICE_API_VERSION_3_1:
907 case CAMERA_DEVICE_API_VERSION_3_2:
908 case CAMERA_DEVICE_API_VERSION_3_3:
909 case CAMERA_DEVICE_API_VERSION_3_4:
910 case CAMERA_DEVICE_API_VERSION_3_5:
911 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -0800912 case CAMERA_DEVICE_API_VERSION_3_7:
Ruben Brunkcc776712015-02-17 20:18:47 -0800913 if (effectiveApiLevel == API_1) { // Camera1 API route
914 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800915 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800916 cameraId, api1CameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700917 facing, sensorOrientation, clientPid, clientUid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700918 servicePid, overrideForPerfClass);
Ruben Brunkcc776712015-02-17 20:18:47 -0800919 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800920 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
921 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800922 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700923 cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
924 overrideForPerfClass);
Ruben Brunkcc776712015-02-17 20:18:47 -0800925 }
926 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700927 default:
Ruben Brunkcc776712015-02-17 20:18:47 -0800928 // Should not be reachable
929 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800930 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800931 "Camera device \"%s\" has unknown HAL version %d",
932 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800933 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800934 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800935}
936
Ruben Brunk6267b532015-04-30 17:44:07 -0700937String8 CameraService::toString(std::set<userid_t> intSet) {
938 String8 s("");
939 bool first = true;
940 for (userid_t i : intSet) {
941 if (first) {
942 s.appendFormat("%d", i);
943 first = false;
944 } else {
945 s.appendFormat(", %d", i);
946 }
947 }
948 return s;
949}
950
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800951int32_t CameraService::mapToInterface(TorchModeStatus status) {
952 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
953 switch (status) {
954 case TorchModeStatus::NOT_AVAILABLE:
955 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
956 break;
957 case TorchModeStatus::AVAILABLE_OFF:
958 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
959 break;
960 case TorchModeStatus::AVAILABLE_ON:
961 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
962 break;
963 default:
964 ALOGW("Unknown new flash status: %d", status);
965 }
966 return serviceStatus;
967}
968
969CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
970 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
971 switch (status) {
972 case CameraDeviceStatus::NOT_PRESENT:
973 serviceStatus = StatusInternal::NOT_PRESENT;
974 break;
975 case CameraDeviceStatus::PRESENT:
976 serviceStatus = StatusInternal::PRESENT;
977 break;
978 case CameraDeviceStatus::ENUMERATING:
979 serviceStatus = StatusInternal::ENUMERATING;
980 break;
981 default:
982 ALOGW("Unknown new HAL device status: %d", status);
983 }
984 return serviceStatus;
985}
986
987int32_t CameraService::mapToInterface(StatusInternal status) {
988 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
989 switch (status) {
990 case StatusInternal::NOT_PRESENT:
991 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
992 break;
993 case StatusInternal::PRESENT:
994 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
995 break;
996 case StatusInternal::ENUMERATING:
997 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
998 break;
999 case StatusInternal::NOT_AVAILABLE:
1000 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1001 break;
1002 case StatusInternal::UNKNOWN:
1003 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1004 break;
1005 default:
1006 ALOGW("Unknown new internal device status: %d", status);
1007 }
1008 return serviceStatus;
1009}
1010
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001011Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001012 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001013
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001014 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -08001015 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001016 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001017 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001018 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001019 sp<ICameraClient>{nullptr}, id, cameraId,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001020 internalPackageName, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001021 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
1022 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001023 ).isOk()) {
1024 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001025 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001026 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001027}
1028
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001029Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001030 /*out*/
1031 CameraParameters* parameters) {
1032
1033 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1034
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001035 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001036
1037 if (parameters == NULL) {
1038 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001039 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001040 }
1041
Ruben Brunkcc776712015-02-17 20:18:47 -08001042 String8 id = String8::format("%d", cameraId);
1043
1044 // Check if we already have parameters
1045 {
1046 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001047 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001048 auto cameraState = getCameraState(id);
1049 if (cameraState == nullptr) {
1050 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001051 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1052 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001053 }
1054 CameraParameters p = cameraState->getShimParams();
1055 if (!p.isEmpty()) {
1056 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001057 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001058 }
1059 }
1060
Jayant Chowdhary12361932018-08-27 14:46:13 -07001061 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001062 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001063 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001064 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001065 // Error already logged by callee
1066 return ret;
1067 }
1068
1069 // Check for parameters again
1070 {
1071 // Scope for service lock
1072 Mutex::Autolock lock(mServiceLock);
1073 auto cameraState = getCameraState(id);
1074 if (cameraState == nullptr) {
1075 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001076 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1077 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001078 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001079 CameraParameters p = cameraState->getShimParams();
1080 if (!p.isEmpty()) {
1081 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001082 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001083 }
1084 }
1085
Ruben Brunkcc776712015-02-17 20:18:47 -08001086 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1087 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001088 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001089}
1090
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001091// Can camera service trust the caller based on the calling UID?
1092static bool isTrustedCallingUid(uid_t uid) {
1093 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001094 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001095 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001096 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001097 return true;
1098 default:
1099 return false;
1100 }
1101}
1102
Nicholas Sauera3620332019-04-03 14:05:17 -07001103static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1104 PermissionController pc;
1105 uid = pc.getPackageUid(packageName, 0);
1106 if (uid <= 0) {
1107 ALOGE("Unknown package: '%s'", String8(packageName).string());
1108 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1109 return BAD_VALUE;
1110 }
1111
1112 if (userId < 0) {
1113 ALOGE("Invalid user: %d", userId);
1114 dprintf(err, "Invalid user: %d\n", userId);
1115 return BAD_VALUE;
1116 }
1117
1118 uid = multiuser_get_uid(userId, uid);
1119 return NO_ERROR;
1120}
1121
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001122Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001123 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1124 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001125
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001126#ifdef __BRILLO__
1127 UNUSED(clientName8);
1128 UNUSED(clientUid);
1129 UNUSED(clientPid);
1130 UNUSED(originalClientPid);
1131#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001132 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1133 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001134 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001135 return allowed;
1136 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001137#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001138
Jayant Chowdhary12361932018-08-27 14:46:13 -07001139 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001140
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001141 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001142 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1143 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001144 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1145 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001146 }
1147
Ruben Brunkcc776712015-02-17 20:18:47 -08001148 if (getCameraState(cameraId) == nullptr) {
1149 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1150 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001151 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1152 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001153 }
1154
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001155 status_t err = checkIfDeviceIsUsable(cameraId);
1156 if (err != NO_ERROR) {
1157 switch(err) {
1158 case -ENODEV:
1159 case -EBUSY:
1160 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1161 "No camera device with ID \"%s\" currently available", cameraId.string());
1162 default:
1163 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1164 "Unknown error connecting to ID \"%s\"", cameraId.string());
1165 }
1166 }
1167 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001168}
1169
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001170Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001171 const String8& clientName8, int& clientUid, int& clientPid,
1172 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001173 int callingPid = CameraThreadState::getCallingPid();
1174 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001175
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001176 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001177 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001178 clientUid = callingUid;
1179 } else if (!isTrustedCallingUid(callingUid)) {
1180 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1181 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001182 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1183 "Untrusted caller (calling PID %d, UID %d) trying to "
1184 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1185 callingPid, callingUid, cameraId.string(),
1186 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001187 }
1188
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001189 // Check if we can trust clientPid
1190 if (clientPid == USE_CALLING_PID) {
1191 clientPid = callingPid;
1192 } else if (!isTrustedCallingUid(callingUid)) {
1193 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1194 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001195 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1196 "Untrusted caller (calling PID %d, UID %d) trying to "
1197 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1198 callingPid, callingUid, cameraId.string(),
1199 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001200 }
1201
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001202 if (shouldRejectSystemCameraConnection(cameraId)) {
1203 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1204 cameraId.c_str());
1205 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1206 "available", cameraId.string());
1207 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001208 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1209 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1210 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1211 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1212 "found while trying to query device kind", cameraId.string());
1213
1214 }
1215
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001216 // If it's not calling from cameraserver, check the permission if the
1217 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1218 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001219 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001220 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001221 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001222 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001223 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1224 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1225 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001226 }
1227
Svet Ganova453d0d2018-01-11 15:37:58 -08001228 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001229 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001230 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001231 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1232 clientPid, clientUid);
1233 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001234 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1235 "calling UID %d proc state %" PRId32 ")",
1236 clientName8.string(), clientUid, clientPid, cameraId.string(),
1237 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001238 }
1239
Michael Grooverd1d435a2018-12-18 17:39:42 -08001240 // If sensor privacy is enabled then prevent access to the camera
1241 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1242 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1243 return STATUS_ERROR_FMT(ERROR_DISABLED,
1244 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1245 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1246 }
1247
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001248 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1249 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001250 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001251 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001252
Ruben Brunk6267b532015-04-30 17:44:07 -07001253 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001254
Ruben Brunka8ca9152015-04-07 14:23:40 -07001255 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001256 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001257 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001258 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001259 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1260 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1261 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001262 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1263 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1264 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001265 }
1266
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001267 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001268}
1269
1270status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1271 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001272 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001273 if (cameraState == nullptr) {
1274 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1275 cameraId.string());
1276 return -ENODEV;
1277 }
1278
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001279 StatusInternal currentStatus = cameraState->getStatus();
1280 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001281 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1282 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001283 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001284 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001285 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1286 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001287 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001288 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001289
Ruben Brunkcc776712015-02-17 20:18:47 -08001290 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001291}
1292
Ruben Brunkcc776712015-02-17 20:18:47 -08001293void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001294 const CameraService::DescriptorPtr& desc, int oomScoreOffset) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001295
Ruben Brunkcc776712015-02-17 20:18:47 -08001296 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001297 auto clientDescriptor =
1298 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
1299 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08001300 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1301
1302 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1303 String8(client->getPackageName()));
1304
1305 if (evicted.size() > 0) {
1306 // This should never happen - clients should already have been removed in disconnect
1307 for (auto& i : evicted) {
1308 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1309 __FUNCTION__, i->getKey().string());
1310 }
1311
1312 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1313 __FUNCTION__);
1314 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001315
1316 // And register a death notification for the client callback. Do
1317 // this last to avoid Binder policy where a nested Binder
1318 // transaction might be pre-empted to service the client death
1319 // notification if the client process dies before linkToDeath is
1320 // invoked.
1321 sp<IBinder> remoteCallback = client->getRemote();
1322 if (remoteCallback != nullptr) {
1323 remoteCallback->linkToDeath(this);
1324 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001325}
1326
1327status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1328 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001329 int oomScoreOffset,
Ruben Brunkcc776712015-02-17 20:18:47 -08001330 /*out*/
1331 sp<BasicClient>* client,
1332 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001333 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001334 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001335 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001336 DescriptorPtr clientDescriptor;
1337 {
1338 if (effectiveApiLevel == API_1) {
1339 // If we are using API1, any existing client for this camera ID with the same remote
1340 // should be returned rather than evicted to allow MediaRecorder to work properly.
1341
1342 auto current = mActiveClientManager.get(cameraId);
1343 if (current != nullptr) {
1344 auto clientSp = current->getValue();
1345 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001346 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001347 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001348 " API level, evicting prior client...");
1349 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001350 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001351 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001352 *client = clientSp;
1353 return NO_ERROR;
1354 }
1355 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001356 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001357 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001358
Ruben Brunkcc776712015-02-17 20:18:47 -08001359 // Get current active client PIDs
1360 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1361 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001362
Emilian Peev8131a262017-02-01 12:33:43 +00001363 std::vector<int> priorityScores(ownerPids.size());
1364 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001365
Emilian Peev8131a262017-02-01 12:33:43 +00001366 // Get priority scores of all active PIDs
1367 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1368 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1369 /*out*/&priorityScores[0]);
1370 if (err != OK) {
1371 ALOGE("%s: Priority score query failed: %d",
1372 __FUNCTION__, err);
1373 return err;
1374 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001375
Ruben Brunkcc776712015-02-17 20:18:47 -08001376 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001377 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001378 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001379 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001380 resource_policy::ClientPriority(priorityScores[i], states[i],
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001381 /* isVendorClient won't get copied over*/ false,
1382 /* oomScoreOffset won't get copied over*/ 0));
Ruben Brunkcc776712015-02-17 20:18:47 -08001383 }
1384 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001385
Ruben Brunkcc776712015-02-17 20:18:47 -08001386 // Get state for the given cameraId
1387 auto state = getCameraState(cameraId);
1388 if (state == nullptr) {
1389 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1390 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001391 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001392 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001393 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001394
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001395 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1396 int32_t actualState = states[states.size() - 1];
1397
1398 // Make descriptor for incoming client. We store the oomScoreOffset
1399 // since we might need it later on new handleEvictionsLocked and
1400 // ProcessInfoService would not take that into account.
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001401 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001402 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001403 state->getConflicting(), actualScore, clientPid, actualState,
1404 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08001405
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001406 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1407
Ruben Brunkcc776712015-02-17 20:18:47 -08001408 // Find clients that would be evicted
1409 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1410
1411 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1412 // background, so we cannot do evictions
1413 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1414 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1415 " priority).", clientPid);
1416
1417 sp<BasicClient> clientSp = clientDescriptor->getValue();
1418 String8 curTime = getFormattedCurrentTime();
1419 auto incompatibleClients =
1420 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1421
1422 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001423 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001424 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001425 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001426
1427 for (auto& i : incompatibleClients) {
1428 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001429 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1430 i->getKey().string(),
1431 String8{i->getValue()->getPackageName()}.string(),
1432 i->getOwnerId(), i->getPriority().getScore(),
1433 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001434 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001435 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001436 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001437 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001438 }
1439
1440 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001441 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001442 mEventLog.add(msg);
1443
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001444 auto current = mActiveClientManager.get(cameraId);
1445 if (current != nullptr) {
1446 return -EBUSY; // CAMERA_IN_USE
1447 } else {
1448 return -EUSERS; // MAX_CAMERAS_IN_USE
1449 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001450 }
1451
1452 for (auto& i : evicted) {
1453 sp<BasicClient> clientSp = i->getValue();
1454 if (clientSp.get() == nullptr) {
1455 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1456
1457 // TODO: Remove this
1458 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1459 __FUNCTION__);
1460 mActiveClientManager.remove(i);
1461 continue;
1462 }
1463
1464 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1465 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001466 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001467
Ruben Brunkcc776712015-02-17 20:18:47 -08001468 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001469 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001470 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1471 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001472 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001473 i->getOwnerId(), i->getPriority().getScore(),
1474 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001475 packageName.string(), clientPid, clientPriority.getScore(),
1476 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001477
1478 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001479 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001480 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001481 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001482 }
1483
Ruben Brunkcc776712015-02-17 20:18:47 -08001484 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1485 // other clients from connecting in mServiceLockWrapper if held
1486 mServiceLock.unlock();
1487
1488 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001489 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001490
1491 // Destroy evicted clients
1492 for (auto& i : evictedClients) {
1493 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001494 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001495 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001496
Jayant Chowdhary12361932018-08-27 14:46:13 -07001497 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001498
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001499 for (const auto& i : evictedClients) {
1500 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1501 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1502 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1503 if (ret == TIMED_OUT) {
1504 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1505 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1506 mActiveClientManager.toString().string());
1507 return -EBUSY;
1508 }
1509 if (ret != NO_ERROR) {
1510 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1511 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1512 ret, mActiveClientManager.toString().string());
1513 return ret;
1514 }
1515 }
1516
1517 evictedClients.clear();
1518
Ruben Brunkcc776712015-02-17 20:18:47 -08001519 // Once clients have been disconnected, relock
1520 mServiceLock.lock();
1521
1522 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1523 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1524 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001525 }
1526
Ruben Brunkcc776712015-02-17 20:18:47 -08001527 *partial = clientDescriptor;
1528 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001529}
1530
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001531Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001532 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001533 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001534 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001535 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001536 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001537 int targetSdkVersion,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001538 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001539 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001540
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001541 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001542 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001543
1544 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001545 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001546 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001547 clientPackageName, {}, clientUid, clientPid, API_1,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001548 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001549
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001550 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001551 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001552 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001553 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001554 }
1555
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001556 *device = client;
1557 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001558}
1559
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001560bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1561 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001562 // If the client is not a vendor client, don't add listener if
1563 // a) the camera is a publicly hidden secure camera OR
1564 // b) the camera is a system only camera and the client doesn't
1565 // have android.permission.SYSTEM_CAMERA permissions.
1566 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1567 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1568 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001569 return true;
1570 }
1571 return false;
1572}
1573
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001574bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1575 // Rules for rejection:
1576 // 1) If cameraserver tries to access this camera device, accept the
1577 // connection.
1578 // 2) The camera device is a publicly hidden secure camera device AND some
1579 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1580 // reject it.
1581 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1582 // and the serving thread is a non hwbinder thread, the client must have
1583 // android.permission.SYSTEM_CAMERA permissions to connect.
1584
1585 int cPid = CameraThreadState::getCallingPid();
1586 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001587 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1588 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001589 // This isn't a known camera ID, so it's not a system camera
1590 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1591 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001592 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001593
1594 // (1) Cameraserver trying to connect, accept.
1595 if (CameraThreadState::getCallingPid() == getpid()) {
1596 return false;
1597 }
1598 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001599 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001600 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1601 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1602 return true;
1603 }
1604 // (3) Here we only check for permissions if it is a system only camera device. This is since
1605 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1606 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1607 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001608 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001609 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jayant Chowdharyc3198c32021-07-28 20:59:14 +00001610 !hasPermissionsForSystemCamera(cPid, cUid, /*logPermissionFailure*/true)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001611 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1612 cameraId.c_str());
1613 return true;
1614 }
1615
1616 return false;
1617}
1618
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001619Status CameraService::connectDevice(
1620 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001621 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001622 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001623 const std::optional<String16>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001624 int clientUid, int oomScoreOffset, int targetSdkVersion,
Ruben Brunkcc776712015-02-17 20:18:47 -08001625 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001626 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001627
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001628 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001629 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001630 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001631 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001632 String16 clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001633 int callingPid = CameraThreadState::getCallingPid();
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001634
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001635 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001636 std::string vendorClient =
1637 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1638 clientPackageNameAdj = String16(vendorClient.c_str());
1639 }
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001640
1641 if (oomScoreOffset < 0) {
1642 String8 msg =
1643 String8::format("Cannot increase the priority of a client %s pid %d for "
1644 "camera id %s", String8(clientPackageNameAdj).string(), callingPid,
1645 id.string());
1646 ALOGE("%s: %s", __FUNCTION__, msg.string());
1647 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1648 }
1649
1650 // enforce system camera permissions
1651 if (oomScoreOffset > 0 &&
1652 !hasPermissionsForSystemCamera(callingPid, CameraThreadState::getCallingUid())) {
1653 String8 msg =
1654 String8::format("Cannot change the priority of a client %s pid %d for "
1655 "camera id %s without SYSTEM_CAMERA permissions",
1656 String8(clientPackageNameAdj).string(), callingPid, id.string());
1657 ALOGE("%s: %s", __FUNCTION__, msg.string());
1658 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.string());
1659 }
1660
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001661 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001662 /*api1CameraId*/-1, clientPackageNameAdj, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001663 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001664 targetSdkVersion, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001665
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001666 if(!ret.isOk()) {
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001667 logRejected(id, callingPid, String8(clientPackageNameAdj), ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001668 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001669 }
1670
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001671 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07001672 Mutex::Autolock lock(mServiceLock);
1673
1674 // Clear the previous cached logs and reposition the
1675 // file offset to beginning of the file to log new data.
1676 // If either truncate or lseek fails, close the previous file and create a new one.
1677 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
1678 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
1679 // Close the previous memfd.
1680 close(mMemFd);
1681 // If failure to wipe the data, then create a new file and
1682 // assign the new value to mMemFd.
1683 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
1684 if (mMemFd == -1) {
1685 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
1686 }
1687 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001688 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001689}
1690
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001691template<class CALLBACK, class CLIENT>
1692Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001693 int api1CameraId, const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001694 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001695 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001696 /*out*/sp<CLIENT>& device) {
1697 binder::Status ret = binder::Status::ok();
1698
1699 String8 clientName8(clientPackageName);
1700
1701 int originalClientPid = 0;
1702
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001703 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001704 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001705 static_cast<int>(effectiveApiLevel));
1706
Shuzhen Wang316781a2020-08-18 18:11:01 -07001707 nsecs_t openTimeNs = systemTime();
1708
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001709 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001710 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07001711 int orientation = 0;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001712 bool isNdk = (clientPackageName.size() == 0);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001713 {
1714 // Acquire mServiceLock and prevent other clients from connecting
1715 std::unique_ptr<AutoConditionLock> lock =
1716 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1717
1718 if (lock == nullptr) {
1719 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1720 , clientPid);
1721 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1722 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1723 cameraId.string(), clientName8.string(), clientPid);
1724 }
1725
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001726 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001727 if(!(ret = validateConnectLocked(cameraId, clientName8,
1728 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1729 return ret;
1730 }
1731
1732 // Check the shim parameters after acquiring lock, if they have already been updated and
1733 // we were doing a shim update, return immediately
1734 if (shimUpdateOnly) {
1735 auto cameraState = getCameraState(cameraId);
1736 if (cameraState != nullptr) {
1737 if (!cameraState->getShimParams().isEmpty()) return ret;
1738 }
1739 }
1740
1741 status_t err;
1742
1743 sp<BasicClient> clientTmp = nullptr;
1744 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1745 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001746 IInterface::asBinder(cameraCb), clientName8, oomScoreOffset, /*out*/&clientTmp,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001747 /*out*/&partial)) != NO_ERROR) {
1748 switch (err) {
1749 case -ENODEV:
1750 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1751 "No camera device with ID \"%s\" currently available",
1752 cameraId.string());
1753 case -EBUSY:
1754 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1755 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1756 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001757 case -EUSERS:
1758 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1759 "Too many cameras already open, cannot open camera \"%s\"",
1760 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001761 default:
1762 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1763 "Unexpected error %s (%d) opening camera \"%s\"",
1764 strerror(-err), err, cameraId.string());
1765 }
1766 }
1767
1768 if (clientTmp.get() != nullptr) {
1769 // Handle special case for API1 MediaRecorder where the existing client is returned
1770 device = static_cast<CLIENT*>(clientTmp.get());
1771 return ret;
1772 }
1773
1774 // give flashlight a chance to close devices if necessary.
1775 mFlashlight->prepareDeviceOpen(cameraId);
1776
Emilian Peevb91f1802021-03-23 14:50:28 -07001777 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001778 if (facing == -1) {
1779 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1780 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1781 "Unable to get camera device \"%s\" facing", cameraId.string());
1782 }
1783
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001784 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001785 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1786 mPerfClassPrimaryCameraIds, cameraId.string(), targetSdkVersion);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001787 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001788 cameraId, api1CameraId, facing, orientation,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001789 clientPid, clientUid, getpid(),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001790 deviceVersion, effectiveApiLevel, overrideForPerfClass,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001791 /*out*/&tmp)).isOk()) {
1792 return ret;
1793 }
1794 client = static_cast<CLIENT*>(tmp.get());
1795
1796 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1797 __FUNCTION__);
1798
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07001799 String8 monitorTags = isClientWatched(client.get()) ? mMonitorTags : String8("");
1800 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001801 if (err != OK) {
1802 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001803 // Errors could be from the HAL module open call or from AppOpsManager
1804 switch(err) {
1805 case BAD_VALUE:
1806 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1807 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1808 case -EBUSY:
1809 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1810 "Camera \"%s\" is already open", cameraId.string());
1811 case -EUSERS:
1812 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1813 "Too many cameras already open, cannot open camera \"%s\"",
1814 cameraId.string());
1815 case PERMISSION_DENIED:
1816 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1817 "No permission to open camera \"%s\"", cameraId.string());
1818 case -EACCES:
1819 return STATUS_ERROR_FMT(ERROR_DISABLED,
1820 "Camera \"%s\" disabled by policy", cameraId.string());
1821 case -ENODEV:
1822 default:
1823 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1824 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1825 strerror(-err), err);
1826 }
1827 }
1828
1829 // Update shim paremeters for legacy clients
1830 if (effectiveApiLevel == API_1) {
1831 // Assume we have always received a Client subclass for API1
1832 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1833 String8 rawParams = shimClient->getParameters();
1834 CameraParameters params(rawParams);
1835
1836 auto cameraState = getCameraState(cameraId);
1837 if (cameraState != nullptr) {
1838 cameraState->setShimParams(params);
1839 } else {
1840 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1841 __FUNCTION__, cameraId.string());
1842 }
1843 }
1844
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001845 // Set rotate-and-crop override behavior
1846 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1847 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Emilian Peev5368ebf2021-10-08 17:52:18 -07001848 } else if (effectiveApiLevel == API_2) {
1849 client->setRotateAndCropOverride(CameraServiceProxyWrapper::getRotateAndCropOverride(
1850 clientPackageName, facing));
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001851 }
1852
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001853 // Set camera muting behavior
Valentin Iftimec0b8d472021-07-23 20:21:06 +02001854 bool isCameraPrivacyEnabled =
1855 mSensorPrivacyPolicy->isCameraPrivacyEnabled(multiuser_get_user_id(clientUid));
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001856 if (client->supportsCameraMute()) {
Valentin Iftimec0b8d472021-07-23 20:21:06 +02001857 client->setCameraMute(
1858 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
1859 } else if (isCameraPrivacyEnabled) {
1860 // no camera mute supported, but privacy is on! => disconnect
1861 ALOGI("Camera mute not supported for package: %s, camera id: %s",
1862 String8(client->getPackageName()).string(), cameraId.string());
1863 // Do not hold mServiceLock while disconnecting clients, but
1864 // retain the condition blocking other clients from connecting
1865 // in mServiceLockWrapper if held.
1866 mServiceLock.unlock();
1867 // Clear caller identity temporarily so client disconnect PID
1868 // checks work correctly
1869 int64_t token = CameraThreadState::clearCallingIdentity();
1870 // Note AppOp to trigger the "Unblock" dialog
1871 client->noteAppOp();
1872 client->disconnect();
1873 CameraThreadState::restoreCallingIdentity(token);
1874 // Reacquire mServiceLock
1875 mServiceLock.lock();
1876
1877 return STATUS_ERROR_FMT(ERROR_DISABLED,
1878 "Camera \"%s\" disabled due to camera mute", cameraId.string());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001879 }
1880
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001881 if (shimUpdateOnly) {
1882 // If only updating legacy shim parameters, immediately disconnect client
1883 mServiceLock.unlock();
1884 client->disconnect();
1885 mServiceLock.lock();
1886 } else {
1887 // Otherwise, add client to active clients list
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001888 finishConnectLocked(client, partial, oomScoreOffset);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001889 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001890
1891 client->setImageDumpMask(mImageDumpMask);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001892 } // lock is destroyed, allow further connect calls
1893
1894 // Important: release the mutex here so the client can call back into the service from its
1895 // destructor (can be at the end of the call)
1896 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001897
1898 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
1899 CameraServiceProxyWrapper::logOpen(cameraId, facing, clientPackageName,
1900 effectiveApiLevel, isNdk, openLatencyMs);
1901
Cliff Wud3a05312021-04-26 23:07:31 +08001902 {
1903 Mutex::Autolock lock(mInjectionParametersLock);
1904 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
1905 mInjectionInitPending = false;
1906 status_t res = NO_ERROR;
1907 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
1908 if (clientDescriptor != nullptr) {
1909 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
1910 res = baseClientPtr->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
1911 if (res != OK) {
1912 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
1913 }
1914 } else {
1915 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
1916 __FUNCTION__, mInjectionInternalCamId.string());
1917 res = NO_INIT;
1918 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
1919 }
1920 }
1921 }
1922
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001923 return ret;
1924}
1925
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001926status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1927 if (offlineClient.get() == nullptr) {
1928 return BAD_VALUE;
1929 }
1930
1931 {
1932 // Acquire mServiceLock and prevent other clients from connecting
1933 std::unique_ptr<AutoConditionLock> lock =
1934 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1935
1936 if (lock == nullptr) {
1937 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1938 , __FUNCTION__, offlineClient->getClientPid());
1939 return TIMED_OUT;
1940 }
1941
1942 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1943 if (onlineClientDesc.get() == nullptr) {
1944 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1945 cameraId.c_str());
1946 return BAD_VALUE;
1947 }
1948
1949 // Offline clients do not evict or conflict with other online devices. Resource sharing
1950 // conflicts are handled by the camera provider which will either succeed or fail before
1951 // reaching this method.
1952 const auto& onlinePriority = onlineClientDesc->getPriority();
1953 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1954 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1955 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001956 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
1957 /*ommScoreOffset*/ 0);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001958
1959 // Allow only one offline device per camera
1960 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1961 if (!incompatibleClients.empty()) {
1962 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1963 return BAD_VALUE;
1964 }
1965
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07001966 String8 monitorTags = isClientWatched(offlineClient.get()) ? mMonitorTags : String8("");
1967 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001968 if (err != OK) {
1969 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1970 return err;
1971 }
1972
1973 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1974 if (evicted.size() > 0) {
1975 for (auto& i : evicted) {
1976 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1977 __FUNCTION__, i->getKey().string());
1978 }
1979
1980 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1981 "properly", __FUNCTION__);
1982
1983 return BAD_VALUE;
1984 }
1985
1986 logConnectedOffline(offlineClientDesc->getKey(),
1987 static_cast<int>(offlineClientDesc->getOwnerId()),
1988 String8(offlineClient->getPackageName()));
1989
1990 sp<IBinder> remoteCallback = offlineClient->getRemote();
1991 if (remoteCallback != nullptr) {
1992 remoteCallback->linkToDeath(this);
1993 }
1994 } // lock is destroyed, allow further connect calls
1995
1996 return OK;
1997}
1998
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001999Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002000 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002001 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002002
2003 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002004 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002005 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002006 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2007 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002008 }
2009
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002010 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07002011 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002012
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002013 if (shouldRejectSystemCameraConnection(id)) {
2014 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
2015 " for system only device %s: ", id.string());
2016 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002017 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08002018 auto state = getCameraState(id);
2019 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002020 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002021 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2022 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002023 }
2024
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002025 StatusInternal cameraStatus = state->getStatus();
2026 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002027 cameraStatus != StatusInternal::NOT_AVAILABLE) {
2028 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002029 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2030 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002031 }
2032
2033 {
2034 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002035 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002036 status_t err = getTorchStatusLocked(id, &status);
2037 if (err != OK) {
2038 if (err == NAME_NOT_FOUND) {
2039 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2040 "Camera \"%s\" does not have a flash unit", id.string());
2041 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002042 ALOGE("%s: getting current torch status failed for camera %s",
2043 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002044 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2045 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
2046 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002047 }
2048
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002049 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002050 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002051 ALOGE("%s: torch mode of camera %s is not available because "
2052 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002053 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2054 "Torch for camera \"%s\" is not available due to an existing camera user",
2055 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002056 } else {
2057 ALOGE("%s: torch mode of camera %s is not available due to "
2058 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002059 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2060 "Torch for camera \"%s\" is not available due to insufficient resources",
2061 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002062 }
2063 }
2064 }
2065
Ruben Brunk99e69712015-05-26 17:25:07 -07002066 {
2067 // Update UID map - this is used in the torch status changed callbacks, so must be done
2068 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002069 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07002070 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
2071 mTorchUidMap[id].first = uid;
2072 mTorchUidMap[id].second = uid;
2073 } else {
2074 // Set the pending UID
2075 mTorchUidMap[id].first = uid;
2076 }
2077 }
2078
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002079 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002080
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002081 if (err != OK) {
2082 int32_t errorCode;
2083 String8 msg;
2084 switch (err) {
2085 case -ENOSYS:
2086 msg = String8::format("Camera \"%s\" has no flashlight",
2087 id.string());
2088 errorCode = ERROR_ILLEGAL_ARGUMENT;
2089 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08002090 case -EBUSY:
2091 msg = String8::format("Camera \"%s\" is in use",
2092 id.string());
2093 errorCode = ERROR_CAMERA_IN_USE;
2094 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002095 default:
2096 msg = String8::format(
2097 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
2098 id.string(), enabled, strerror(-err), err);
2099 errorCode = ERROR_INVALID_OPERATION;
2100 }
2101 ALOGE("%s: %s", __FUNCTION__, msg.string());
Rucha Katakward9ea6452021-05-06 11:57:16 -07002102 logServiceError(msg,errorCode);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002103 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002104 }
2105
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002106 {
2107 // update the link to client's death
2108 Mutex::Autolock al(mTorchClientMapMutex);
2109 ssize_t index = mTorchClientMap.indexOfKey(id);
2110 if (enabled) {
2111 if (index == NAME_NOT_FOUND) {
2112 mTorchClientMap.add(id, clientBinder);
2113 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07002114 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002115 mTorchClientMap.replaceValueAt(index, clientBinder);
2116 }
2117 clientBinder->linkToDeath(this);
2118 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07002119 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002120 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002121 }
2122
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002123 int clientPid = CameraThreadState::getCallingPid();
2124 const char *id_cstr = id.c_str();
2125 const char *torchState = enabled ? "on" : "off";
2126 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
2127 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002128 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002129}
2130
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002131Status CameraService::notifySystemEvent(int32_t eventId,
2132 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002133 const int pid = CameraThreadState::getCallingPid();
2134 const int selfPid = getpid();
2135
2136 // Permission checks
2137 if (pid != selfPid) {
2138 // Ensure we're being called by system_server, or similar process with
2139 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002140 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002141 const int uid = CameraThreadState::getCallingUid();
2142 ALOGE("Permission Denial: cannot send updates to camera service about system"
2143 " events from pid=%d, uid=%d", pid, uid);
2144 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09002145 "No permission to send updates to camera service about system events"
2146 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002147 }
2148 }
2149
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002150 ATRACE_CALL();
2151
Ruben Brunk36597b22015-03-20 22:15:57 -07002152 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002153 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002154 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002155 // from a system server crash
2156 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002157 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002158 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002159 break;
2160 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002161 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002162 default: {
2163 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2164 eventId);
2165 break;
2166 }
2167 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002168 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002169}
2170
Emilian Peev53722fa2019-02-22 17:47:20 -08002171void CameraService::notifyMonitoredUids() {
2172 Mutex::Autolock lock(mStatusListenerLock);
2173
2174 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002175 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08002176 if (!ret.isOk()) {
2177 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
2178 ret.exceptionCode());
2179 }
2180 }
2181}
2182
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002183Status CameraService::notifyDeviceStateChange(int64_t newState) {
2184 const int pid = CameraThreadState::getCallingPid();
2185 const int selfPid = getpid();
2186
2187 // Permission checks
2188 if (pid != selfPid) {
2189 // Ensure we're being called by system_server, or similar process with
2190 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002191 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002192 const int uid = CameraThreadState::getCallingUid();
2193 ALOGE("Permission Denial: cannot send updates to camera service about device"
2194 " state changes from pid=%d, uid=%d", pid, uid);
2195 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2196 "No permission to send updates to camera service about device state"
2197 " changes from pid=%d, uid=%d", pid, uid);
2198 }
2199 }
2200
2201 ATRACE_CALL();
2202
2203 using hardware::camera::provider::V2_5::DeviceState;
2204 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2205 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2206 newDeviceState |= DeviceState::BACK_COVERED;
2207 }
2208 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2209 newDeviceState |= DeviceState::FRONT_COVERED;
2210 }
2211 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2212 newDeviceState |= DeviceState::FOLDED;
2213 }
2214 // Only map vendor bits directly
2215 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2216 newDeviceState |= vendorBits;
2217
2218 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002219 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2220
2221 return Status::ok();
2222}
2223
Emilian Peev8b64f282021-03-25 16:49:57 -07002224Status CameraService::notifyDisplayConfigurationChange() {
2225 ATRACE_CALL();
2226 const int callingPid = CameraThreadState::getCallingPid();
2227 const int selfPid = getpid();
2228
2229 // Permission checks
2230 if (callingPid != selfPid) {
2231 // Ensure we're being called by system_server, or similar process with
2232 // permissions to notify the camera service about system events
2233 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2234 const int uid = CameraThreadState::getCallingUid();
2235 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2236 " changes from pid=%d, uid=%d", callingPid, uid);
2237 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2238 "No permission to send updates to camera service about orientation"
2239 " changes from pid=%d, uid=%d", callingPid, uid);
2240 }
2241 }
2242
2243 Mutex::Autolock lock(mServiceLock);
2244
2245 // Don't do anything if rotate-and-crop override via cmd is active
2246 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2247
2248 const auto clients = mActiveClientManager.getAll();
2249 for (auto& current : clients) {
2250 if (current != nullptr) {
2251 const auto basicClient = current->getValue();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002252 if (basicClient.get() != nullptr && basicClient->canCastToApiClient(API_2)) {
Emilian Peev5368ebf2021-10-08 17:52:18 -07002253 basicClient->setRotateAndCropOverride(
2254 CameraServiceProxyWrapper::getRotateAndCropOverride(
2255 basicClient->getPackageName(), basicClient->getCameraFacing()));
Emilian Peev8b64f282021-03-25 16:49:57 -07002256 }
2257 }
2258 }
2259
2260 return Status::ok();
2261}
2262
2263Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002264 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2265 ATRACE_CALL();
2266 if (!concurrentCameraIds) {
2267 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2268 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2269 }
2270
2271 if (!mInitialized) {
2272 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002273 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002274 return STATUS_ERROR(ERROR_DISCONNECTED,
2275 "Camera subsystem is not available");
2276 }
2277 // First call into the provider and get the set of concurrent camera
2278 // combinations
2279 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002280 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002281 for (auto &combination : concurrentCameraCombinations) {
2282 std::vector<std::string> validCombination;
2283 for (auto &cameraId : combination) {
2284 // if the camera state is not present, skip
2285 String8 cameraIdStr(cameraId.c_str());
2286 auto state = getCameraState(cameraIdStr);
2287 if (state == nullptr) {
2288 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2289 continue;
2290 }
2291 StatusInternal status = state->getStatus();
2292 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2293 continue;
2294 }
2295 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2296 continue;
2297 }
2298 validCombination.push_back(cameraId);
2299 }
2300 if (validCombination.size() != 0) {
2301 concurrentCameraIds->push_back(std::move(validCombination));
2302 }
2303 }
2304 return Status::ok();
2305}
2306
2307Status CameraService::isConcurrentSessionConfigurationSupported(
2308 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002309 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002310 if (!isSupported) {
2311 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2312 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2313 }
2314
2315 if (!mInitialized) {
2316 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2317 return STATUS_ERROR(ERROR_DISCONNECTED,
2318 "Camera subsystem is not available");
2319 }
2320
2321 // Check for camera permissions
2322 int callingPid = CameraThreadState::getCallingPid();
2323 int callingUid = CameraThreadState::getCallingUid();
2324 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2325 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2326 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2327 "android.permission.CAMERA needed to call"
2328 "isConcurrentSessionConfigurationSupported");
2329 }
2330
2331 status_t res =
2332 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002333 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
2334 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002335 if (res != OK) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07002336 logServiceError(String8::format("Unable to query session configuration support"),
2337 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002338 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2339 "support %s (%d)", strerror(-res), res);
2340 }
2341 return Status::ok();
2342}
2343
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002344Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2345 /*out*/
2346 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002347 return addListenerHelper(listener, cameraStatuses);
2348}
2349
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002350binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2351 std::vector<hardware::CameraStatus>* cameraStatuses) {
2352 return addListenerHelper(listener, cameraStatuses, false, true);
2353}
2354
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002355Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2356 /*out*/
2357 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002358 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002359
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002360 ATRACE_CALL();
2361
Igor Murashkinbfc99152013-02-27 12:55:20 -08002362 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002363
Ruben Brunk3450ba72015-06-16 11:00:37 -07002364 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002365 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002366 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002367 }
2368
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002369 auto clientUid = CameraThreadState::getCallingUid();
2370 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002371 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
Jayant Chowdharyc3198c32021-07-28 20:59:14 +00002372 clientPid, clientUid, /*logPermissionFailure*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002373
Igor Murashkinbfc99152013-02-27 12:55:20 -08002374 Mutex::Autolock lock(mServiceLock);
2375
Ruben Brunkcc776712015-02-17 20:18:47 -08002376 {
2377 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002378 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002379 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002380 ALOGW("%s: Tried to add listener %p which was already subscribed",
2381 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002382 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002383 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002384 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002385
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002386 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002387 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2388 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002389 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08002390 if (ret != NO_ERROR) {
2391 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2392 strerror(-ret), ret);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002393 logServiceError(msg,ERROR_ILLEGAL_ARGUMENT);
Emilian Peev53722fa2019-02-22 17:47:20 -08002394 ALOGE("%s: %s", __FUNCTION__, msg.string());
2395 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2396 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002397 // The listener still needs to be added to the list of listeners, regardless of what
2398 // permissions the listener process has / whether it is a vendor listener. Since it might be
2399 // eligible to listen to other camera ids.
2400 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002401 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002402 }
2403
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002404 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002405 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002406 Mutex::Autolock lock(mCameraStatesLock);
2407 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002408 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07002409 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
2410 openCloseCallbackAllowed ? i.second->getClientPackage() : String8::empty());
Igor Murashkincba2c162013-03-20 15:56:31 -07002411 }
2412 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002413 // Remove the camera statuses that should be hidden from the client, we do
2414 // this after collecting the states in order to avoid holding
2415 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2416 // the same time.
2417 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2418 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2419 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2420 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2421 ALOGE("%s: Invalid camera id %s, skipping status update",
2422 __FUNCTION__, s.cameraId.c_str());
2423 return true;
2424 }
2425 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2426 clientUid);}), cameraStatuses->end());
2427
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002428 //cameraStatuses will have non-eligible camera ids removed.
2429 std::set<String16> idsChosenForCallback;
2430 for (const auto &s : *cameraStatuses) {
2431 idsChosenForCallback.insert(String16(s.cameraId));
2432 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002433
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002434 /*
2435 * Immediately signal current torch status to this listener only
2436 * This may be a subset of all the devices, so don't include it in the response directly
2437 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002438 {
2439 Mutex::Autolock al(mTorchStatusMutex);
2440 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002441 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002442 // The camera id is visible to the client. Fine to send torch
2443 // callback.
2444 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2445 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2446 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002447 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002448 }
2449
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002450 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002451}
Ruben Brunkcc776712015-02-17 20:18:47 -08002452
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002453Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002454 ATRACE_CALL();
2455
Igor Murashkinbfc99152013-02-27 12:55:20 -08002456 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2457
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002458 if (listener == 0) {
2459 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002460 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002461 }
2462
Igor Murashkinbfc99152013-02-27 12:55:20 -08002463 Mutex::Autolock lock(mServiceLock);
2464
Ruben Brunkcc776712015-02-17 20:18:47 -08002465 {
2466 Mutex::Autolock lock(mStatusListenerLock);
2467 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002468 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2469 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2470 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002471 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002472 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002473 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002474 }
2475 }
2476
2477 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2478 __FUNCTION__, listener.get());
2479
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002480 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002481}
2482
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002483Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002484
2485 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002486 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2487
2488 if (parameters == NULL) {
2489 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002490 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002491 }
2492
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002493 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002494
2495 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002496 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002497 // Error logged by caller
2498 return ret;
2499 }
2500
2501 String8 shimParamsString8 = shimParams.flatten();
2502 String16 shimParamsString16 = String16(shimParamsString8);
2503
2504 *parameters = shimParamsString16;
2505
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002506 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002507}
2508
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002509Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2510 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002511 ATRACE_CALL();
2512
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002513 const String8 id = String8(cameraId);
2514
2515 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002516
2517 switch (apiVersion) {
2518 case API_VERSION_1:
2519 case API_VERSION_2:
2520 break;
2521 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002522 String8 msg = String8::format("Unknown API version %d", apiVersion);
2523 ALOGE("%s: %s", __FUNCTION__, msg.string());
2524 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002525 }
2526
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002527 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002528 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002529 case CAMERA_DEVICE_API_VERSION_1_0:
2530 case CAMERA_DEVICE_API_VERSION_3_0:
2531 case CAMERA_DEVICE_API_VERSION_3_1:
2532 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002533 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2534 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002535 *isSupported = false;
2536 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002537 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2538 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002539 *isSupported = true;
2540 }
2541 break;
2542 case CAMERA_DEVICE_API_VERSION_3_2:
2543 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002544 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002545 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002546 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -08002547 case CAMERA_DEVICE_API_VERSION_3_7:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002548 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2549 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002550 *isSupported = true;
2551 break;
2552 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002553 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002554 ALOGE("%s: %s", __FUNCTION__, msg.string());
2555 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002556 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002557 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002558 String8 msg = String8::format("Unknown device version %x for device %s",
2559 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002560 ALOGE("%s: %s", __FUNCTION__, msg.string());
2561 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2562 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002563 }
2564
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002565 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002566}
2567
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002568Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2569 /*out*/ bool *isSupported) {
2570 ATRACE_CALL();
2571
2572 const String8 id = String8(cameraId);
2573
2574 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2575 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2576
2577 return Status::ok();
2578}
2579
Cliff Wud8cae102021-03-11 01:37:42 +08002580Status CameraService::injectCamera(
2581 const String16& packageName, const String16& internalCamId,
2582 const String16& externalCamId,
2583 const sp<ICameraInjectionCallback>& callback,
2584 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08002585 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08002586 ATRACE_CALL();
2587
2588 if (!checkCallingPermission(sCameraInjectExternalCameraPermission)) {
2589 const int pid = CameraThreadState::getCallingPid();
2590 const int uid = CameraThreadState::getCallingUid();
2591 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
2592 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2593 "Permission Denial: no permission to inject camera");
2594 }
2595
2596 ALOGV(
2597 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
2598 "%s",
2599 __FUNCTION__, String8(packageName).string(),
2600 String8(internalCamId).string(), String8(externalCamId).string());
2601
Cliff Wud3a05312021-04-26 23:07:31 +08002602 {
2603 Mutex::Autolock lock(mInjectionParametersLock);
2604 mInjectionInternalCamId = String8(internalCamId);
2605 mInjectionExternalCamId = String8(externalCamId);
2606 status_t res = NO_ERROR;
2607 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2608 // If the client already exists, we can directly connect to the camera device through the
2609 // client's injectCamera(), otherwise we need to wait until the client is established
2610 // (execute connectHelper()) before injecting the camera to the camera device.
2611 if (clientDescriptor != nullptr) {
2612 mInjectionInitPending = false;
2613 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
2614 res = baseClientPtr->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
2615 if(res != OK) {
2616 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2617 }
2618 } else {
2619 mInjectionInitPending = true;
2620 }
2621 }
Cliff Wud8cae102021-03-11 01:37:42 +08002622 mInjectionStatusListener->addListener(callback);
2623 *cameraInjectionSession = new CameraInjectionSession(this);
2624
Cliff Wud3a05312021-04-26 23:07:31 +08002625 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08002626}
2627
Ruben Brunkcc776712015-02-17 20:18:47 -08002628void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002629 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002630 for (auto& i : mActiveClientManager.getAll()) {
2631 auto clientSp = i->getValue();
2632 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002633 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08002634 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002635 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002636 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002637 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002638}
2639
Ruben Brunkcc776712015-02-17 20:18:47 -08002640bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002641 bool ret = false;
2642 {
2643 // Acquire mServiceLock and prevent other clients from connecting
2644 std::unique_ptr<AutoConditionLock> lock =
2645 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002646
Igor Murashkin634a5152013-02-20 17:15:11 -08002647
Ruben Brunkcc776712015-02-17 20:18:47 -08002648 std::vector<sp<BasicClient>> evicted;
2649 for (auto& i : mActiveClientManager.getAll()) {
2650 auto clientSp = i->getValue();
2651 if (clientSp.get() == nullptr) {
2652 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2653 mActiveClientManager.remove(i);
2654 continue;
2655 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002656 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002657 mActiveClientManager.remove(i);
2658 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002659
Ruben Brunkcc776712015-02-17 20:18:47 -08002660 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002661 clientSp->notifyError(
2662 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002663 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002664 }
2665 }
2666
Ruben Brunkcc776712015-02-17 20:18:47 -08002667 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2668 // other clients from connecting in mServiceLockWrapper if held
2669 mServiceLock.unlock();
2670
Ruben Brunk36597b22015-03-20 22:15:57 -07002671 // Do not clear caller identity, remote caller should be client proccess
2672
Ruben Brunkcc776712015-02-17 20:18:47 -08002673 for (auto& i : evicted) {
2674 if (i.get() != nullptr) {
2675 i->disconnect();
2676 ret = true;
2677 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002678 }
2679
Ruben Brunkcc776712015-02-17 20:18:47 -08002680 // Reacquire mServiceLock
2681 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002682
Ruben Brunkcc776712015-02-17 20:18:47 -08002683 } // lock is destroyed, allow further connect calls
2684
2685 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002686}
2687
Ruben Brunkcc776712015-02-17 20:18:47 -08002688std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2689 const String8& cameraId) const {
2690 std::shared_ptr<CameraState> state;
2691 {
2692 Mutex::Autolock lock(mCameraStatesLock);
2693 auto iter = mCameraStates.find(cameraId);
2694 if (iter != mCameraStates.end()) {
2695 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002696 }
2697 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002698 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002699}
2700
Ruben Brunkcc776712015-02-17 20:18:47 -08002701sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2702 // Remove from active clients list
2703 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2704 if (clientDescriptorPtr == nullptr) {
2705 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2706 cameraId.string());
2707 return sp<BasicClient>{nullptr};
2708 }
2709
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002710 sp<BasicClient> client = clientDescriptorPtr->getValue();
2711 if (client.get() != nullptr) {
2712 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
2713 }
2714 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07002715}
2716
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002717void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002718 // Acquire mServiceLock and prevent other clients from connecting
2719 std::unique_ptr<AutoConditionLock> lock =
2720 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2721
Ruben Brunk6267b532015-04-30 17:44:07 -07002722 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002723 for (size_t i = 0; i < newUserIds.size(); i++) {
2724 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002725 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002726 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002727 return;
2728 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002729 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002730 }
2731
Ruben Brunka8ca9152015-04-07 14:23:40 -07002732
Ruben Brunk6267b532015-04-30 17:44:07 -07002733 if (newAllowedUsers == mAllowedUsers) {
2734 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2735 return;
2736 }
2737
2738 logUserSwitch(mAllowedUsers, newAllowedUsers);
2739
2740 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002741
2742 // Current user has switched, evict all current clients.
2743 std::vector<sp<BasicClient>> evicted;
2744 for (auto& i : mActiveClientManager.getAll()) {
2745 auto clientSp = i->getValue();
2746
2747 if (clientSp.get() == nullptr) {
2748 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2749 continue;
2750 }
2751
Ruben Brunk6267b532015-04-30 17:44:07 -07002752 // Don't evict clients that are still allowed.
2753 uid_t clientUid = clientSp->getClientUid();
2754 userid_t clientUserId = multiuser_get_user_id(clientUid);
2755 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2756 continue;
2757 }
2758
Ruben Brunk36597b22015-03-20 22:15:57 -07002759 evicted.push_back(clientSp);
2760
2761 String8 curTime = getFormattedCurrentTime();
2762
2763 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2764 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002765
Ruben Brunk36597b22015-03-20 22:15:57 -07002766 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002767 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002768 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2769 " to user switch.", i->getKey().string(),
2770 String8{clientSp->getPackageName()}.string(),
2771 i->getOwnerId(), i->getPriority().getScore(),
2772 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002773
2774 }
2775
2776 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2777 // blocking other clients from connecting in mServiceLockWrapper if held.
2778 mServiceLock.unlock();
2779
2780 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002781 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002782
2783 for (auto& i : evicted) {
2784 i->disconnect();
2785 }
2786
Jayant Chowdhary12361932018-08-27 14:46:13 -07002787 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002788
2789 // Reacquire mServiceLock
2790 mServiceLock.lock();
2791}
Ruben Brunkcc776712015-02-17 20:18:47 -08002792
Ruben Brunka8ca9152015-04-07 14:23:40 -07002793void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002794 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002795 Mutex::Autolock l(mLogLock);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002796 String8 msg = String8::format("%s : %s", curTime.string(), event);
2797 // For service error events, print the msg only once.
2798 if(!msg.contains("SERVICE ERROR")) {
2799 mEventLog.add(msg);
2800 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
2801 // Error event not added to the dumpsys log before
2802 mEventLog.add(msg);
2803 sServiceErrorEventSet.insert(msg);
2804 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002805}
2806
Ruben Brunka8ca9152015-04-07 14:23:40 -07002807void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002808 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002809 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002810 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002811 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002812}
2813
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002814void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2815 const char* clientPackage) {
2816 // Log the clients evicted
2817 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2818 cameraId, clientPackage, clientPid));
2819}
2820
Ruben Brunka8ca9152015-04-07 14:23:40 -07002821void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002822 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002823 // Log the clients evicted
2824 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002825 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002826}
2827
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002828void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2829 const char* clientPackage) {
2830 // Log the clients evicted
2831 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2832 clientPackage, clientPid));
2833}
2834
Ruben Brunka8ca9152015-04-07 14:23:40 -07002835void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002836 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002837 // Log the client rejected
2838 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002839 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002840}
2841
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002842void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2843 // Log torch event
2844 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2845 torchState, clientPid));
2846}
2847
Ruben Brunk6267b532015-04-30 17:44:07 -07002848void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2849 const std::set<userid_t>& newUserIds) {
2850 String8 newUsers = toString(newUserIds);
2851 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002852 if (oldUsers.size() == 0) {
2853 oldUsers = "<None>";
2854 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002855 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002856 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002857 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002858}
2859
2860void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2861 // Log the device removal
2862 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2863}
2864
2865void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2866 // Log the device removal
2867 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2868}
2869
2870void CameraService::logClientDied(int clientPid, const char* reason) {
2871 // Log the device removal
2872 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002873}
2874
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002875void CameraService::logServiceError(const char* msg, int errorCode) {
2876 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002877 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002878}
2879
Ruben Brunk36597b22015-03-20 22:15:57 -07002880status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2881 uint32_t flags) {
2882
Mathias Agopian65ab4712010-07-14 17:59:35 -07002883 // Permission checks
2884 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002885 case SHELL_COMMAND_TRANSACTION: {
2886 int in = data.readFileDescriptor();
2887 int out = data.readFileDescriptor();
2888 int err = data.readFileDescriptor();
2889 int argc = data.readInt32();
2890 Vector<String16> args;
2891 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2892 args.add(data.readString16());
2893 }
2894 sp<IBinder> unusedCallback;
2895 sp<IResultReceiver> resultReceiver;
2896 status_t status;
2897 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2898 return status;
2899 }
2900 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2901 return status;
2902 }
2903 status = shellCommand(in, out, err, args);
2904 if (resultReceiver != nullptr) {
2905 resultReceiver->send(status);
2906 }
2907 return NO_ERROR;
2908 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002909 }
2910
2911 return BnCameraService::onTransact(code, data, reply, flags);
2912}
2913
Mathias Agopian65ab4712010-07-14 17:59:35 -07002914// We share the media players for shutter and recording sound for all clients.
2915// A reference count is kept to determine when we will actually release the
2916// media players.
2917
Jaekyun Seokef498052018-03-23 13:09:44 +09002918sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2919 sp<MediaPlayer> mp = new MediaPlayer();
2920 status_t error;
2921 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002922 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002923 error = mp->prepare();
2924 }
2925 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002926 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002927 mp->disconnect();
2928 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002929 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002930 }
2931 return mp;
2932}
2933
username5755fea2018-12-27 09:48:08 +08002934void CameraService::increaseSoundRef() {
2935 Mutex::Autolock lock(mSoundLock);
2936 mSoundRef++;
2937}
2938
2939void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002940 ATRACE_CALL();
2941
username5755fea2018-12-27 09:48:08 +08002942 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2943 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2944 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2945 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2946 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2947 }
2948 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2949 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2950 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2951 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002952 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002953 }
2954 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2955 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2956 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2957 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2958 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002959 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002960}
2961
username5755fea2018-12-27 09:48:08 +08002962void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002963 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002964 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002965 if (--mSoundRef) return;
2966
2967 for (int i = 0; i < NUM_SOUNDS; i++) {
2968 if (mSoundPlayer[i] != 0) {
2969 mSoundPlayer[i]->disconnect();
2970 mSoundPlayer[i].clear();
2971 }
2972 }
2973}
2974
2975void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002976 ATRACE_CALL();
2977
Mathias Agopian65ab4712010-07-14 17:59:35 -07002978 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07002979 if (kind < 0 || kind >= NUM_SOUNDS) {
2980 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
2981 return;
2982 }
2983
Mathias Agopian65ab4712010-07-14 17:59:35 -07002984 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002985 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002986 sp<MediaPlayer> player = mSoundPlayer[kind];
2987 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002988 player->seekTo(0);
2989 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002990 }
2991}
2992
2993// ----------------------------------------------------------------------------
2994
2995CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002996 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002997 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09002998 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002999 const String8& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003000 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003001 int clientPid, uid_t clientUid,
3002 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003003 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003004 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003005 clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003006 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003007 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003008 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003009 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003010{
Jayant Chowdhary12361932018-08-27 14:46:13 -07003011 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003012 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003013
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003014 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003015
username5755fea2018-12-27 09:48:08 +08003016 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003017
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003018 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003019}
3020
Mathias Agopian65ab4712010-07-14 17:59:35 -07003021// tear down the client
3022CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003023 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08003024 mDestructionStarted = true;
3025
username5755fea2018-12-27 09:48:08 +08003026 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003027 // unconditionally disconnect. function is idempotent
3028 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003029}
3030
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003031sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
3032
Igor Murashkin634a5152013-02-20 17:15:11 -08003033CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003034 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003035 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003036 const String8& cameraIdStr, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003037 int clientPid, uid_t clientUid,
3038 int servicePid):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003039 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07003040 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003041 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003042 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003043 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07003044 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003045 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003046 mRemoteBinder(remoteCallback),
3047 mOpsActive(false),
3048 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08003049{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003050 if (sCameraService == nullptr) {
3051 sCameraService = cameraService;
3052 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08003053
3054 // In some cases the calling code has no access to the package it runs under.
3055 // For example, NDK camera API.
3056 // In this case we will get the packages for the calling UID and pick the first one
3057 // for attributing the app op. This will work correctly for runtime permissions
3058 // as for legacy apps we will toggle the app op for all packages in the UID.
3059 // The caveat is that the operation may be attributed to the wrong package and
3060 // stats based on app ops may be slightly off.
3061 if (mClientPackageName.size() <= 0) {
3062 sp<IServiceManager> sm = defaultServiceManager();
3063 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
3064 if (binder == 0) {
3065 ALOGE("Cannot get permission service");
3066 // Leave mClientPackageName unchanged (empty) and the further interaction
3067 // with camera will fail in BasicClient::startCameraOps
3068 return;
3069 }
3070
3071 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
3072 Vector<String16> packages;
3073
3074 permCtrl->getPackagesForUid(mClientUid, packages);
3075
3076 if (packages.isEmpty()) {
3077 ALOGE("No packages for calling UID");
3078 // Leave mClientPackageName unchanged (empty) and the further interaction
3079 // with camera will fail in BasicClient::startCameraOps
3080 return;
3081 }
3082 mClientPackageName = packages[0];
3083 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003084 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003085 mAppOpsManager = std::make_unique<AppOpsManager>();
3086 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07003087
3088 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08003089}
3090
3091CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003092 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08003093 mDestructionStarted = true;
3094}
3095
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003096binder::Status CameraService::BasicClient::disconnect() {
3097 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003098 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003099 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07003100 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07003101 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08003102
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003103 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003104 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07003105 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
3106 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003107
3108 sp<IBinder> remote = getRemote();
3109 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003110 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08003111 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003112
3113 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07003114 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003115 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
3116 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
3117 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003118
Igor Murashkincba2c162013-03-20 15:56:31 -07003119 // client shouldn't be able to call into us anymore
3120 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003121
3122 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08003123}
3124
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003125status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
3126 // No dumping of clients directly over Binder,
3127 // must go through CameraService::dump
3128 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003129 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003130 return OK;
3131}
3132
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07003133status_t CameraService::BasicClient::startWatchingTags(const String8&, int) {
3134 // Can't watch tags directly, must go through CameraService::startWatchingTags
3135 return OK;
3136}
3137
3138status_t CameraService::BasicClient::stopWatchingTags(int) {
3139 // Can't watch tags directly, must go through CameraService::stopWatchingTags
3140 return OK;
3141}
3142
3143status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
3144 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
3145 return OK;
3146}
3147
Ruben Brunkcc776712015-02-17 20:18:47 -08003148String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003149 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08003150}
3151
Emilian Peev8b64f282021-03-25 16:49:57 -07003152int CameraService::BasicClient::getCameraFacing() const {
3153 return mCameraFacing;
3154}
3155
3156int CameraService::BasicClient::getCameraOrientation() const {
3157 return mOrientation;
3158}
Ruben Brunkcc776712015-02-17 20:18:47 -08003159
3160int CameraService::BasicClient::getClientPid() const {
3161 return mClientPid;
3162}
3163
Ruben Brunk6267b532015-04-30 17:44:07 -07003164uid_t CameraService::BasicClient::getClientUid() const {
3165 return mClientUid;
3166}
3167
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003168bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
3169 // Defaults to API2.
3170 return level == API_2;
3171}
3172
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003173status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003174 {
3175 Mutex::Autolock l(mAudioRestrictionLock);
3176 mAudioRestriction = mode;
3177 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003178 sCameraService->updateAudioRestriction();
3179 return OK;
3180}
3181
3182int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003183 return sCameraService->updateAudioRestriction();
3184}
3185
3186int32_t CameraService::BasicClient::getAudioRestriction() const {
3187 Mutex::Autolock l(mAudioRestrictionLock);
3188 return mAudioRestriction;
3189}
3190
3191bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
3192 switch (mode) {
3193 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
3194 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
3195 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
3196 return true;
3197 default:
3198 return false;
3199 }
3200}
3201
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003202status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
3203 if (mode == AppOpsManager::MODE_ERRORED) {
3204 ALOGI("Camera %s: Access for \"%s\" has been revoked",
3205 mCameraIdStr.string(), String8(mClientPackageName).string());
3206 return PERMISSION_DENIED;
3207 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
3208 // If the calling Uid is trusted (a native service), the AppOpsManager could
3209 // return MODE_IGNORED. Do not treat such case as error.
3210 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
3211 mClientPackageName);
3212 bool isCameraPrivacyEnabled =
3213 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3214 multiuser_get_user_id(mClientUid));
3215 if (!isUidActive || !isCameraPrivacyEnabled) {
3216 ALOGI("Camera %s: Access for \"%s\" has been restricted",
3217 mCameraIdStr.string(), String8(mClientPackageName).string());
3218 // Return the same error as for device policy manager rejection
3219 return -EACCES;
3220 }
3221 }
3222 return OK;
3223}
3224
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003225status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003226 ATRACE_CALL();
3227
Igor Murashkine6800ce2013-03-04 17:25:57 -08003228 {
3229 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003230 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003231 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003232 if (mAppOpsManager != nullptr) {
3233 // Notify app ops that the camera is not available
3234 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003235 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
3236 mClientPackageName, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003237
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003238 // Just check for camera acccess here on open - delay startOp until
3239 // camera frames start streaming in startCameraStreamingOps
3240 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
3241 mClientPackageName);
3242 status_t res = handleAppOpMode(mode);
3243 if (res != OK) {
3244 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003245 }
Svetoslav28e8ef72015-05-11 19:21:31 -07003246 }
3247
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003248 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003249
3250 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003251 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003252
Emilian Peev53722fa2019-02-22 17:47:20 -08003253 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
3254
Shuzhen Wang695044d2020-03-06 09:02:23 -08003255 // Notify listeners of camera open/close status
3256 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
3257
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003258 return OK;
3259}
3260
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003261status_t CameraService::BasicClient::startCameraStreamingOps() {
3262 ATRACE_CALL();
3263
3264 if (!mOpsActive) {
3265 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3266 return INVALID_OPERATION;
3267 }
3268 if (mOpsStreaming) {
3269 ALOGV("%s: Streaming already active!", __FUNCTION__);
3270 return OK;
3271 }
3272
3273 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
3274 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3275
3276 if (mAppOpsManager != nullptr) {
3277 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
3278 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
3279 String16("start camera ") + String16(mCameraIdStr));
3280 status_t res = handleAppOpMode(mode);
3281 if (res != OK) {
3282 return res;
3283 }
3284 }
3285
3286 mOpsStreaming = true;
3287
3288 return OK;
3289}
3290
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003291status_t CameraService::BasicClient::noteAppOp() {
3292 ATRACE_CALL();
3293
3294 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
3295 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3296
3297 // noteAppOp is only used for when camera mute is not supported, in order
3298 // to trigger the sensor privacy "Unblock" dialog
3299 if (mAppOpsManager != nullptr) {
3300 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
3301 mClientPackageName, mClientFeatureId,
3302 String16("start camera ") + String16(mCameraIdStr));
3303 status_t res = handleAppOpMode(mode);
3304 if (res != OK) {
3305 return res;
3306 }
3307 }
3308
3309 return OK;
3310}
3311
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003312status_t CameraService::BasicClient::finishCameraStreamingOps() {
3313 ATRACE_CALL();
3314
3315 if (!mOpsActive) {
3316 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3317 return INVALID_OPERATION;
3318 }
3319 if (!mOpsStreaming) {
3320 ALOGV("%s: Streaming not active!", __FUNCTION__);
3321 return OK;
3322 }
3323
3324 if (mAppOpsManager != nullptr) {
3325 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
3326 mClientPackageName, mClientFeatureId);
3327 mOpsStreaming = false;
3328 }
3329
3330 return OK;
3331}
3332
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003333status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003334 ATRACE_CALL();
3335
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003336 if (mOpsStreaming) {
3337 // Make sure we've notified everyone about camera stopping
3338 finishCameraStreamingOps();
3339 }
3340
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003341 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003342 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003343 mOpsActive = false;
3344
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003345 // This function is called when a client disconnects. This should
3346 // release the camera, but actually only if it was in a proper
3347 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003348 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003349 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003350
Ruben Brunkcc776712015-02-17 20:18:47 -08003351 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003352 sCameraService->updateStatus(StatusInternal::PRESENT,
3353 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003354 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003355 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003356 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3357 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003358 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003359 mOpsCallback.clear();
3360
Emilian Peev53722fa2019-02-22 17:47:20 -08003361 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3362
Shuzhen Wang695044d2020-03-06 09:02:23 -08003363 // Notify listeners of camera open/close status
3364 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3365
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003366 return OK;
3367}
3368
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003369void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003370 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003371 if (mAppOpsManager == nullptr) {
3372 return;
3373 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003374 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003375 if (op != AppOpsManager::OP_CAMERA) {
3376 ALOGW("Unexpected app ops notification received: %d", op);
3377 return;
3378 }
3379
3380 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003381 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003382 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003383 ALOGV("checkOp returns: %d, %s ", res,
3384 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3385 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3386 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3387 "UNKNOWN");
3388
Shuzhen Wang64900852021-02-05 09:03:29 -08003389 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003390 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003391 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003392 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003393 } else if (res == AppOpsManager::MODE_IGNORED) {
3394 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08003395 bool isCameraPrivacyEnabled =
3396 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3397 multiuser_get_user_id(mClientUid));
Shuzhen Wang64900852021-02-05 09:03:29 -08003398 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3399 mCameraIdStr.string(), String8(mClientPackageName).string(),
3400 mUidIsTrusted, isUidActive);
3401 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3402 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3403 // error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003404 if (!mUidIsTrusted) {
3405 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
3406 setCameraMute(true);
3407 } else if (!isUidActive
3408 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
3409 block();
3410 }
Shuzhen Wang64900852021-02-05 09:03:29 -08003411 }
Evan Severson09ab4002021-02-10 14:15:19 -08003412 } else if (res == AppOpsManager::MODE_ALLOWED) {
3413 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003414 }
3415}
3416
Svet Ganova453d0d2018-01-11 15:37:58 -08003417void CameraService::BasicClient::block() {
3418 ATRACE_CALL();
3419
3420 // Reset the client PID to allow server-initiated disconnect,
3421 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003422 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003423 CaptureResultExtras resultExtras; // a dummy result (invalid)
3424 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3425 disconnect();
3426}
3427
Mathias Agopian65ab4712010-07-14 17:59:35 -07003428// ----------------------------------------------------------------------------
3429
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003430void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003431 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003432 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003433 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003434 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3435 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3436 api1ErrorCode = CAMERA_ERROR_DISABLED;
3437 }
3438 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003439 } else {
3440 ALOGE("mRemoteCallback is NULL!!");
3441 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003442}
3443
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003444// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003445binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003446 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003447 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003448}
3449
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003450bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3451 return level == API_1;
3452}
3453
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003454CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3455 mClient(client) {
3456}
3457
3458void CameraService::Client::OpsCallback::opChanged(int32_t op,
3459 const String16& packageName) {
3460 sp<BasicClient> client = mClient.promote();
3461 if (client != NULL) {
3462 client->opChanged(op, packageName);
3463 }
3464}
3465
Mathias Agopian65ab4712010-07-14 17:59:35 -07003466// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003467// UidPolicy
3468// ----------------------------------------------------------------------------
3469
3470void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003471 Mutex::Autolock _l(mUidLock);
3472
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003473 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003474 status_t res = mAm.linkToDeath(this);
3475 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003476 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003477 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003478 ActivityManager::PROCESS_STATE_UNKNOWN,
3479 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003480 if (res == OK) {
3481 mRegistered = true;
3482 ALOGV("UidPolicy: Registered with ActivityManager");
3483 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003484}
3485
3486void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003487 Mutex::Autolock _l(mUidLock);
3488
Steven Moreland2f348142019-07-02 15:59:07 -07003489 mAm.unregisterUidObserver(this);
3490 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003491 mRegistered = false;
3492 mActiveUids.clear();
3493 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003494}
3495
3496void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3497 onUidIdle(uid, disabled);
3498}
3499
3500void CameraService::UidPolicy::onUidActive(uid_t uid) {
3501 Mutex::Autolock _l(mUidLock);
3502 mActiveUids.insert(uid);
3503}
3504
3505void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3506 bool deleted = false;
3507 {
3508 Mutex::Autolock _l(mUidLock);
3509 if (mActiveUids.erase(uid) > 0) {
3510 deleted = true;
3511 }
3512 }
3513 if (deleted) {
3514 sp<CameraService> service = mService.promote();
3515 if (service != nullptr) {
3516 service->blockClientsForUid(uid);
3517 }
3518 }
3519}
3520
Emilian Peev53722fa2019-02-22 17:47:20 -08003521void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003522 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003523 bool procStateChange = false;
3524 {
3525 Mutex::Autolock _l(mUidLock);
3526 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3527 (mMonitoredUids[uid].first != procState)) {
3528 mMonitoredUids[uid].first = procState;
3529 procStateChange = true;
3530 }
3531 }
3532
3533 if (procStateChange) {
3534 sp<CameraService> service = mService.promote();
3535 if (service != nullptr) {
3536 service->notifyMonitoredUids();
3537 }
3538 }
3539}
3540
3541void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3542 Mutex::Autolock _l(mUidLock);
3543 auto it = mMonitoredUids.find(uid);
3544 if (it != mMonitoredUids.end()) {
3545 it->second.second++;
3546 } else {
3547 mMonitoredUids.emplace(
3548 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3549 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3550 }
3551}
3552
3553void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3554 Mutex::Autolock _l(mUidLock);
3555 auto it = mMonitoredUids.find(uid);
3556 if (it != mMonitoredUids.end()) {
3557 it->second.second--;
3558 if (it->second.second == 0) {
3559 mMonitoredUids.erase(it);
3560 }
3561 } else {
3562 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3563 }
3564}
3565
Svet Ganov7b4ab782018-03-25 12:48:10 -07003566bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003567 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003568 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003569}
3570
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003571static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3572static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003573
Svet Ganov7b4ab782018-03-25 12:48:10 -07003574bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003575 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003576 // If activity manager is unreachable, assume everything is active
3577 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003578 return true;
3579 }
3580 auto it = mOverrideUids.find(uid);
3581 if (it != mOverrideUids.end()) {
3582 return it->second;
3583 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003584 bool active = mActiveUids.find(uid) != mActiveUids.end();
3585 if (!active) {
3586 // We want active UIDs to always access camera with their first attempt since
3587 // there is no guarantee the app is robustly written and would retry getting
3588 // the camera on failure. The inverse case is not a problem as we would take
3589 // camera away soon once we get the callback that the uid is no longer active.
3590 ActivityManager am;
3591 // Okay to access with a lock held as UID changes are dispatched without
3592 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003593 int64_t startTimeMillis = 0;
3594 do {
3595 // TODO: Fix this b/109950150!
3596 // Okay this is a hack. There is a race between the UID turning active and
3597 // activity being resumed. The proper fix is very risky, so we temporary add
3598 // some polling which should happen pretty rarely anyway as the race is hard
3599 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003600 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003601 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003602 if (active) {
3603 break;
3604 }
3605 if (startTimeMillis <= 0) {
3606 startTimeMillis = uptimeMillis();
3607 }
3608 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003609 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003610 if (remainingTimeMillis <= 0) {
3611 break;
3612 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003613 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3614
3615 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003616 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003617 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003618 } while (true);
3619
Svet Ganov7b4ab782018-03-25 12:48:10 -07003620 if (active) {
3621 // Now that we found out the UID is actually active, cache that
3622 mActiveUids.insert(uid);
3623 }
3624 }
3625 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003626}
3627
Varun Shahb42f1eb2019-04-16 14:45:13 -07003628int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3629 Mutex::Autolock _l(mUidLock);
3630 return getProcStateLocked(uid);
3631}
3632
3633int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3634 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3635 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3636 procState = mMonitoredUids[uid].first;
3637 }
3638 return procState;
3639}
3640
Svet Ganov7b4ab782018-03-25 12:48:10 -07003641void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3642 String16 callingPackage, bool active) {
3643 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003644}
3645
Svet Ganov7b4ab782018-03-25 12:48:10 -07003646void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3647 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003648}
3649
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003650void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3651 Mutex::Autolock _l(mUidLock);
3652 ALOGV("UidPolicy: ActivityManager has died");
3653 mRegistered = false;
3654 mActiveUids.clear();
3655}
3656
Svet Ganov7b4ab782018-03-25 12:48:10 -07003657void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3658 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003659 bool wasActive = false;
3660 bool isActive = false;
3661 {
3662 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003663 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003664 mOverrideUids.erase(uid);
3665 if (insert) {
3666 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3667 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003668 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003669 }
3670 if (wasActive != isActive && !isActive) {
3671 sp<CameraService> service = mService.promote();
3672 if (service != nullptr) {
3673 service->blockClientsForUid(uid);
3674 }
3675 }
3676}
3677
3678// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003679// SensorPrivacyPolicy
3680// ----------------------------------------------------------------------------
3681void CameraService::SensorPrivacyPolicy::registerSelf() {
3682 Mutex::Autolock _l(mSensorPrivacyLock);
3683 if (mRegistered) {
3684 return;
3685 }
Evan Severson09ab4002021-02-10 14:15:19 -08003686 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08003687 mSpm.addSensorPrivacyListener(this);
3688 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3689 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003690 if (res == OK) {
3691 mRegistered = true;
3692 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3693 }
3694}
3695
3696void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3697 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003698 mSpm.removeSensorPrivacyListener(this);
3699 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003700 mRegistered = false;
3701 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3702}
3703
3704bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3705 Mutex::Autolock _l(mSensorPrivacyLock);
3706 return mSensorPrivacyEnabled;
3707}
3708
Evan Severson09ab4002021-02-10 14:15:19 -08003709bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(userid_t userId) {
3710 if (!hasCameraPrivacyFeature()) {
3711 return false;
3712 }
3713 return mSpm.isIndividualSensorPrivacyEnabled(userId,
3714 SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
3715}
3716
Michael Grooverd1d435a2018-12-18 17:39:42 -08003717binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3718 {
3719 Mutex::Autolock _l(mSensorPrivacyLock);
3720 mSensorPrivacyEnabled = enabled;
3721 }
3722 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08003723 if (enabled) {
3724 sp<CameraService> service = mService.promote();
3725 if (service != nullptr) {
3726 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003727 }
3728 }
3729 return binder::Status::ok();
3730}
3731
3732void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3733 Mutex::Autolock _l(mSensorPrivacyLock);
3734 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3735 mRegistered = false;
3736}
3737
Evan Severson09ab4002021-02-10 14:15:19 -08003738bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Severson671806e2021-04-20 16:44:53 -07003739 return mSpm.supportsSensorToggle(SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08003740}
3741
Michael Grooverd1d435a2018-12-18 17:39:42 -08003742// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003743// CameraState
3744// ----------------------------------------------------------------------------
3745
3746CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003747 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3748 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3749 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003750
3751CameraService::CameraState::~CameraState() {}
3752
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003753CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003754 Mutex::Autolock lock(mStatusLock);
3755 return mStatus;
3756}
3757
Shuzhen Wang43858162020-01-10 13:42:15 -08003758std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3759 Mutex::Autolock lock(mStatusLock);
3760 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3761 return res;
3762}
3763
Ruben Brunkcc776712015-02-17 20:18:47 -08003764CameraParameters CameraService::CameraState::getShimParams() const {
3765 return mShimParams;
3766}
3767
3768void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3769 mShimParams = params;
3770}
3771
3772int CameraService::CameraState::getCost() const {
3773 return mCost;
3774}
3775
3776std::set<String8> CameraService::CameraState::getConflicting() const {
3777 return mConflicting;
3778}
3779
3780String8 CameraService::CameraState::getId() const {
3781 return mId;
3782}
3783
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003784SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3785 return mSystemCameraKind;
3786}
3787
Shuzhen Wang43858162020-01-10 13:42:15 -08003788bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3789 Mutex::Autolock lock(mStatusLock);
3790 auto result = mUnavailablePhysicalIds.insert(physicalId);
3791 return result.second;
3792}
3793
3794bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3795 Mutex::Autolock lock(mStatusLock);
3796 auto count = mUnavailablePhysicalIds.erase(physicalId);
3797 return count > 0;
3798}
3799
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003800void CameraService::CameraState::setClientPackage(const String8& clientPackage) {
3801 Mutex::Autolock lock(mStatusLock);
3802 mClientPackage = clientPackage;
3803}
3804
3805String8 CameraService::CameraState::getClientPackage() const {
3806 Mutex::Autolock lock(mStatusLock);
3807 return mClientPackage;
3808}
3809
Ruben Brunkcc776712015-02-17 20:18:47 -08003810// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003811// ClientEventListener
3812// ----------------------------------------------------------------------------
3813
3814void CameraService::ClientEventListener::onClientAdded(
3815 const resource_policy::ClientDescriptor<String8,
3816 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003817 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003818 if (basicClient.get() != nullptr) {
3819 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3820 notifier.noteStartCamera(descriptor.getKey(),
3821 static_cast<int>(basicClient->getClientUid()));
3822 }
3823}
3824
3825void CameraService::ClientEventListener::onClientRemoved(
3826 const resource_policy::ClientDescriptor<String8,
3827 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003828 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003829 if (basicClient.get() != nullptr) {
3830 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3831 notifier.noteStopCamera(descriptor.getKey(),
3832 static_cast<int>(basicClient->getClientUid()));
3833 }
3834}
3835
3836
3837// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003838// CameraClientManager
3839// ----------------------------------------------------------------------------
3840
Ruben Brunk99e69712015-05-26 17:25:07 -07003841CameraService::CameraClientManager::CameraClientManager() {
3842 setListener(std::make_shared<ClientEventListener>());
3843}
3844
Ruben Brunkcc776712015-02-17 20:18:47 -08003845CameraService::CameraClientManager::~CameraClientManager() {}
3846
3847sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3848 const String8& id) const {
3849 auto descriptor = get(id);
3850 if (descriptor == nullptr) {
3851 return sp<BasicClient>{nullptr};
3852 }
3853 return descriptor->getValue();
3854}
3855
3856String8 CameraService::CameraClientManager::toString() const {
3857 auto all = getAll();
3858 String8 ret("[");
3859 bool hasAny = false;
3860 for (auto& i : all) {
3861 hasAny = true;
3862 String8 key = i->getKey();
3863 int32_t cost = i->getCost();
3864 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003865 int32_t score = i->getPriority().getScore();
3866 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003867 auto conflicting = i->getConflicting();
3868 auto clientSp = i->getValue();
3869 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003870 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003871 if (clientSp.get() != nullptr) {
3872 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003873 uid_t clientUid = clientSp->getClientUid();
3874 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003875 }
Emilian Peev8131a262017-02-01 12:33:43 +00003876 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3877 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003878
Ruben Brunk6267b532015-04-30 17:44:07 -07003879 if (clientSp.get() != nullptr) {
3880 ret.appendFormat("User Id: %d, ", clientUserId);
3881 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003882 if (packageName.size() != 0) {
3883 ret.appendFormat("Client Package Name: %s", packageName.string());
3884 }
3885
3886 ret.append(", Conflicting Client Devices: {");
3887 for (auto& j : conflicting) {
3888 ret.appendFormat("%s, ", j.string());
3889 }
3890 ret.append("})");
3891 }
3892 if (hasAny) ret.append("\n");
3893 ret.append("]\n");
3894 return ret;
3895}
3896
3897CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3898 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003899 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003900 int32_t state, int32_t oomScoreOffset) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003901
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003902 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003903 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3904 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3905
Ruben Brunkcc776712015-02-17 20:18:47 -08003906 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003907 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient,
3908 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08003909}
3910
3911CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003912 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
3913 int32_t oomScoreOffset) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003914 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003915 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003916 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08003917}
3918
3919// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08003920// InjectionStatusListener
3921// ----------------------------------------------------------------------------
3922
3923void CameraService::InjectionStatusListener::addListener(
3924 const sp<ICameraInjectionCallback>& callback) {
3925 Mutex::Autolock lock(mListenerLock);
3926 if (mCameraInjectionCallback) return;
3927 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
3928 if (res == OK) {
3929 mCameraInjectionCallback = callback;
3930 }
3931}
3932
3933void CameraService::InjectionStatusListener::removeListener() {
3934 Mutex::Autolock lock(mListenerLock);
3935 if (mCameraInjectionCallback == nullptr) {
3936 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
3937 return;
3938 }
3939 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
3940 mCameraInjectionCallback = nullptr;
3941}
3942
3943void CameraService::InjectionStatusListener::notifyInjectionError(
Cliff Wud3a05312021-04-26 23:07:31 +08003944 String8 injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08003945 if (mCameraInjectionCallback == nullptr) {
3946 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
3947 return;
3948 }
Cliff Wud3a05312021-04-26 23:07:31 +08003949
3950 switch (err) {
3951 case -ENODEV:
3952 mCameraInjectionCallback->onInjectionError(
3953 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
3954 ALOGE("No camera device with ID \"%s\" currently available!",
3955 injectedCamId.string());
3956 break;
3957 case -EBUSY:
3958 mCameraInjectionCallback->onInjectionError(
3959 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
3960 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
3961 injectedCamId.string());
3962 break;
3963 case DEAD_OBJECT:
3964 mCameraInjectionCallback->onInjectionError(
3965 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
3966 ALOGE("Camera ID \"%s\" object is dead!",
3967 injectedCamId.string());
3968 break;
3969 case INVALID_OPERATION:
3970 mCameraInjectionCallback->onInjectionError(
3971 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
3972 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
3973 injectedCamId.string());
3974 break;
3975 case UNKNOWN_TRANSACTION:
3976 mCameraInjectionCallback->onInjectionError(
3977 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
3978 ALOGE("Camera ID \"%s\" method doesn't support!",
3979 injectedCamId.string());
3980 break;
3981 default:
3982 mCameraInjectionCallback->onInjectionError(
3983 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
3984 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
3985 strerror(-err), err, injectedCamId.string());
3986 }
Cliff Wud8cae102021-03-11 01:37:42 +08003987}
3988
3989void CameraService::InjectionStatusListener::binderDied(
3990 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08003991 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
3992 auto parent = mParent.promote();
3993 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08003994 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
3995 if (clientDescriptor != nullptr) {
3996 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
3997 baseClientPtr->stopInjection();
3998 }
Cliff Wu3b268182021-07-06 15:44:43 +08003999 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004000 }
4001}
4002
4003// ----------------------------------------------------------------------------
4004// CameraInjectionSession
4005// ----------------------------------------------------------------------------
4006
4007binder::Status CameraService::CameraInjectionSession::stopInjection() {
4008 Mutex::Autolock lock(mInjectionSessionLock);
4009 auto parent = mParent.promote();
4010 if (parent == nullptr) {
4011 ALOGE("CameraInjectionSession: Parent is gone");
4012 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
4013 "Camera service encountered error");
4014 }
Cliff Wud3a05312021-04-26 23:07:31 +08004015
4016 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08004017 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4018 if (clientDescriptor != nullptr) {
4019 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4020 res = baseClientPtr->stopInjection();
4021 if (res != OK) {
4022 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
4023 " ret != NO_ERROR: %d", res);
4024 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
4025 "Camera session encountered error");
4026 }
4027 }
Cliff Wu3b268182021-07-06 15:44:43 +08004028 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004029 return binder::Status::ok();
4030}
4031
4032// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07004033
4034static const int kDumpLockRetries = 50;
4035static const int kDumpLockSleep = 60000;
4036
4037static bool tryLock(Mutex& mutex)
4038{
4039 bool locked = false;
4040 for (int i = 0; i < kDumpLockRetries; ++i) {
4041 if (mutex.tryLock() == NO_ERROR) {
4042 locked = true;
4043 break;
4044 }
4045 usleep(kDumpLockSleep);
4046 }
4047 return locked;
4048}
4049
Rucha Katakwardf223072021-06-15 10:21:00 -07004050void CameraService::cacheDump() {
4051 if (mMemFd != -1) {
4052 const Vector<String16> args;
4053 ATRACE_CALL();
4054 // Acquiring service lock here will avoid the deadlock since
4055 // cacheDump will not be called during the second disconnect.
4056 Mutex::Autolock lock(mServiceLock);
4057
4058 Mutex::Autolock l(mCameraStatesLock);
4059 // Start collecting the info for open sessions and store it in temp file.
4060 for (const auto& state : mCameraStates) {
4061 String8 cameraId = state.first;
4062 auto clientDescriptor = mActiveClientManager.get(cameraId);
4063 if (clientDescriptor != nullptr) {
4064 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.string());
4065 // Log the current open session info before device is disconnected.
4066 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
4067 }
4068 }
4069 }
4070}
4071
Mathias Agopian65ab4712010-07-14 17:59:35 -07004072status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004073 ATRACE_CALL();
4074
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004075 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004076 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004077 CameraThreadState::getCallingPid(),
4078 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004079 return NO_ERROR;
4080 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004081 bool locked = tryLock(mServiceLock);
4082 // failed to lock - CameraService is probably deadlocked
4083 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004084 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004085 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004086
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004087 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004088 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07004089
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004090 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004091 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08004092
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004093 if (locked) mServiceLock.unlock();
4094 return NO_ERROR;
4095 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004096 dprintf(fd, "\n== Service global info: ==\n\n");
4097 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004098 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07004099 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
4100 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004101 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
4102 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
4103 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004104 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004105 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
4106 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004107
4108 dumpEventLog(fd);
4109
4110 bool stateLocked = tryLock(mCameraStatesLock);
4111 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004112 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004113 }
4114
Emilian Peevbd8c5032018-02-14 23:05:40 +00004115 int argSize = args.size();
4116 for (int i = 0; i < argSize; i++) {
4117 if (args[i] == TagMonitor::kMonitorOption) {
4118 if (i + 1 < argSize) {
4119 mMonitorTags = String8(args[i + 1]);
4120 }
4121 break;
4122 }
4123 }
4124
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004125 for (auto& state : mCameraStates) {
4126 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004127
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004128 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004129
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004130 CameraParameters p = state.second->getShimParams();
4131 if (!p.isEmpty()) {
4132 dprintf(fd, " Camera1 API shim is using parameters:\n ");
4133 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004134 }
4135
4136 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004137 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004138 // log the current open session info
4139 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004140 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07004141 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004142 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004143
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004144 }
4145
4146 if (stateLocked) mCameraStatesLock.unlock();
4147
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004148 if (locked) mServiceLock.unlock();
4149
Emilian Peevf53f66e2017-04-11 14:29:43 +01004150 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004151
4152 dprintf(fd, "\n== Vendor tags: ==\n\n");
4153
4154 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
4155 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00004156 sp<VendorTagDescriptorCache> cache =
4157 VendorTagDescriptorCache::getGlobalVendorTagCache();
4158 if (cache == NULL) {
4159 dprintf(fd, "No vendor tags.\n");
4160 } else {
4161 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
4162 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004163 } else {
4164 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
4165 }
4166
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004167 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004168 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004169 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004170
4171 // Process dump arguments, if any
4172 int n = args.size();
4173 String16 verboseOption("-v");
4174 String16 unreachableOption("--unreachable");
4175 for (int i = 0; i < n; i++) {
4176 if (args[i] == verboseOption) {
4177 // change logging level
4178 if (i + 1 >= n) continue;
4179 String8 levelStr(args[i+1]);
4180 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004181 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004182 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004183 } else if (args[i] == unreachableOption) {
4184 // Dump memory analysis
4185 // TODO - should limit be an argument parameter?
4186 UnreachableMemoryInfo info;
4187 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
4188 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004189 dprintf(fd, "\n== Unable to dump unreachable memory. "
4190 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004191 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004192 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004193 std::string s = info.ToString(/*log_contents*/ true);
4194 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004195 }
4196 }
4197 }
Rucha Katakwardf223072021-06-15 10:21:00 -07004198
4199 bool serviceLocked = tryLock(mServiceLock);
4200
4201 // Dump info from previous open sessions.
4202 // Reposition the offset to beginning of the file before reading
4203
4204 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
4205 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
4206 ssize_t size_read;
4207 char buf[4096];
4208 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
4209 // Read data from file to a small buffer and write it to fd.
4210 write(fd, buf, size_read);
4211 if (size_read == -1) {
4212 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4213 break;
4214 }
4215 }
4216 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
4217 } else {
4218 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4219 }
4220
4221 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004222 return NO_ERROR;
4223}
4224
Rucha Katakwardf223072021-06-15 10:21:00 -07004225void CameraService::dumpOpenSessionClientLogs(int fd,
4226 const Vector<String16>& args, const String8& cameraId) {
4227 auto clientDescriptor = mActiveClientManager.get(cameraId);
4228 dprintf(fd, " Device %s is open. Client instance dump:\n",
4229 cameraId.string());
4230 dprintf(fd, " Client priority score: %d state: %d\n",
4231 clientDescriptor->getPriority().getScore(),
4232 clientDescriptor->getPriority().getState());
4233 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
4234
4235 auto client = clientDescriptor->getValue();
4236 dprintf(fd, " Client package: %s\n",
4237 String8(client->getPackageName()).string());
4238
4239 client->dumpClient(fd, args);
4240}
4241
4242void CameraService::dumpClosedSessionClientLogs(int fd, const String8& cameraId) {
4243 dprintf(fd, " Device %s is closed, no client instance\n",
4244 cameraId.string());
4245}
4246
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004247void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004248 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004249
4250 Mutex::Autolock l(mLogLock);
4251 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004252 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004253 }
4254
4255 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004256 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004257 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004258 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004259 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004260 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004261}
4262
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004263void CameraService::cacheClientTagDumpIfNeeded(const char *cameraId, BasicClient* client) {
4264 Mutex::Autolock lock(mLogLock);
4265 if (!isClientWatchedLocked(client)) { return; }
4266
4267 std::vector<std::string> dumpVector;
4268 client->dumpWatchedEventsToVector(dumpVector);
4269
4270 if (dumpVector.empty()) { return; }
4271
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004272 const String16 &packageName = client->getPackageName();
4273
4274 String8 packageName8 = String8(packageName);
4275 const char *printablePackageName = packageName8.lockBuffer(packageName.size());
4276
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004277 std::string dumpString;
4278 size_t i = dumpVector.size();
4279
4280 // Store the string in reverse order (latest last)
4281 while (i > 0) {
4282 i--;
4283 dumpString += cameraId;
4284 dumpString += ":";
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004285 dumpString += printablePackageName;
4286 dumpString += " ";
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004287 dumpString += dumpVector[i]; // implicitly ends with '\n'
4288 }
4289
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004290 packageName8.unlockBuffer();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004291 mWatchedClientsDumpCache[packageName] = dumpString;
4292}
4293
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004294void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004295 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004296 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
4297 if (mTorchClientMap[i] == who) {
4298 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004299 String8 cameraId = mTorchClientMap.keyAt(i);
4300 status_t res = mFlashlight->setTorchMode(cameraId, false);
4301 if (res) {
4302 ALOGE("%s: torch client died but couldn't turn off torch: "
4303 "%s (%d)", __FUNCTION__, strerror(-res), res);
4304 return;
4305 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004306 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004307 break;
4308 }
4309 }
4310}
4311
Ruben Brunkcc776712015-02-17 20:18:47 -08004312/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07004313
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004314 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07004315 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
4316 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004317 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08004318 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004319 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004320
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004321 // check torch client
4322 handleTorchClientBinderDied(who);
4323
4324 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08004325 if(!evictClientIdByRemote(who)) {
4326 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004327 return;
4328 }
4329
Ruben Brunkcc776712015-02-17 20:18:47 -08004330 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
4331 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004332}
4333
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004334void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004335 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08004336}
4337
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004338void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
4339 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004340 // Do not lock mServiceLock here or can get into a deadlock from
4341 // connect() -> disconnect -> updateStatus
4342
4343 auto state = getCameraState(cameraId);
4344
4345 if (state == nullptr) {
4346 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4347 cameraId.string());
4348 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07004349 }
4350
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004351 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
4352 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
4353 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
4354 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
4355 return;
4356 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004357
4358 // Collect the logical cameras without holding mStatusLock in updateStatus
4359 // as that can lead to a deadlock(b/162192331).
4360 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08004361 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08004362 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07004363 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004364 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004365 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004366
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004367 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004368 // Update torch status if it has a flash unit.
4369 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004370 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004371 if (getTorchStatusLocked(cameraId, &torchStatus) !=
4372 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004373 TorchModeStatus newTorchStatus =
4374 status == StatusInternal::PRESENT ?
4375 TorchModeStatus::AVAILABLE_OFF :
4376 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004377 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07004378 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004379 }
4380 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004381 }
4382
4383 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004384 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
4385 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08004386
Ruben Brunkcc776712015-02-17 20:18:47 -08004387 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07004388 bool isVendorListener = listener->isVendorListener();
4389 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
4390 listener->getListenerPid(), listener->getListenerUid()) ||
Shuzhen Wangb8259792021-05-27 09:27:06 -07004391 isVendorListener) {
4392 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004393 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08004394 continue;
4395 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004396 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08004397 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08004398 }
4399 });
Igor Murashkincba2c162013-03-20 15:56:31 -07004400}
4401
Shuzhen Wang695044d2020-03-06 09:02:23 -08004402void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
4403 const String16& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004404 auto state = getCameraState(cameraId);
4405 if (state == nullptr) {
4406 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4407 cameraId.string());
4408 return;
4409 }
4410 if (open) {
4411 state->setClientPackage(String8(clientPackageName));
4412 } else {
4413 state->setClientPackage(String8::empty());
4414 }
4415
Shuzhen Wang695044d2020-03-06 09:02:23 -08004416 Mutex::Autolock lock(mStatusListenerLock);
4417
4418 for (const auto& it : mListenerList) {
4419 if (!it->isOpenCloseCallbackAllowed()) {
4420 continue;
4421 }
4422
4423 binder::Status ret;
4424 String16 cameraId64(cameraId);
4425 if (open) {
4426 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
4427 } else {
4428 ret = it->getListener()->onCameraClosed(cameraId64);
4429 }
4430 if (!ret.isOk()) {
4431 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
4432 ret.exceptionCode());
4433 }
4434 }
4435}
4436
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004437template<class Func>
4438void CameraService::CameraState::updateStatus(StatusInternal status,
4439 const String8& cameraId,
4440 std::initializer_list<StatusInternal> rejectSourceStates,
4441 Func onStatusUpdatedLocked) {
4442 Mutex::Autolock lock(mStatusLock);
4443 StatusInternal oldStatus = mStatus;
4444 mStatus = status;
4445
4446 if (oldStatus == status) {
4447 return;
4448 }
4449
4450 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
4451 cameraId.string(), oldStatus, status);
4452
4453 if (oldStatus == StatusInternal::NOT_PRESENT &&
4454 (status != StatusInternal::PRESENT &&
4455 status != StatusInternal::ENUMERATING)) {
4456
4457 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
4458 __FUNCTION__);
4459 mStatus = oldStatus;
4460 return;
4461 }
4462
4463 /**
4464 * Sometimes we want to conditionally do a transition.
4465 * For example if a client disconnects, we want to go to PRESENT
4466 * only if we weren't already in NOT_PRESENT or ENUMERATING.
4467 */
4468 for (auto& rejectStatus : rejectSourceStates) {
4469 if (oldStatus == rejectStatus) {
4470 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
4471 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
4472 mStatus = oldStatus;
4473 return;
4474 }
4475 }
4476
4477 onStatusUpdatedLocked(cameraId, status);
4478}
4479
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004480status_t CameraService::getTorchStatusLocked(
4481 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004482 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004483 if (!status) {
4484 return BAD_VALUE;
4485 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004486 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4487 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004488 // invalid camera ID or the camera doesn't have a flash unit
4489 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004490 }
4491
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004492 *status = mTorchStatusMap.valueAt(index);
4493 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004494}
4495
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004496status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004497 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004498 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4499 if (index == NAME_NOT_FOUND) {
4500 return BAD_VALUE;
4501 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004502 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004503
4504 return OK;
4505}
4506
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004507std::list<String16> CameraService::getLogicalCameras(
4508 const String8& physicalCameraId) {
4509 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08004510 Mutex::Autolock lock(mCameraStatesLock);
4511 for (const auto& state : mCameraStates) {
4512 std::vector<std::string> physicalCameraIds;
4513 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
4514 // This is not a logical multi-camera.
4515 continue;
4516 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004517 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), physicalCameraId.c_str())
Shuzhen Wang43858162020-01-10 13:42:15 -08004518 == physicalCameraIds.end()) {
4519 // cameraId is not a physical camera of this logical multi-camera.
4520 continue;
4521 }
4522
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004523 retList.emplace_back(String16(state.first));
4524 }
4525 return retList;
4526}
4527
4528void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
4529 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
4530 SystemCameraKind deviceKind) {
4531 // mStatusListenerLock is expected to be locked
4532 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004533 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004534 // Note: we check only the deviceKind of the physical camera id
4535 // since, logical camera ids and their physical camera ids are
4536 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004537 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
4538 listener->getListenerPid(), listener->getListenerUid())) {
4539 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004540 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004541 continue;
4542 }
Shuzhen Wang43858162020-01-10 13:42:15 -08004543 listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004544 logicalCameraId, physicalCameraId);
Shuzhen Wang43858162020-01-10 13:42:15 -08004545 }
4546 }
4547}
4548
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004549
Svet Ganova453d0d2018-01-11 15:37:58 -08004550void CameraService::blockClientsForUid(uid_t uid) {
4551 const auto clients = mActiveClientManager.getAll();
4552 for (auto& current : clients) {
4553 if (current != nullptr) {
4554 const auto basicClient = current->getValue();
4555 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
4556 basicClient->block();
4557 }
4558 }
4559 }
4560}
4561
Michael Grooverd1d435a2018-12-18 17:39:42 -08004562void CameraService::blockAllClients() {
4563 const auto clients = mActiveClientManager.getAll();
4564 for (auto& current : clients) {
4565 if (current != nullptr) {
4566 const auto basicClient = current->getValue();
4567 if (basicClient.get() != nullptr) {
4568 basicClient->block();
4569 }
4570 }
4571 }
4572}
4573
Svet Ganova453d0d2018-01-11 15:37:58 -08004574// NOTE: This is a remote API - make sure all args are validated
4575status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
4576 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
4577 return PERMISSION_DENIED;
4578 }
4579 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
4580 return BAD_VALUE;
4581 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004582 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004583 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004584 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004585 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004586 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004587 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004588 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
4589 return handleSetRotateAndCrop(args);
4590 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
4591 return handleGetRotateAndCrop(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004592 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
4593 return handleSetImageDumpMask(args);
4594 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
4595 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004596 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
4597 return handleSetCameraMute(args);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004598 } else if (args.size() >= 2 && args[0] == String16("watch")) {
4599 return handleWatchCommand(args, out);
Svet Ganova453d0d2018-01-11 15:37:58 -08004600 } else if (args.size() == 1 && args[0] == String16("help")) {
4601 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004602 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08004603 }
4604 printHelp(err);
4605 return BAD_VALUE;
4606}
4607
4608status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004609 String16 packageName = args[1];
4610
Svet Ganova453d0d2018-01-11 15:37:58 -08004611 bool active = false;
4612 if (args[2] == String16("active")) {
4613 active = true;
4614 } else if ((args[2] != String16("idle"))) {
4615 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
4616 return BAD_VALUE;
4617 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004618
4619 int userId = 0;
4620 if (args.size() >= 5 && args[3] == String16("--user")) {
4621 userId = atoi(String8(args[4]));
4622 }
4623
4624 uid_t uid;
4625 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
4626 return BAD_VALUE;
4627 }
4628
4629 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08004630 return NO_ERROR;
4631}
4632
4633status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004634 String16 packageName = args[1];
4635
4636 int userId = 0;
4637 if (args.size() >= 4 && args[2] == String16("--user")) {
4638 userId = atoi(String8(args[3]));
4639 }
4640
4641 uid_t uid;
4642 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004643 return BAD_VALUE;
4644 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004645
4646 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004647 return NO_ERROR;
4648}
4649
4650status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004651 String16 packageName = args[1];
4652
4653 int userId = 0;
4654 if (args.size() >= 4 && args[2] == String16("--user")) {
4655 userId = atoi(String8(args[3]));
4656 }
4657
4658 uid_t uid;
4659 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004660 return BAD_VALUE;
4661 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004662
4663 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004664 return dprintf(out, "active\n");
4665 } else {
4666 return dprintf(out, "idle\n");
4667 }
4668}
4669
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004670status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4671 int rotateValue = atoi(String8(args[1]));
4672 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4673 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4674 Mutex::Autolock lock(mServiceLock);
4675
4676 mOverrideRotateAndCropMode = rotateValue;
4677
4678 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4679
4680 const auto clients = mActiveClientManager.getAll();
4681 for (auto& current : clients) {
4682 if (current != nullptr) {
4683 const auto basicClient = current->getValue();
4684 if (basicClient.get() != nullptr) {
4685 basicClient->setRotateAndCropOverride(rotateValue);
4686 }
4687 }
4688 }
4689
4690 return OK;
4691}
4692
4693status_t CameraService::handleGetRotateAndCrop(int out) {
4694 Mutex::Autolock lock(mServiceLock);
4695
4696 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4697}
4698
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004699status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
4700 char *endPtr;
4701 errno = 0;
4702 String8 maskString8 = String8(args[1]);
4703 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
4704
4705 if (errno != 0) return BAD_VALUE;
4706 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
4707 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
4708
4709 Mutex::Autolock lock(mServiceLock);
4710
4711 mImageDumpMask = maskValue;
4712
4713 return OK;
4714}
4715
4716status_t CameraService::handleGetImageDumpMask(int out) {
4717 Mutex::Autolock lock(mServiceLock);
4718
4719 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
4720}
4721
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004722status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
4723 int muteValue = strtol(String8(args[1]), nullptr, 10);
4724 if (errno != 0) return BAD_VALUE;
4725
4726 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
4727 Mutex::Autolock lock(mServiceLock);
4728
4729 mOverrideCameraMuteMode = (muteValue == 1);
4730
4731 const auto clients = mActiveClientManager.getAll();
4732 for (auto& current : clients) {
4733 if (current != nullptr) {
4734 const auto basicClient = current->getValue();
4735 if (basicClient.get() != nullptr) {
4736 if (basicClient->supportsCameraMute()) {
4737 basicClient->setCameraMute(mOverrideCameraMuteMode);
4738 }
4739 }
4740 }
4741 }
4742
4743 return OK;
4744}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004745
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004746status_t CameraService::handleWatchCommand(const Vector<String16>& args, int outFd) {
4747 if (args.size() >= 3 && args[1] == String16("start")) {
4748 return startWatchingTags(args, outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004749 } else if (args.size() == 2 && args[1] == String16("dump")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004750 return camera3::CameraTraces::dump(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004751 } else if (args.size() == 2 && args[1] == String16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004752 return stopWatchingTags(outFd);
4753 } else if (args.size() >= 2 && args[1] == String16("print")) {
4754 return printWatchedTags(args, outFd);
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004755 } else if (args.size() == 2 && args[1] == String16("clear")) {
4756 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004757 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004758 dprintf(outFd, "Camera service watch commands:\n"
4759 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
4760 " starts watching the provided tags for clients with provided package\n"
4761 " recognizes tag shorthands like '3a'\n"
4762 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004763 " dump dumps camera trace\n"
4764 " stop stops watching all tags\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004765 " print [-n <refresh_interval_ms>]\n"
4766 " prints the monitored information in real time\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004767 " Hit Ctrl+C to exit\n"
4768 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004769 return BAD_VALUE;
4770}
4771
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004772status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
4773 Mutex::Autolock lock(mLogLock);
4774 size_t tagsIdx; // index of '-m'
4775 String16 tags("");
4776 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != String16("-m"); tagsIdx++);
4777 if (tagsIdx < args.size() - 1) {
4778 tags = args[tagsIdx + 1];
4779 } else {
4780 dprintf(outFd, "No tags provided.\n");
4781 return BAD_VALUE;
4782 }
4783
4784 size_t clientsIdx; // index of '-c'
4785 String16 clients = kWatchAllClientsFlag; // watch all clients if no clients are provided
4786 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != String16("-c");
4787 clientsIdx++);
4788 if (clientsIdx < args.size() - 1) {
4789 clients = args[clientsIdx + 1];
4790 }
4791 parseClientsToWatchLocked(String8(clients));
4792
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004793 // track tags to initialize future clients with the monitoring information
4794 mMonitorTags = String8(tags);
4795
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004796 bool serviceLock = tryLock(mServiceLock);
4797 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004798 auto cameraClients = mActiveClientManager.getAll();
4799 for (const auto &clientDescriptor: cameraClients) {
4800 if (clientDescriptor == nullptr) { continue; }
4801 sp<BasicClient> client = clientDescriptor->getValue();
4802 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004803
4804 if (isClientWatchedLocked(client.get())) {
4805 client->startWatchingTags(mMonitorTags, outFd);
4806 numWatchedClients++;
4807 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004808 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004809 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
4810
4811 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004812 return OK;
4813}
4814
4815status_t CameraService::stopWatchingTags(int outFd) {
4816 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004817 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004818 mMonitorTags = String8::empty();
4819
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004820 mWatchedClientPackages.clear();
4821 mWatchedClientsDumpCache.clear();
4822
4823 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004824 auto cameraClients = mActiveClientManager.getAll();
4825 for (const auto &clientDescriptor : cameraClients) {
4826 if (clientDescriptor == nullptr) { continue; }
4827 sp<BasicClient> client = clientDescriptor->getValue();
4828 if (client.get() == nullptr) { continue; }
4829 client->stopWatchingTags(outFd);
4830 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004831 dprintf(outFd, "Stopped watching all clients.\n");
4832 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004833 return OK;
4834}
4835
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004836status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
4837 Mutex::Autolock lock(mLogLock);
4838 size_t clearedSize = mWatchedClientsDumpCache.size();
4839 mWatchedClientsDumpCache.clear();
4840 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
4841 return OK;
4842}
4843
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004844status_t CameraService::printWatchedTags(const Vector<String16> &args, int outFd) {
4845 // Figure outFd refresh interval, if present in args
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004846 useconds_t refreshTimeoutMs = 1000; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004847 if (args.size() > 2) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004848 size_t intervalIdx; // index of '-n'
4849 for (intervalIdx = 2; intervalIdx < args.size() && String16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004850 intervalIdx++);
4851
4852 size_t intervalValIdx = intervalIdx + 1;
4853 if (intervalValIdx < args.size()) {
4854 refreshTimeoutMs = strtol(String8(args[intervalValIdx].string()), nullptr, 10);
4855 if (errno) { return BAD_VALUE; }
4856 }
4857 }
4858
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004859 std::set<String16> connectedMonitoredClients;
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004860 {
4861 Mutex::Autolock logLock(mLogLock);
4862 bool serviceLock = tryLock(mServiceLock);
4863 // get all watched clients that are currently connected
4864 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
4865 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004866
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004867 sp<BasicClient> client = clientDescriptor->getValue();
4868 if (client.get() == nullptr) { continue; }
4869 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004870
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004871 connectedMonitoredClients.emplace(client->getPackageName());
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004872 }
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004873 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004874
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004875 // Print entries in mWatchedClientsDumpCache for clients that are not connected
4876 for (const auto &kv: mWatchedClientsDumpCache) {
4877 const String16 &package = kv.first;
4878 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
4879 continue;
4880 }
4881
4882 dprintf(outFd, "Client: %s\n", String8(package).string());
4883 dprintf(outFd, "%s\n", kv.second.c_str());
4884 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004885 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004886
Avichal Rakesh1cda16b2021-11-09 16:51:02 -08004887 if (connectedMonitoredClients.empty()) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004888 dprintf(outFd, "No watched client active.\n");
4889 return OK;
4890 }
4891
4892 // For connected watched clients, print monitored tags live
4893 return printWatchedTagsUntilInterrupt(refreshTimeoutMs * 1000, outFd);
4894}
4895
4896status_t CameraService::printWatchedTagsUntilInterrupt(useconds_t refreshMicros, int outFd) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004897 std::unordered_map<std::string, std::string> cameraToLastEvent;
4898 auto cameraClients = mActiveClientManager.getAll();
4899
4900 if (cameraClients.empty()) {
4901 dprintf(outFd, "No clients connected.\n");
4902 return OK;
4903 }
4904
4905 dprintf(outFd, "Press Ctrl + C to exit...\n\n");
4906 while (true) {
4907 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004908 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004909 if (clientDescriptor == nullptr) { continue; }
4910 const char* cameraId = clientDescriptor->getKey().string();
4911
4912 // This also initializes the map entries with an empty string
4913 const std::string& lastPrintedEvent = cameraToLastEvent[cameraId];
4914
4915 sp<BasicClient> client = clientDescriptor->getValue();
4916 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004917 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004918
4919 std::vector<std::string> latestEvents;
4920 client->dumpWatchedEventsToVector(latestEvents);
4921
4922 if (!latestEvents.empty()) {
4923 printNewWatchedEvents(outFd,
4924 cameraId,
4925 client->getPackageName(),
4926 latestEvents,
4927 lastPrintedEvent);
4928 cameraToLastEvent[cameraId] = latestEvents[0];
4929 }
4930 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004931 usleep(refreshMicros); // convert ms to us
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004932 }
4933 return OK;
4934}
4935
4936void CameraService::printNewWatchedEvents(int outFd,
4937 const char *cameraId,
4938 const String16 &packageName,
4939 const std::vector<std::string> &events,
4940 const std::string &lastPrintedEvent) {
4941 if (events.empty()) { return; }
4942
4943 // index of lastPrintedEvent in events.
4944 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
4945 size_t lastPrintedIdx;
4946 for (lastPrintedIdx = 0;
4947 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
4948 lastPrintedIdx++);
4949
4950 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
4951
4952 const char *printPackageName = String8(packageName).string();
4953 // print events in chronological order (latest event last)
4954 size_t idxToPrint = lastPrintedIdx;
4955 do {
4956 idxToPrint--;
4957 dprintf(outFd, "%s:%s %s", cameraId, printPackageName, events[idxToPrint].c_str());
4958 } while (idxToPrint != 0);
4959}
4960
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004961void CameraService::parseClientsToWatchLocked(String8 clients) {
4962 mWatchedClientPackages.clear();
4963
4964 const char *allSentinel = String8(kWatchAllClientsFlag).string();
4965
4966 char *tokenized = clients.lockBuffer(clients.size());
4967 char *savePtr;
4968 char *nextClient = strtok_r(tokenized, ",", &savePtr);
4969
4970 while (nextClient != nullptr) {
4971 if (strcmp(nextClient, allSentinel) == 0) {
4972 // Don't need to track any other package if 'all' is present
4973 mWatchedClientPackages.clear();
4974 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
4975 break;
4976 }
4977
4978 // track package names
4979 mWatchedClientPackages.emplace(nextClient);
4980 nextClient = strtok_r(nullptr, ",", &savePtr);
4981 }
4982 clients.unlockBuffer();
4983}
4984
Svet Ganova453d0d2018-01-11 15:37:58 -08004985status_t CameraService::printHelp(int out) {
4986 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004987 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4988 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4989 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004990 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4991 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4992 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004993 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
4994 " Valid values 0=OFF, 1=ON for JPEG\n"
4995 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004996 " set-camera-mute <0/1> enable or disable camera muting\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08004997 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004998 " help print this message\n");
4999}
5000
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005001bool CameraService::isClientWatched(const BasicClient *client) {
5002 Mutex::Autolock lock(mLogLock);
5003 return isClientWatchedLocked(client);
5004}
5005
5006bool CameraService::isClientWatchedLocked(const BasicClient *client) {
5007 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
5008 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
5009}
5010
Yin-Chia Yehdba03232019-08-19 15:54:28 -07005011int32_t CameraService::updateAudioRestriction() {
5012 Mutex::Autolock lock(mServiceLock);
5013 return updateAudioRestrictionLocked();
5014}
5015
5016int32_t CameraService::updateAudioRestrictionLocked() {
5017 int32_t mode = 0;
5018 // iterate through all active client
5019 for (const auto& i : mActiveClientManager.getAll()) {
5020 const auto clientSp = i->getValue();
5021 mode |= clientSp->getAudioRestriction();
5022 }
5023
5024 bool modeChanged = (mAudioRestriction != mode);
5025 mAudioRestriction = mode;
5026 if (modeChanged) {
5027 mAppOps.setCameraAudioRestriction(mode);
5028 }
5029 return mode;
5030}
5031
Cliff Wud3a05312021-04-26 23:07:31 +08005032void CameraService::clearInjectionParameters() {
5033 {
5034 Mutex::Autolock lock(mInjectionParametersLock);
5035 mInjectionInitPending = true;
5036 mInjectionInternalCamId = "";
5037 }
5038 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08005039 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08005040}
5041
Mathias Agopian65ab4712010-07-14 17:59:35 -07005042}; // namespace android