blob: 1b8eb99843d4a09defa87d116d8ed4093eab17a1 [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:
Shuzhen Wang90708ea2021-11-04 11:40:49 -0700913 case CAMERA_DEVICE_API_VERSION_3_8:
Ruben Brunkcc776712015-02-17 20:18:47 -0800914 if (effectiveApiLevel == API_1) { // Camera1 API route
915 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800916 *client = new Camera2Client(cameraService, tmp, packageName, featureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800917 cameraId, api1CameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -0700918 facing, sensorOrientation, clientPid, clientUid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700919 servicePid, overrideForPerfClass);
Ruben Brunkcc776712015-02-17 20:18:47 -0800920 } else { // Camera2 API route
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800921 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
922 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Philip P. Moltmann9e648f62019-11-04 12:52:45 -0800923 *client = new CameraDeviceClient(cameraService, tmp, packageName, featureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700924 cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
925 overrideForPerfClass);
Ruben Brunkcc776712015-02-17 20:18:47 -0800926 }
927 break;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700928 default:
Ruben Brunkcc776712015-02-17 20:18:47 -0800929 // Should not be reachable
930 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800931 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800932 "Camera device \"%s\" has unknown HAL version %d",
933 cameraId.string(), deviceVersion);
Ruben Brunkcc776712015-02-17 20:18:47 -0800934 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800935 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -0800936}
937
Ruben Brunk6267b532015-04-30 17:44:07 -0700938String8 CameraService::toString(std::set<userid_t> intSet) {
939 String8 s("");
940 bool first = true;
941 for (userid_t i : intSet) {
942 if (first) {
943 s.appendFormat("%d", i);
944 first = false;
945 } else {
946 s.appendFormat(", %d", i);
947 }
948 }
949 return s;
950}
951
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800952int32_t CameraService::mapToInterface(TorchModeStatus status) {
953 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
954 switch (status) {
955 case TorchModeStatus::NOT_AVAILABLE:
956 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
957 break;
958 case TorchModeStatus::AVAILABLE_OFF:
959 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
960 break;
961 case TorchModeStatus::AVAILABLE_ON:
962 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
963 break;
964 default:
965 ALOGW("Unknown new flash status: %d", status);
966 }
967 return serviceStatus;
968}
969
970CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
971 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
972 switch (status) {
973 case CameraDeviceStatus::NOT_PRESENT:
974 serviceStatus = StatusInternal::NOT_PRESENT;
975 break;
976 case CameraDeviceStatus::PRESENT:
977 serviceStatus = StatusInternal::PRESENT;
978 break;
979 case CameraDeviceStatus::ENUMERATING:
980 serviceStatus = StatusInternal::ENUMERATING;
981 break;
982 default:
983 ALOGW("Unknown new HAL device status: %d", status);
984 }
985 return serviceStatus;
986}
987
988int32_t CameraService::mapToInterface(StatusInternal status) {
989 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
990 switch (status) {
991 case StatusInternal::NOT_PRESENT:
992 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
993 break;
994 case StatusInternal::PRESENT:
995 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
996 break;
997 case StatusInternal::ENUMERATING:
998 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
999 break;
1000 case StatusInternal::NOT_AVAILABLE:
1001 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1002 break;
1003 case StatusInternal::UNKNOWN:
1004 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1005 break;
1006 default:
1007 ALOGW("Unknown new internal device status: %d", status);
1008 }
1009 return serviceStatus;
1010}
1011
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001012Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001013 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001014
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001015 String16 internalPackageName("cameraserver");
Ruben Brunkcc776712015-02-17 20:18:47 -08001016 String8 id = String8::format("%d", cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001017 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001018 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001019 if (!(ret = connectHelper<ICameraClient,Client>(
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001020 sp<ICameraClient>{nullptr}, id, cameraId,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001021 internalPackageName, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001022 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
1023 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001024 ).isOk()) {
1025 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001026 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001027 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001028}
1029
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001030Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001031 /*out*/
1032 CameraParameters* parameters) {
1033
1034 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1035
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001036 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001037
1038 if (parameters == NULL) {
1039 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001040 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001041 }
1042
Ruben Brunkcc776712015-02-17 20:18:47 -08001043 String8 id = String8::format("%d", cameraId);
1044
1045 // Check if we already have parameters
1046 {
1047 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001048 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001049 auto cameraState = getCameraState(id);
1050 if (cameraState == nullptr) {
1051 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001052 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1053 "Invalid camera ID: %s", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08001054 }
1055 CameraParameters p = cameraState->getShimParams();
1056 if (!p.isEmpty()) {
1057 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001058 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001059 }
1060 }
1061
Jayant Chowdhary12361932018-08-27 14:46:13 -07001062 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001063 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001064 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001065 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001066 // Error already logged by callee
1067 return ret;
1068 }
1069
1070 // Check for parameters again
1071 {
1072 // Scope for service lock
1073 Mutex::Autolock lock(mServiceLock);
1074 auto cameraState = getCameraState(id);
1075 if (cameraState == nullptr) {
1076 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001077 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1078 "Invalid camera ID: %s", id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001079 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001080 CameraParameters p = cameraState->getShimParams();
1081 if (!p.isEmpty()) {
1082 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001083 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001084 }
1085 }
1086
Ruben Brunkcc776712015-02-17 20:18:47 -08001087 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1088 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001089 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001090}
1091
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001092// Can camera service trust the caller based on the calling UID?
1093static bool isTrustedCallingUid(uid_t uid) {
1094 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001095 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001096 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001097 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001098 return true;
1099 default:
1100 return false;
1101 }
1102}
1103
Nicholas Sauera3620332019-04-03 14:05:17 -07001104static status_t getUidForPackage(String16 packageName, int userId, /*inout*/uid_t& uid, int err) {
1105 PermissionController pc;
1106 uid = pc.getPackageUid(packageName, 0);
1107 if (uid <= 0) {
1108 ALOGE("Unknown package: '%s'", String8(packageName).string());
1109 dprintf(err, "Unknown package: '%s'\n", String8(packageName).string());
1110 return BAD_VALUE;
1111 }
1112
1113 if (userId < 0) {
1114 ALOGE("Invalid user: %d", userId);
1115 dprintf(err, "Invalid user: %d\n", userId);
1116 return BAD_VALUE;
1117 }
1118
1119 uid = multiuser_get_uid(userId, uid);
1120 return NO_ERROR;
1121}
1122
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001123Status CameraService::validateConnectLocked(const String8& cameraId,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001124 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
1125 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001126
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001127#ifdef __BRILLO__
1128 UNUSED(clientName8);
1129 UNUSED(clientUid);
1130 UNUSED(clientPid);
1131 UNUSED(originalClientPid);
1132#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001133 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1134 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001135 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001136 return allowed;
1137 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001138#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001139
Jayant Chowdhary12361932018-08-27 14:46:13 -07001140 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001141
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001142 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001143 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1144 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001145 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1146 "No camera HAL module available to open camera device \"%s\"", cameraId.string());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001147 }
1148
Ruben Brunkcc776712015-02-17 20:18:47 -08001149 if (getCameraState(cameraId) == nullptr) {
1150 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1151 cameraId.string());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001152 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1153 "No camera device with ID \"%s\" available", cameraId.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001154 }
1155
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001156 status_t err = checkIfDeviceIsUsable(cameraId);
1157 if (err != NO_ERROR) {
1158 switch(err) {
1159 case -ENODEV:
1160 case -EBUSY:
1161 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1162 "No camera device with ID \"%s\" currently available", cameraId.string());
1163 default:
1164 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1165 "Unknown error connecting to ID \"%s\"", cameraId.string());
1166 }
1167 }
1168 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001169}
1170
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001171Status CameraService::validateClientPermissionsLocked(const String8& cameraId,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001172 const String8& clientName8, int& clientUid, int& clientPid,
1173 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001174 int callingPid = CameraThreadState::getCallingPid();
1175 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001176
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001177 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001178 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001179 clientUid = callingUid;
1180 } else if (!isTrustedCallingUid(callingUid)) {
1181 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1182 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001183 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1184 "Untrusted caller (calling PID %d, UID %d) trying to "
1185 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1186 callingPid, callingUid, cameraId.string(),
1187 clientName8.string(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001188 }
1189
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001190 // Check if we can trust clientPid
1191 if (clientPid == USE_CALLING_PID) {
1192 clientPid = callingPid;
1193 } else if (!isTrustedCallingUid(callingUid)) {
1194 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1195 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001196 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1197 "Untrusted caller (calling PID %d, UID %d) trying to "
1198 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1199 callingPid, callingUid, cameraId.string(),
1200 clientName8.string(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001201 }
1202
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001203 if (shouldRejectSystemCameraConnection(cameraId)) {
1204 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1205 cameraId.c_str());
1206 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
1207 "available", cameraId.string());
1208 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001209 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1210 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1211 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
1212 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
1213 "found while trying to query device kind", cameraId.string());
1214
1215 }
1216
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001217 // If it's not calling from cameraserver, check the permission if the
1218 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1219 // android.permission.SYSTEM_CAMERA for system only camera devices).
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001220 if (callingPid != getpid() &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001221 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001222 !checkPermission(sCameraPermission, clientPid, clientUid)) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001223 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001224 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1225 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
1226 clientName8.string(), clientUid, clientPid, cameraId.string());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001227 }
1228
Svet Ganova453d0d2018-01-11 15:37:58 -08001229 // Make sure the UID is in an active state to use the camera
Svet Ganov7b4ab782018-03-25 12:48:10 -07001230 if (!mUidPolicy->isUidActive(callingUid, String16(clientName8))) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001231 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001232 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1233 clientPid, clientUid);
1234 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001235 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1236 "calling UID %d proc state %" PRId32 ")",
1237 clientName8.string(), clientUid, clientPid, cameraId.string(),
1238 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001239 }
1240
Michael Grooverd1d435a2018-12-18 17:39:42 -08001241 // If sensor privacy is enabled then prevent access to the camera
1242 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1243 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1244 return STATUS_ERROR_FMT(ERROR_DISABLED,
1245 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
1246 "is enabled", clientName8.string(), clientUid, clientPid, cameraId.string());
1247 }
1248
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001249 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1250 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001251 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001252 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001253
Ruben Brunk6267b532015-04-30 17:44:07 -07001254 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001255
Ruben Brunka8ca9152015-04-07 14:23:40 -07001256 // Only allow clients who are being used by the current foreground device user, unless calling
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001257 // from our own process OR the caller is using the cameraserver's HIDL interface.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001258 if (getCurrentServingCall() != BinderCallType::HWBINDER && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001259 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001260 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1261 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
1262 toString(mAllowedUsers).string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001263 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1264 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
1265 clientUserId, cameraId.string());
Ruben Brunk36597b22015-03-20 22:15:57 -07001266 }
1267
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001268 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001269}
1270
1271status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
1272 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001273 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001274 if (cameraState == nullptr) {
1275 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
1276 cameraId.string());
1277 return -ENODEV;
1278 }
1279
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001280 StatusInternal currentStatus = cameraState->getStatus();
1281 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001282 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
1283 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001284 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001285 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001286 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
1287 callingPid, cameraId.string());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001288 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001289 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001290
Ruben Brunkcc776712015-02-17 20:18:47 -08001291 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001292}
1293
Ruben Brunkcc776712015-02-17 20:18:47 -08001294void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001295 const CameraService::DescriptorPtr& desc, int oomScoreOffset) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001296
Ruben Brunkcc776712015-02-17 20:18:47 -08001297 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001298 auto clientDescriptor =
1299 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
1300 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08001301 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1302
1303 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
1304 String8(client->getPackageName()));
1305
1306 if (evicted.size() > 0) {
1307 // This should never happen - clients should already have been removed in disconnect
1308 for (auto& i : evicted) {
1309 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
1310 __FUNCTION__, i->getKey().string());
1311 }
1312
1313 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1314 __FUNCTION__);
1315 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001316
1317 // And register a death notification for the client callback. Do
1318 // this last to avoid Binder policy where a nested Binder
1319 // transaction might be pre-empted to service the client death
1320 // notification if the client process dies before linkToDeath is
1321 // invoked.
1322 sp<IBinder> remoteCallback = client->getRemote();
1323 if (remoteCallback != nullptr) {
1324 remoteCallback->linkToDeath(this);
1325 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001326}
1327
1328status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
1329 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001330 int oomScoreOffset,
Ruben Brunkcc776712015-02-17 20:18:47 -08001331 /*out*/
1332 sp<BasicClient>* client,
1333 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001334 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001335 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001336 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001337 DescriptorPtr clientDescriptor;
1338 {
1339 if (effectiveApiLevel == API_1) {
1340 // If we are using API1, any existing client for this camera ID with the same remote
1341 // should be returned rather than evicted to allow MediaRecorder to work properly.
1342
1343 auto current = mActiveClientManager.get(cameraId);
1344 if (current != nullptr) {
1345 auto clientSp = current->getValue();
1346 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001347 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001348 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001349 " API level, evicting prior client...");
1350 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001351 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001352 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001353 *client = clientSp;
1354 return NO_ERROR;
1355 }
1356 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001357 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001358 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001359
Ruben Brunkcc776712015-02-17 20:18:47 -08001360 // Get current active client PIDs
1361 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1362 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001363
Emilian Peev8131a262017-02-01 12:33:43 +00001364 std::vector<int> priorityScores(ownerPids.size());
1365 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001366
Emilian Peev8131a262017-02-01 12:33:43 +00001367 // Get priority scores of all active PIDs
1368 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1369 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1370 /*out*/&priorityScores[0]);
1371 if (err != OK) {
1372 ALOGE("%s: Priority score query failed: %d",
1373 __FUNCTION__, err);
1374 return err;
1375 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001376
Ruben Brunkcc776712015-02-17 20:18:47 -08001377 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001378 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001379 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001380 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001381 resource_policy::ClientPriority(priorityScores[i], states[i],
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001382 /* isVendorClient won't get copied over*/ false,
1383 /* oomScoreOffset won't get copied over*/ 0));
Ruben Brunkcc776712015-02-17 20:18:47 -08001384 }
1385 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001386
Ruben Brunkcc776712015-02-17 20:18:47 -08001387 // Get state for the given cameraId
1388 auto state = getCameraState(cameraId);
1389 if (state == nullptr) {
1390 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1391 clientPid, cameraId.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001392 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001393 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001394 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001395
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001396 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1397 int32_t actualState = states[states.size() - 1];
1398
1399 // Make descriptor for incoming client. We store the oomScoreOffset
1400 // since we might need it later on new handleEvictionsLocked and
1401 // ProcessInfoService would not take that into account.
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001402 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001403 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001404 state->getConflicting(), actualScore, clientPid, actualState,
1405 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08001406
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001407 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1408
Ruben Brunkcc776712015-02-17 20:18:47 -08001409 // Find clients that would be evicted
1410 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1411
1412 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1413 // background, so we cannot do evictions
1414 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1415 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1416 " priority).", clientPid);
1417
1418 sp<BasicClient> clientSp = clientDescriptor->getValue();
1419 String8 curTime = getFormattedCurrentTime();
1420 auto incompatibleClients =
1421 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1422
1423 String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
Emilian Peev8131a262017-02-01 12:33:43 +00001424 "(PID %d, score %d state %d) due to eviction policy", curTime.string(),
Ruben Brunkcc776712015-02-17 20:18:47 -08001425 cameraId.string(), packageName.string(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001426 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001427
1428 for (auto& i : incompatibleClients) {
1429 msg.appendFormat("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001430 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
1431 i->getKey().string(),
1432 String8{i->getValue()->getPackageName()}.string(),
1433 i->getOwnerId(), i->getPriority().getScore(),
1434 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001435 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00001436 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(),
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001437 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001438 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001439 }
1440
1441 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001442 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001443 mEventLog.add(msg);
1444
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001445 auto current = mActiveClientManager.get(cameraId);
1446 if (current != nullptr) {
1447 return -EBUSY; // CAMERA_IN_USE
1448 } else {
1449 return -EUSERS; // MAX_CAMERAS_IN_USE
1450 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001451 }
1452
1453 for (auto& i : evicted) {
1454 sp<BasicClient> clientSp = i->getValue();
1455 if (clientSp.get() == nullptr) {
1456 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1457
1458 // TODO: Remove this
1459 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1460 __FUNCTION__);
1461 mActiveClientManager.remove(i);
1462 continue;
1463 }
1464
1465 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1466 i->getKey().string());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001467 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001468
Ruben Brunkcc776712015-02-17 20:18:47 -08001469 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07001470 logEvent(String8::format("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001471 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1472 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Ruben Brunkcc776712015-02-17 20:18:47 -08001473 i->getKey().string(), String8{clientSp->getPackageName()}.string(),
Emilian Peev8131a262017-02-01 12:33:43 +00001474 i->getOwnerId(), i->getPriority().getScore(),
1475 i->getPriority().getState(), cameraId.string(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001476 packageName.string(), clientPid, clientPriority.getScore(),
1477 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001478
1479 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001480 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001481 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001482 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001483 }
1484
Ruben Brunkcc776712015-02-17 20:18:47 -08001485 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1486 // other clients from connecting in mServiceLockWrapper if held
1487 mServiceLock.unlock();
1488
1489 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001490 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001491
1492 // Destroy evicted clients
1493 for (auto& i : evictedClients) {
1494 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001495 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001496 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001497
Jayant Chowdhary12361932018-08-27 14:46:13 -07001498 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001499
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001500 for (const auto& i : evictedClients) {
1501 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1502 __FUNCTION__, i->getKey().string(), i->getOwnerId());
1503 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1504 if (ret == TIMED_OUT) {
1505 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1506 "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1507 mActiveClientManager.toString().string());
1508 return -EBUSY;
1509 }
1510 if (ret != NO_ERROR) {
1511 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1512 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1513 ret, mActiveClientManager.toString().string());
1514 return ret;
1515 }
1516 }
1517
1518 evictedClients.clear();
1519
Ruben Brunkcc776712015-02-17 20:18:47 -08001520 // Once clients have been disconnected, relock
1521 mServiceLock.lock();
1522
1523 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1524 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1525 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001526 }
1527
Ruben Brunkcc776712015-02-17 20:18:47 -08001528 *partial = clientDescriptor;
1529 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001530}
1531
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001532Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001533 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001534 int api1CameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001535 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001536 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001537 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001538 int targetSdkVersion,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001539 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001540 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001541
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001542 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001543 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001544
1545 String8 id = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001546 sp<Client> client = nullptr;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001547 ret = connectHelper<ICameraClient,Client>(cameraClient, id, api1CameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001548 clientPackageName, {}, clientUid, clientPid, API_1,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001549 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001550
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001551 if(!ret.isOk()) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001552 logRejected(id, CameraThreadState::getCallingPid(), String8(clientPackageName),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001553 ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001554 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001555 }
1556
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001557 *device = client;
1558 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001559}
1560
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001561bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1562 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001563 // If the client is not a vendor client, don't add listener if
1564 // a) the camera is a publicly hidden secure camera OR
1565 // b) the camera is a system only camera and the client doesn't
1566 // have android.permission.SYSTEM_CAMERA permissions.
1567 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1568 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1569 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001570 return true;
1571 }
1572 return false;
1573}
1574
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001575bool CameraService::shouldRejectSystemCameraConnection(const String8& cameraId) const {
1576 // Rules for rejection:
1577 // 1) If cameraserver tries to access this camera device, accept the
1578 // connection.
1579 // 2) The camera device is a publicly hidden secure camera device AND some
1580 // component is trying to access it on a non-hwbinder thread (generally a non HAL client),
1581 // reject it.
1582 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1583 // and the serving thread is a non hwbinder thread, the client must have
1584 // android.permission.SYSTEM_CAMERA permissions to connect.
1585
1586 int cPid = CameraThreadState::getCallingPid();
1587 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001588 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1589 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001590 // This isn't a known camera ID, so it's not a system camera
1591 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1592 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001593 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001594
1595 // (1) Cameraserver trying to connect, accept.
1596 if (CameraThreadState::getCallingPid() == getpid()) {
1597 return false;
1598 }
1599 // (2)
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001600 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001601 systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
1602 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1603 return true;
1604 }
1605 // (3) Here we only check for permissions if it is a system only camera device. This is since
1606 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1607 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1608 // same behavior for system camera devices.
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001609 if (getCurrentServingCall() != BinderCallType::HWBINDER &&
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001610 systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jayant Chowdharyc3198c32021-07-28 20:59:14 +00001611 !hasPermissionsForSystemCamera(cPid, cUid, /*logPermissionFailure*/true)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001612 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1613 cameraId.c_str());
1614 return true;
1615 }
1616
1617 return false;
1618}
1619
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001620Status CameraService::connectDevice(
1621 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001622 const String16& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00001623 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001624 const std::optional<String16>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001625 int clientUid, int oomScoreOffset, int targetSdkVersion,
Ruben Brunkcc776712015-02-17 20:18:47 -08001626 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001627 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001628
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001629 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001630 Status ret = Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001631 String8 id = String8(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001632 sp<CameraDeviceClient> client = nullptr;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001633 String16 clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001634 int callingPid = CameraThreadState::getCallingPid();
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001635
Steven Moreland89a2c5c2020-01-31 15:02:25 -08001636 if (getCurrentServingCall() == BinderCallType::HWBINDER) {
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001637 std::string vendorClient =
1638 StringPrintf("vendor.client.pid<%d>", CameraThreadState::getCallingPid());
1639 clientPackageNameAdj = String16(vendorClient.c_str());
1640 }
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001641
1642 if (oomScoreOffset < 0) {
1643 String8 msg =
1644 String8::format("Cannot increase the priority of a client %s pid %d for "
1645 "camera id %s", String8(clientPackageNameAdj).string(), callingPid,
1646 id.string());
1647 ALOGE("%s: %s", __FUNCTION__, msg.string());
1648 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
1649 }
1650
1651 // enforce system camera permissions
1652 if (oomScoreOffset > 0 &&
1653 !hasPermissionsForSystemCamera(callingPid, CameraThreadState::getCallingUid())) {
1654 String8 msg =
1655 String8::format("Cannot change the priority of a client %s pid %d for "
1656 "camera id %s without SYSTEM_CAMERA permissions",
1657 String8(clientPackageNameAdj).string(), callingPid, id.string());
1658 ALOGE("%s: %s", __FUNCTION__, msg.string());
1659 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.string());
1660 }
1661
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001662 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001663 /*api1CameraId*/-1, clientPackageNameAdj, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001664 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001665 targetSdkVersion, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001666
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001667 if(!ret.isOk()) {
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001668 logRejected(id, callingPid, String8(clientPackageNameAdj), ret.toString8());
Ruben Brunkcc776712015-02-17 20:18:47 -08001669 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001670 }
1671
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001672 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07001673 Mutex::Autolock lock(mServiceLock);
1674
1675 // Clear the previous cached logs and reposition the
1676 // file offset to beginning of the file to log new data.
1677 // If either truncate or lseek fails, close the previous file and create a new one.
1678 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
1679 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
1680 // Close the previous memfd.
1681 close(mMemFd);
1682 // If failure to wipe the data, then create a new file and
1683 // assign the new value to mMemFd.
1684 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
1685 if (mMemFd == -1) {
1686 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
1687 }
1688 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001689 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001690}
1691
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001692template<class CALLBACK, class CLIENT>
1693Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001694 int api1CameraId, const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09001695 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001696 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001697 /*out*/sp<CLIENT>& device) {
1698 binder::Status ret = binder::Status::ok();
1699
1700 String8 clientName8(clientPackageName);
1701
1702 int originalClientPid = 0;
1703
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001704 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001705 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001706 static_cast<int>(effectiveApiLevel));
1707
Shuzhen Wang316781a2020-08-18 18:11:01 -07001708 nsecs_t openTimeNs = systemTime();
1709
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001710 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001711 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07001712 int orientation = 0;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001713 bool isNdk = (clientPackageName.size() == 0);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001714 {
1715 // Acquire mServiceLock and prevent other clients from connecting
1716 std::unique_ptr<AutoConditionLock> lock =
1717 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1718
1719 if (lock == nullptr) {
1720 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
1721 , clientPid);
1722 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1723 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
1724 cameraId.string(), clientName8.string(), clientPid);
1725 }
1726
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07001727 // Enforce client permissions and do basic validity checks
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001728 if(!(ret = validateConnectLocked(cameraId, clientName8,
1729 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
1730 return ret;
1731 }
1732
1733 // Check the shim parameters after acquiring lock, if they have already been updated and
1734 // we were doing a shim update, return immediately
1735 if (shimUpdateOnly) {
1736 auto cameraState = getCameraState(cameraId);
1737 if (cameraState != nullptr) {
1738 if (!cameraState->getShimParams().isEmpty()) return ret;
1739 }
1740 }
1741
1742 status_t err;
1743
1744 sp<BasicClient> clientTmp = nullptr;
1745 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
1746 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001747 IInterface::asBinder(cameraCb), clientName8, oomScoreOffset, /*out*/&clientTmp,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001748 /*out*/&partial)) != NO_ERROR) {
1749 switch (err) {
1750 case -ENODEV:
1751 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
1752 "No camera device with ID \"%s\" currently available",
1753 cameraId.string());
1754 case -EBUSY:
1755 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1756 "Higher-priority client using camera, ID \"%s\" currently unavailable",
1757 cameraId.string());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001758 case -EUSERS:
1759 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1760 "Too many cameras already open, cannot open camera \"%s\"",
1761 cameraId.string());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001762 default:
1763 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1764 "Unexpected error %s (%d) opening camera \"%s\"",
1765 strerror(-err), err, cameraId.string());
1766 }
1767 }
1768
1769 if (clientTmp.get() != nullptr) {
1770 // Handle special case for API1 MediaRecorder where the existing client is returned
1771 device = static_cast<CLIENT*>(clientTmp.get());
1772 return ret;
1773 }
1774
1775 // give flashlight a chance to close devices if necessary.
1776 mFlashlight->prepareDeviceOpen(cameraId);
1777
Emilian Peevb91f1802021-03-23 14:50:28 -07001778 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08001779 if (facing == -1) {
1780 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string());
1781 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1782 "Unable to get camera device \"%s\" facing", cameraId.string());
1783 }
1784
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001785 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001786 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1787 mPerfClassPrimaryCameraIds, cameraId.string(), targetSdkVersion);
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08001788 if(!(ret = makeClient(this, cameraCb, clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001789 cameraId, api1CameraId, facing, orientation,
Shuzhen Wang06fcfb02018-07-30 18:23:31 -07001790 clientPid, clientUid, getpid(),
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001791 deviceVersion, effectiveApiLevel, overrideForPerfClass,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001792 /*out*/&tmp)).isOk()) {
1793 return ret;
1794 }
1795 client = static_cast<CLIENT*>(tmp.get());
1796
1797 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
1798 __FUNCTION__);
1799
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07001800 String8 monitorTags = isClientWatched(client.get()) ? mMonitorTags : String8("");
1801 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001802 if (err != OK) {
1803 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001804 // Errors could be from the HAL module open call or from AppOpsManager
1805 switch(err) {
1806 case BAD_VALUE:
1807 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1808 "Illegal argument to HAL module for camera \"%s\"", cameraId.string());
1809 case -EBUSY:
1810 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
1811 "Camera \"%s\" is already open", cameraId.string());
1812 case -EUSERS:
1813 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
1814 "Too many cameras already open, cannot open camera \"%s\"",
1815 cameraId.string());
1816 case PERMISSION_DENIED:
1817 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1818 "No permission to open camera \"%s\"", cameraId.string());
1819 case -EACCES:
1820 return STATUS_ERROR_FMT(ERROR_DISABLED,
1821 "Camera \"%s\" disabled by policy", cameraId.string());
1822 case -ENODEV:
1823 default:
1824 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1825 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
1826 strerror(-err), err);
1827 }
1828 }
1829
1830 // Update shim paremeters for legacy clients
1831 if (effectiveApiLevel == API_1) {
1832 // Assume we have always received a Client subclass for API1
1833 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
1834 String8 rawParams = shimClient->getParameters();
1835 CameraParameters params(rawParams);
1836
1837 auto cameraState = getCameraState(cameraId);
1838 if (cameraState != nullptr) {
1839 cameraState->setShimParams(params);
1840 } else {
1841 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
1842 __FUNCTION__, cameraId.string());
1843 }
1844 }
1845
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001846 // Set rotate-and-crop override behavior
1847 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
1848 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Emilian Peev5368ebf2021-10-08 17:52:18 -07001849 } else if (effectiveApiLevel == API_2) {
1850 client->setRotateAndCropOverride(CameraServiceProxyWrapper::getRotateAndCropOverride(
1851 clientPackageName, facing));
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001852 }
1853
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001854 // Set camera muting behavior
Valentin Iftimec0b8d472021-07-23 20:21:06 +02001855 bool isCameraPrivacyEnabled =
1856 mSensorPrivacyPolicy->isCameraPrivacyEnabled(multiuser_get_user_id(clientUid));
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001857 if (client->supportsCameraMute()) {
Valentin Iftimec0b8d472021-07-23 20:21:06 +02001858 client->setCameraMute(
1859 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
1860 } else if (isCameraPrivacyEnabled) {
1861 // no camera mute supported, but privacy is on! => disconnect
1862 ALOGI("Camera mute not supported for package: %s, camera id: %s",
1863 String8(client->getPackageName()).string(), cameraId.string());
1864 // Do not hold mServiceLock while disconnecting clients, but
1865 // retain the condition blocking other clients from connecting
1866 // in mServiceLockWrapper if held.
1867 mServiceLock.unlock();
1868 // Clear caller identity temporarily so client disconnect PID
1869 // checks work correctly
1870 int64_t token = CameraThreadState::clearCallingIdentity();
1871 // Note AppOp to trigger the "Unblock" dialog
1872 client->noteAppOp();
1873 client->disconnect();
1874 CameraThreadState::restoreCallingIdentity(token);
1875 // Reacquire mServiceLock
1876 mServiceLock.lock();
1877
1878 return STATUS_ERROR_FMT(ERROR_DISABLED,
1879 "Camera \"%s\" disabled due to camera mute", cameraId.string());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08001880 }
1881
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001882 if (shimUpdateOnly) {
1883 // If only updating legacy shim parameters, immediately disconnect client
1884 mServiceLock.unlock();
1885 client->disconnect();
1886 mServiceLock.lock();
1887 } else {
1888 // Otherwise, add client to active clients list
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001889 finishConnectLocked(client, partial, oomScoreOffset);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001890 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001891
1892 client->setImageDumpMask(mImageDumpMask);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001893 } // lock is destroyed, allow further connect calls
1894
1895 // Important: release the mutex here so the client can call back into the service from its
1896 // destructor (can be at the end of the call)
1897 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07001898
1899 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
1900 CameraServiceProxyWrapper::logOpen(cameraId, facing, clientPackageName,
1901 effectiveApiLevel, isNdk, openLatencyMs);
1902
Cliff Wud3a05312021-04-26 23:07:31 +08001903 {
1904 Mutex::Autolock lock(mInjectionParametersLock);
1905 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
1906 mInjectionInitPending = false;
1907 status_t res = NO_ERROR;
1908 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
1909 if (clientDescriptor != nullptr) {
1910 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
1911 res = baseClientPtr->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
1912 if (res != OK) {
1913 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
1914 }
1915 } else {
1916 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
1917 __FUNCTION__, mInjectionInternalCamId.string());
1918 res = NO_INIT;
1919 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
1920 }
1921 }
1922 }
1923
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001924 return ret;
1925}
1926
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001927status_t CameraService::addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient) {
1928 if (offlineClient.get() == nullptr) {
1929 return BAD_VALUE;
1930 }
1931
1932 {
1933 // Acquire mServiceLock and prevent other clients from connecting
1934 std::unique_ptr<AutoConditionLock> lock =
1935 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
1936
1937 if (lock == nullptr) {
1938 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
1939 , __FUNCTION__, offlineClient->getClientPid());
1940 return TIMED_OUT;
1941 }
1942
1943 auto onlineClientDesc = mActiveClientManager.get(cameraId);
1944 if (onlineClientDesc.get() == nullptr) {
1945 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
1946 cameraId.c_str());
1947 return BAD_VALUE;
1948 }
1949
1950 // Offline clients do not evict or conflict with other online devices. Resource sharing
1951 // conflicts are handled by the camera provider which will either succeed or fail before
1952 // reaching this method.
1953 const auto& onlinePriority = onlineClientDesc->getPriority();
1954 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
1955 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
1956 /*conflictingKeys*/ std::set<String8>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001957 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
1958 /*ommScoreOffset*/ 0);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001959
1960 // Allow only one offline device per camera
1961 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
1962 if (!incompatibleClients.empty()) {
1963 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
1964 return BAD_VALUE;
1965 }
1966
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07001967 String8 monitorTags = isClientWatched(offlineClient.get()) ? mMonitorTags : String8("");
1968 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08001969 if (err != OK) {
1970 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
1971 return err;
1972 }
1973
1974 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
1975 if (evicted.size() > 0) {
1976 for (auto& i : evicted) {
1977 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
1978 __FUNCTION__, i->getKey().string());
1979 }
1980
1981 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
1982 "properly", __FUNCTION__);
1983
1984 return BAD_VALUE;
1985 }
1986
1987 logConnectedOffline(offlineClientDesc->getKey(),
1988 static_cast<int>(offlineClientDesc->getOwnerId()),
1989 String8(offlineClient->getPackageName()));
1990
1991 sp<IBinder> remoteCallback = offlineClient->getRemote();
1992 if (remoteCallback != nullptr) {
1993 remoteCallback->linkToDeath(this);
1994 }
1995 } // lock is destroyed, allow further connect calls
1996
1997 return OK;
1998}
1999
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002000Status CameraService::setTorchMode(const String16& cameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002001 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002002 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002003
2004 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002005 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002006 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002007 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2008 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002009 }
2010
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002011 String8 id = String8(cameraId.string());
Jayant Chowdhary12361932018-08-27 14:46:13 -07002012 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002013
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002014 if (shouldRejectSystemCameraConnection(id)) {
2015 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
2016 " for system only device %s: ", id.string());
2017 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002018 // verify id is valid.
Ruben Brunkcc776712015-02-17 20:18:47 -08002019 auto state = getCameraState(id);
2020 if (state == nullptr) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07002021 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002022 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2023 "Camera ID \"%s\" is a not valid camera ID", id.string());
Ruben Brunkcc776712015-02-17 20:18:47 -08002024 }
2025
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002026 StatusInternal cameraStatus = state->getStatus();
2027 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002028 cameraStatus != StatusInternal::NOT_AVAILABLE) {
2029 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002030 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2031 "Camera ID \"%s\" is a not valid camera ID", id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002032 }
2033
2034 {
2035 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002036 TorchModeStatus status;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002037 status_t err = getTorchStatusLocked(id, &status);
2038 if (err != OK) {
2039 if (err == NAME_NOT_FOUND) {
2040 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
2041 "Camera \"%s\" does not have a flash unit", id.string());
2042 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002043 ALOGE("%s: getting current torch status failed for camera %s",
2044 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002045 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2046 "Error updating torch status for camera \"%s\": %s (%d)", id.string(),
2047 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002048 }
2049
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002050 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002051 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002052 ALOGE("%s: torch mode of camera %s is not available because "
2053 "camera is in use", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002054 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2055 "Torch for camera \"%s\" is not available due to an existing camera user",
2056 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002057 } else {
2058 ALOGE("%s: torch mode of camera %s is not available due to "
2059 "insufficient resources", __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002060 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2061 "Torch for camera \"%s\" is not available due to insufficient resources",
2062 id.string());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002063 }
2064 }
2065 }
2066
Ruben Brunk99e69712015-05-26 17:25:07 -07002067 {
2068 // Update UID map - this is used in the torch status changed callbacks, so must be done
2069 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002070 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -07002071 if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
2072 mTorchUidMap[id].first = uid;
2073 mTorchUidMap[id].second = uid;
2074 } else {
2075 // Set the pending UID
2076 mTorchUidMap[id].first = uid;
2077 }
2078 }
2079
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002080 status_t err = mFlashlight->setTorchMode(id, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002081
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002082 if (err != OK) {
2083 int32_t errorCode;
2084 String8 msg;
2085 switch (err) {
2086 case -ENOSYS:
2087 msg = String8::format("Camera \"%s\" has no flashlight",
2088 id.string());
2089 errorCode = ERROR_ILLEGAL_ARGUMENT;
2090 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08002091 case -EBUSY:
2092 msg = String8::format("Camera \"%s\" is in use",
2093 id.string());
2094 errorCode = ERROR_CAMERA_IN_USE;
2095 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002096 default:
2097 msg = String8::format(
2098 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
2099 id.string(), enabled, strerror(-err), err);
2100 errorCode = ERROR_INVALID_OPERATION;
2101 }
2102 ALOGE("%s: %s", __FUNCTION__, msg.string());
Rucha Katakward9ea6452021-05-06 11:57:16 -07002103 logServiceError(msg,errorCode);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002104 return STATUS_ERROR(errorCode, msg.string());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002105 }
2106
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002107 {
2108 // update the link to client's death
2109 Mutex::Autolock al(mTorchClientMapMutex);
2110 ssize_t index = mTorchClientMap.indexOfKey(id);
2111 if (enabled) {
2112 if (index == NAME_NOT_FOUND) {
2113 mTorchClientMap.add(id, clientBinder);
2114 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07002115 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002116 mTorchClientMap.replaceValueAt(index, clientBinder);
2117 }
2118 clientBinder->linkToDeath(this);
2119 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07002120 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002121 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002122 }
2123
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002124 int clientPid = CameraThreadState::getCallingPid();
2125 const char *id_cstr = id.c_str();
2126 const char *torchState = enabled ? "on" : "off";
2127 ALOGI("Torch for camera id %s turned %s for client PID %d", id_cstr, torchState, clientPid);
2128 logTorchEvent(id_cstr, torchState , clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002129 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002130}
2131
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002132Status CameraService::notifySystemEvent(int32_t eventId,
2133 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002134 const int pid = CameraThreadState::getCallingPid();
2135 const int selfPid = getpid();
2136
2137 // Permission checks
2138 if (pid != selfPid) {
2139 // Ensure we're being called by system_server, or similar process with
2140 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002141 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002142 const int uid = CameraThreadState::getCallingUid();
2143 ALOGE("Permission Denial: cannot send updates to camera service about system"
2144 " events from pid=%d, uid=%d", pid, uid);
2145 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09002146 "No permission to send updates to camera service about system events"
2147 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002148 }
2149 }
2150
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002151 ATRACE_CALL();
2152
Ruben Brunk36597b22015-03-20 22:15:57 -07002153 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002154 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002155 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002156 // from a system server crash
2157 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002158 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002159 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002160 break;
2161 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002162 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002163 default: {
2164 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2165 eventId);
2166 break;
2167 }
2168 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002169 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002170}
2171
Emilian Peev53722fa2019-02-22 17:47:20 -08002172void CameraService::notifyMonitoredUids() {
2173 Mutex::Autolock lock(mStatusListenerLock);
2174
2175 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002176 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Emilian Peev53722fa2019-02-22 17:47:20 -08002177 if (!ret.isOk()) {
2178 ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
2179 ret.exceptionCode());
2180 }
2181 }
2182}
2183
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002184Status CameraService::notifyDeviceStateChange(int64_t newState) {
2185 const int pid = CameraThreadState::getCallingPid();
2186 const int selfPid = getpid();
2187
2188 // Permission checks
2189 if (pid != selfPid) {
2190 // Ensure we're being called by system_server, or similar process with
2191 // permissions to notify the camera service about system events
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002192 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002193 const int uid = CameraThreadState::getCallingUid();
2194 ALOGE("Permission Denial: cannot send updates to camera service about device"
2195 " state changes from pid=%d, uid=%d", pid, uid);
2196 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2197 "No permission to send updates to camera service about device state"
2198 " changes from pid=%d, uid=%d", pid, uid);
2199 }
2200 }
2201
2202 ATRACE_CALL();
2203
2204 using hardware::camera::provider::V2_5::DeviceState;
2205 hardware::hidl_bitfield<DeviceState> newDeviceState{};
2206 if (newState & ICameraService::DEVICE_STATE_BACK_COVERED) {
2207 newDeviceState |= DeviceState::BACK_COVERED;
2208 }
2209 if (newState & ICameraService::DEVICE_STATE_FRONT_COVERED) {
2210 newDeviceState |= DeviceState::FRONT_COVERED;
2211 }
2212 if (newState & ICameraService::DEVICE_STATE_FOLDED) {
2213 newDeviceState |= DeviceState::FOLDED;
2214 }
2215 // Only map vendor bits directly
2216 uint64_t vendorBits = static_cast<uint64_t>(newState) & 0xFFFFFFFF00000000l;
2217 newDeviceState |= vendorBits;
2218
2219 ALOGV("%s: New device state 0x%" PRIx64, __FUNCTION__, newDeviceState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002220 mCameraProviderManager->notifyDeviceStateChange(newDeviceState);
2221
2222 return Status::ok();
2223}
2224
Emilian Peev8b64f282021-03-25 16:49:57 -07002225Status CameraService::notifyDisplayConfigurationChange() {
2226 ATRACE_CALL();
2227 const int callingPid = CameraThreadState::getCallingPid();
2228 const int selfPid = getpid();
2229
2230 // Permission checks
2231 if (callingPid != selfPid) {
2232 // Ensure we're being called by system_server, or similar process with
2233 // permissions to notify the camera service about system events
2234 if (!checkCallingPermission(sCameraSendSystemEventsPermission)) {
2235 const int uid = CameraThreadState::getCallingUid();
2236 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2237 " changes from pid=%d, uid=%d", callingPid, uid);
2238 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2239 "No permission to send updates to camera service about orientation"
2240 " changes from pid=%d, uid=%d", callingPid, uid);
2241 }
2242 }
2243
2244 Mutex::Autolock lock(mServiceLock);
2245
2246 // Don't do anything if rotate-and-crop override via cmd is active
2247 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2248
2249 const auto clients = mActiveClientManager.getAll();
2250 for (auto& current : clients) {
2251 if (current != nullptr) {
2252 const auto basicClient = current->getValue();
Emilian Peeve23f1d92021-09-20 14:56:01 -07002253 if (basicClient.get() != nullptr && basicClient->canCastToApiClient(API_2)) {
Emilian Peev5368ebf2021-10-08 17:52:18 -07002254 basicClient->setRotateAndCropOverride(
2255 CameraServiceProxyWrapper::getRotateAndCropOverride(
2256 basicClient->getPackageName(), basicClient->getCameraFacing()));
Emilian Peev8b64f282021-03-25 16:49:57 -07002257 }
2258 }
2259 }
2260
2261 return Status::ok();
2262}
2263
2264Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002265 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2266 ATRACE_CALL();
2267 if (!concurrentCameraIds) {
2268 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2269 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2270 }
2271
2272 if (!mInitialized) {
2273 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002274 logServiceError(String8::format("Camera subsystem is not available"),ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002275 return STATUS_ERROR(ERROR_DISCONNECTED,
2276 "Camera subsystem is not available");
2277 }
2278 // First call into the provider and get the set of concurrent camera
2279 // combinations
2280 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002281 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002282 for (auto &combination : concurrentCameraCombinations) {
2283 std::vector<std::string> validCombination;
2284 for (auto &cameraId : combination) {
2285 // if the camera state is not present, skip
2286 String8 cameraIdStr(cameraId.c_str());
2287 auto state = getCameraState(cameraIdStr);
2288 if (state == nullptr) {
2289 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2290 continue;
2291 }
2292 StatusInternal status = state->getStatus();
2293 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2294 continue;
2295 }
2296 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
2297 continue;
2298 }
2299 validCombination.push_back(cameraId);
2300 }
2301 if (validCombination.size() != 0) {
2302 concurrentCameraIds->push_back(std::move(validCombination));
2303 }
2304 }
2305 return Status::ok();
2306}
2307
2308Status CameraService::isConcurrentSessionConfigurationSupported(
2309 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002310 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002311 if (!isSupported) {
2312 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2313 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2314 }
2315
2316 if (!mInitialized) {
2317 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2318 return STATUS_ERROR(ERROR_DISCONNECTED,
2319 "Camera subsystem is not available");
2320 }
2321
2322 // Check for camera permissions
2323 int callingPid = CameraThreadState::getCallingPid();
2324 int callingUid = CameraThreadState::getCallingUid();
2325 if ((callingPid != getpid()) && !checkPermission(sCameraPermission, callingPid, callingUid)) {
2326 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2327 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2328 "android.permission.CAMERA needed to call"
2329 "isConcurrentSessionConfigurationSupported");
2330 }
2331
2332 status_t res =
2333 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002334 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
2335 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002336 if (res != OK) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07002337 logServiceError(String8::format("Unable to query session configuration support"),
2338 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002339 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2340 "support %s (%d)", strerror(-res), res);
2341 }
2342 return Status::ok();
2343}
2344
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002345Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2346 /*out*/
2347 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002348 return addListenerHelper(listener, cameraStatuses);
2349}
2350
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002351binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2352 std::vector<hardware::CameraStatus>* cameraStatuses) {
2353 return addListenerHelper(listener, cameraStatuses, false, true);
2354}
2355
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002356Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2357 /*out*/
2358 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002359 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002360
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002361 ATRACE_CALL();
2362
Igor Murashkinbfc99152013-02-27 12:55:20 -08002363 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002364
Ruben Brunk3450ba72015-06-16 11:00:37 -07002365 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002366 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002367 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002368 }
2369
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002370 auto clientUid = CameraThreadState::getCallingUid();
2371 auto clientPid = CameraThreadState::getCallingPid();
Shuzhen Wang695044d2020-03-06 09:02:23 -08002372 bool openCloseCallbackAllowed = checkPermission(sCameraOpenCloseListenerPermission,
Jayant Chowdharyc3198c32021-07-28 20:59:14 +00002373 clientPid, clientUid, /*logPermissionFailure*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002374
Igor Murashkinbfc99152013-02-27 12:55:20 -08002375 Mutex::Autolock lock(mServiceLock);
2376
Ruben Brunkcc776712015-02-17 20:18:47 -08002377 {
2378 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002379 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002380 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002381 ALOGW("%s: Tried to add listener %p which was already subscribed",
2382 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002383 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002384 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002385 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002386
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002387 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002388 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2389 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002390 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08002391 if (ret != NO_ERROR) {
2392 String8 msg = String8::format("Failed to initialize service listener: %s (%d)",
2393 strerror(-ret), ret);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002394 logServiceError(msg,ERROR_ILLEGAL_ARGUMENT);
Emilian Peev53722fa2019-02-22 17:47:20 -08002395 ALOGE("%s: %s", __FUNCTION__, msg.string());
2396 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
2397 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002398 // The listener still needs to be added to the list of listeners, regardless of what
2399 // permissions the listener process has / whether it is a vendor listener. Since it might be
2400 // eligible to listen to other camera ids.
2401 mListenerList.emplace_back(serviceListener);
Emilian Peev53722fa2019-02-22 17:47:20 -08002402 mUidPolicy->registerMonitorUid(clientUid);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002403 }
2404
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002405 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002406 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002407 Mutex::Autolock lock(mCameraStatesLock);
2408 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002409 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07002410 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
2411 openCloseCallbackAllowed ? i.second->getClientPackage() : String8::empty());
Igor Murashkincba2c162013-03-20 15:56:31 -07002412 }
2413 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002414 // Remove the camera statuses that should be hidden from the client, we do
2415 // this after collecting the states in order to avoid holding
2416 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
2417 // the same time.
2418 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
2419 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
2420 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
2421 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
2422 ALOGE("%s: Invalid camera id %s, skipping status update",
2423 __FUNCTION__, s.cameraId.c_str());
2424 return true;
2425 }
2426 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
2427 clientUid);}), cameraStatuses->end());
2428
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002429 //cameraStatuses will have non-eligible camera ids removed.
2430 std::set<String16> idsChosenForCallback;
2431 for (const auto &s : *cameraStatuses) {
2432 idsChosenForCallback.insert(String16(s.cameraId));
2433 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002434
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002435 /*
2436 * Immediately signal current torch status to this listener only
2437 * This may be a subset of all the devices, so don't include it in the response directly
2438 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002439 {
2440 Mutex::Autolock al(mTorchStatusMutex);
2441 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002442 String16 id = String16(mTorchStatusMap.keyAt(i).string());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002443 // The camera id is visible to the client. Fine to send torch
2444 // callback.
2445 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
2446 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
2447 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002448 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002449 }
2450
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002451 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08002452}
Ruben Brunkcc776712015-02-17 20:18:47 -08002453
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002454Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002455 ATRACE_CALL();
2456
Igor Murashkinbfc99152013-02-27 12:55:20 -08002457 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
2458
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002459 if (listener == 0) {
2460 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002461 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002462 }
2463
Igor Murashkinbfc99152013-02-27 12:55:20 -08002464 Mutex::Autolock lock(mServiceLock);
2465
Ruben Brunkcc776712015-02-17 20:18:47 -08002466 {
2467 Mutex::Autolock lock(mStatusListenerLock);
2468 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002469 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
2470 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
2471 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08002472 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002473 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002474 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002475 }
2476 }
2477
2478 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
2479 __FUNCTION__, listener.get());
2480
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002481 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08002482}
2483
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002484Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002485
2486 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002487 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
2488
2489 if (parameters == NULL) {
2490 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002491 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07002492 }
2493
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002494 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002495
2496 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002497 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07002498 // Error logged by caller
2499 return ret;
2500 }
2501
2502 String8 shimParamsString8 = shimParams.flatten();
2503 String16 shimParamsString16 = String16(shimParamsString8);
2504
2505 *parameters = shimParamsString16;
2506
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002507 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07002508}
2509
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002510Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion,
2511 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002512 ATRACE_CALL();
2513
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002514 const String8 id = String8(cameraId);
2515
2516 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002517
2518 switch (apiVersion) {
2519 case API_VERSION_1:
2520 case API_VERSION_2:
2521 break;
2522 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002523 String8 msg = String8::format("Unknown API version %d", apiVersion);
2524 ALOGE("%s: %s", __FUNCTION__, msg.string());
2525 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002526 }
2527
Emilian Peev28ad2ea2017-02-07 16:14:32 +00002528 int deviceVersion = getDeviceVersion(id);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002529 switch (deviceVersion) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002530 case CAMERA_DEVICE_API_VERSION_1_0:
2531 case CAMERA_DEVICE_API_VERSION_3_0:
2532 case CAMERA_DEVICE_API_VERSION_3_1:
2533 if (apiVersion == API_VERSION_2) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002534 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim",
2535 __FUNCTION__, id.string(), deviceVersion);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002536 *isSupported = false;
2537 } else { // if (apiVersion == API_VERSION_1) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002538 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported",
2539 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002540 *isSupported = true;
2541 }
2542 break;
2543 case CAMERA_DEVICE_API_VERSION_3_2:
2544 case CAMERA_DEVICE_API_VERSION_3_3:
Zhijun He4afbdec2016-05-04 15:42:51 -07002545 case CAMERA_DEVICE_API_VERSION_3_4:
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002546 case CAMERA_DEVICE_API_VERSION_3_5:
Yin-Chia Yeh56d98ba2020-01-16 16:57:14 -08002547 case CAMERA_DEVICE_API_VERSION_3_6:
Shuzhen Wang83bff122020-11-20 15:51:39 -08002548 case CAMERA_DEVICE_API_VERSION_3_7:
Shuzhen Wang90708ea2021-11-04 11:40:49 -07002549 case CAMERA_DEVICE_API_VERSION_3_8:
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002550 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
2551 __FUNCTION__, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002552 *isSupported = true;
2553 break;
2554 case -1: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002555 String8 msg = String8::format("Unknown camera ID %s", id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002556 ALOGE("%s: %s", __FUNCTION__, msg.string());
2557 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string());
Igor Murashkin65d14b92014-06-17 12:03:20 -07002558 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002559 default: {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002560 String8 msg = String8::format("Unknown device version %x for device %s",
2561 deviceVersion, id.string());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002562 ALOGE("%s: %s", __FUNCTION__, msg.string());
2563 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string());
2564 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07002565 }
2566
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002567 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07002568}
2569
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07002570Status CameraService::isHiddenPhysicalCamera(const String16& cameraId,
2571 /*out*/ bool *isSupported) {
2572 ATRACE_CALL();
2573
2574 const String8 id = String8(cameraId);
2575
2576 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string());
2577 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(id.string());
2578
2579 return Status::ok();
2580}
2581
Cliff Wud8cae102021-03-11 01:37:42 +08002582Status CameraService::injectCamera(
2583 const String16& packageName, const String16& internalCamId,
2584 const String16& externalCamId,
2585 const sp<ICameraInjectionCallback>& callback,
2586 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08002587 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08002588 ATRACE_CALL();
2589
2590 if (!checkCallingPermission(sCameraInjectExternalCameraPermission)) {
2591 const int pid = CameraThreadState::getCallingPid();
2592 const int uid = CameraThreadState::getCallingUid();
2593 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
2594 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2595 "Permission Denial: no permission to inject camera");
2596 }
2597
2598 ALOGV(
2599 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
2600 "%s",
2601 __FUNCTION__, String8(packageName).string(),
2602 String8(internalCamId).string(), String8(externalCamId).string());
2603
Cliff Wud3a05312021-04-26 23:07:31 +08002604 {
2605 Mutex::Autolock lock(mInjectionParametersLock);
2606 mInjectionInternalCamId = String8(internalCamId);
2607 mInjectionExternalCamId = String8(externalCamId);
2608 status_t res = NO_ERROR;
2609 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2610 // If the client already exists, we can directly connect to the camera device through the
2611 // client's injectCamera(), otherwise we need to wait until the client is established
2612 // (execute connectHelper()) before injecting the camera to the camera device.
2613 if (clientDescriptor != nullptr) {
2614 mInjectionInitPending = false;
2615 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
2616 res = baseClientPtr->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
2617 if(res != OK) {
2618 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2619 }
2620 } else {
2621 mInjectionInitPending = true;
2622 }
2623 }
Cliff Wud8cae102021-03-11 01:37:42 +08002624 mInjectionStatusListener->addListener(callback);
2625 *cameraInjectionSession = new CameraInjectionSession(this);
2626
Cliff Wud3a05312021-04-26 23:07:31 +08002627 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08002628}
2629
Ruben Brunkcc776712015-02-17 20:18:47 -08002630void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07002631 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002632 for (auto& i : mActiveClientManager.getAll()) {
2633 auto clientSp = i->getValue();
2634 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002635 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08002636 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08002637 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07002638 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07002639 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08002640}
2641
Ruben Brunkcc776712015-02-17 20:18:47 -08002642bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002643 bool ret = false;
2644 {
2645 // Acquire mServiceLock and prevent other clients from connecting
2646 std::unique_ptr<AutoConditionLock> lock =
2647 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08002648
Igor Murashkin634a5152013-02-20 17:15:11 -08002649
Ruben Brunkcc776712015-02-17 20:18:47 -08002650 std::vector<sp<BasicClient>> evicted;
2651 for (auto& i : mActiveClientManager.getAll()) {
2652 auto clientSp = i->getValue();
2653 if (clientSp.get() == nullptr) {
2654 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2655 mActiveClientManager.remove(i);
2656 continue;
2657 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08002658 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002659 mActiveClientManager.remove(i);
2660 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08002661
Ruben Brunkcc776712015-02-17 20:18:47 -08002662 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002663 clientSp->notifyError(
2664 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002665 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08002666 }
2667 }
2668
Ruben Brunkcc776712015-02-17 20:18:47 -08002669 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2670 // other clients from connecting in mServiceLockWrapper if held
2671 mServiceLock.unlock();
2672
Ruben Brunk36597b22015-03-20 22:15:57 -07002673 // Do not clear caller identity, remote caller should be client proccess
2674
Ruben Brunkcc776712015-02-17 20:18:47 -08002675 for (auto& i : evicted) {
2676 if (i.get() != nullptr) {
2677 i->disconnect();
2678 ret = true;
2679 }
Igor Murashkin634a5152013-02-20 17:15:11 -08002680 }
2681
Ruben Brunkcc776712015-02-17 20:18:47 -08002682 // Reacquire mServiceLock
2683 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08002684
Ruben Brunkcc776712015-02-17 20:18:47 -08002685 } // lock is destroyed, allow further connect calls
2686
2687 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07002688}
2689
Ruben Brunkcc776712015-02-17 20:18:47 -08002690std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
2691 const String8& cameraId) const {
2692 std::shared_ptr<CameraState> state;
2693 {
2694 Mutex::Autolock lock(mCameraStatesLock);
2695 auto iter = mCameraStates.find(cameraId);
2696 if (iter != mCameraStates.end()) {
2697 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002698 }
2699 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002700 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002701}
2702
Ruben Brunkcc776712015-02-17 20:18:47 -08002703sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
2704 // Remove from active clients list
2705 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
2706 if (clientDescriptorPtr == nullptr) {
2707 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
2708 cameraId.string());
2709 return sp<BasicClient>{nullptr};
2710 }
2711
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002712 sp<BasicClient> client = clientDescriptorPtr->getValue();
2713 if (client.get() != nullptr) {
2714 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
2715 }
2716 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07002717}
2718
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002719void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07002720 // Acquire mServiceLock and prevent other clients from connecting
2721 std::unique_ptr<AutoConditionLock> lock =
2722 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
2723
Ruben Brunk6267b532015-04-30 17:44:07 -07002724 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002725 for (size_t i = 0; i < newUserIds.size(); i++) {
2726 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002727 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002728 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07002729 return;
2730 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002731 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07002732 }
2733
Ruben Brunka8ca9152015-04-07 14:23:40 -07002734
Ruben Brunk6267b532015-04-30 17:44:07 -07002735 if (newAllowedUsers == mAllowedUsers) {
2736 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
2737 return;
2738 }
2739
2740 logUserSwitch(mAllowedUsers, newAllowedUsers);
2741
2742 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07002743
2744 // Current user has switched, evict all current clients.
2745 std::vector<sp<BasicClient>> evicted;
2746 for (auto& i : mActiveClientManager.getAll()) {
2747 auto clientSp = i->getValue();
2748
2749 if (clientSp.get() == nullptr) {
2750 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
2751 continue;
2752 }
2753
Ruben Brunk6267b532015-04-30 17:44:07 -07002754 // Don't evict clients that are still allowed.
2755 uid_t clientUid = clientSp->getClientUid();
2756 userid_t clientUserId = multiuser_get_user_id(clientUid);
2757 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
2758 continue;
2759 }
2760
Ruben Brunk36597b22015-03-20 22:15:57 -07002761 evicted.push_back(clientSp);
2762
2763 String8 curTime = getFormattedCurrentTime();
2764
2765 ALOGE("Evicting conflicting client for camera ID %s due to user change",
2766 i->getKey().string());
Ruben Brunka8ca9152015-04-07 14:23:40 -07002767
Ruben Brunk36597b22015-03-20 22:15:57 -07002768 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002769 logEvent(String8::format("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00002770 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
2771 " to user switch.", i->getKey().string(),
2772 String8{clientSp->getPackageName()}.string(),
2773 i->getOwnerId(), i->getPriority().getScore(),
2774 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07002775
2776 }
2777
2778 // Do not hold mServiceLock while disconnecting clients, but retain the condition
2779 // blocking other clients from connecting in mServiceLockWrapper if held.
2780 mServiceLock.unlock();
2781
2782 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002783 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07002784
2785 for (auto& i : evicted) {
2786 i->disconnect();
2787 }
2788
Jayant Chowdhary12361932018-08-27 14:46:13 -07002789 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07002790
2791 // Reacquire mServiceLock
2792 mServiceLock.lock();
2793}
Ruben Brunkcc776712015-02-17 20:18:47 -08002794
Ruben Brunka8ca9152015-04-07 14:23:40 -07002795void CameraService::logEvent(const char* event) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002796 String8 curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07002797 Mutex::Autolock l(mLogLock);
Rucha Katakward9ea6452021-05-06 11:57:16 -07002798 String8 msg = String8::format("%s : %s", curTime.string(), event);
2799 // For service error events, print the msg only once.
2800 if(!msg.contains("SERVICE ERROR")) {
2801 mEventLog.add(msg);
2802 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
2803 // Error event not added to the dumpsys log before
2804 mEventLog.add(msg);
2805 sServiceErrorEventSet.insert(msg);
2806 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002807}
2808
Ruben Brunka8ca9152015-04-07 14:23:40 -07002809void CameraService::logDisconnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002810 const char* clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002811 // Log the clients evicted
Ruben Brunka8ca9152015-04-07 14:23:40 -07002812 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002813 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002814}
2815
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002816void CameraService::logDisconnectedOffline(const char* cameraId, int clientPid,
2817 const char* clientPackage) {
2818 // Log the clients evicted
2819 logEvent(String8::format("DISCONNECT offline device %s client for package %s (PID %d)",
2820 cameraId, clientPackage, clientPid));
2821}
2822
Ruben Brunka8ca9152015-04-07 14:23:40 -07002823void CameraService::logConnected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002824 const char* clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002825 // Log the clients evicted
2826 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002827 clientPackage, clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002828}
2829
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002830void CameraService::logConnectedOffline(const char* cameraId, int clientPid,
2831 const char* clientPackage) {
2832 // Log the clients evicted
2833 logEvent(String8::format("CONNECT offline device %s client for package %s (PID %d)", cameraId,
2834 clientPackage, clientPid));
2835}
2836
Ruben Brunka8ca9152015-04-07 14:23:40 -07002837void CameraService::logRejected(const char* cameraId, int clientPid,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002838 const char* clientPackage, const char* reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07002839 // Log the client rejected
2840 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002841 cameraId, clientPackage, clientPid, reason));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002842}
2843
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002844void CameraService::logTorchEvent(const char* cameraId, const char *torchState, int clientPid) {
2845 // Log torch event
2846 logEvent(String8::format("Torch for camera id %s turned %s for client PID %d", cameraId,
2847 torchState, clientPid));
2848}
2849
Ruben Brunk6267b532015-04-30 17:44:07 -07002850void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
2851 const std::set<userid_t>& newUserIds) {
2852 String8 newUsers = toString(newUserIds);
2853 String8 oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002854 if (oldUsers.size() == 0) {
2855 oldUsers = "<None>";
2856 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07002857 // Log the new and old users
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08002858 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
Ruben Brunk6267b532015-04-30 17:44:07 -07002859 oldUsers.string(), newUsers.string()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07002860}
2861
2862void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
2863 // Log the device removal
2864 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
2865}
2866
2867void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
2868 // Log the device removal
2869 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
2870}
2871
2872void CameraService::logClientDied(int clientPid, const char* reason) {
2873 // Log the device removal
2874 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
Igor Murashkinecf17e82012-10-02 16:05:11 -07002875}
2876
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002877void CameraService::logServiceError(const char* msg, int errorCode) {
2878 String8 curTime = getFormattedCurrentTime();
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08002879 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07002880}
2881
Ruben Brunk36597b22015-03-20 22:15:57 -07002882status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
2883 uint32_t flags) {
2884
Mathias Agopian65ab4712010-07-14 17:59:35 -07002885 // Permission checks
2886 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08002887 case SHELL_COMMAND_TRANSACTION: {
2888 int in = data.readFileDescriptor();
2889 int out = data.readFileDescriptor();
2890 int err = data.readFileDescriptor();
2891 int argc = data.readInt32();
2892 Vector<String16> args;
2893 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
2894 args.add(data.readString16());
2895 }
2896 sp<IBinder> unusedCallback;
2897 sp<IResultReceiver> resultReceiver;
2898 status_t status;
2899 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
2900 return status;
2901 }
2902 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
2903 return status;
2904 }
2905 status = shellCommand(in, out, err, args);
2906 if (resultReceiver != nullptr) {
2907 resultReceiver->send(status);
2908 }
2909 return NO_ERROR;
2910 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002911 }
2912
2913 return BnCameraService::onTransact(code, data, reply, flags);
2914}
2915
Mathias Agopian65ab4712010-07-14 17:59:35 -07002916// We share the media players for shutter and recording sound for all clients.
2917// A reference count is kept to determine when we will actually release the
2918// media players.
2919
Jaekyun Seokef498052018-03-23 13:09:44 +09002920sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
2921 sp<MediaPlayer> mp = new MediaPlayer();
2922 status_t error;
2923 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08002924 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09002925 error = mp->prepare();
2926 }
2927 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00002928 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09002929 mp->disconnect();
2930 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002931 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002932 }
2933 return mp;
2934}
2935
username5755fea2018-12-27 09:48:08 +08002936void CameraService::increaseSoundRef() {
2937 Mutex::Autolock lock(mSoundLock);
2938 mSoundRef++;
2939}
2940
2941void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002942 ATRACE_CALL();
2943
username5755fea2018-12-27 09:48:08 +08002944 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
2945 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
2946 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
2947 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
2948 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
2949 }
2950 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
2951 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
2952 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
2953 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002954 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08002955 }
2956 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
2957 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
2958 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
2959 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
2960 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09002961 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002962}
2963
username5755fea2018-12-27 09:48:08 +08002964void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002965 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002966 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002967 if (--mSoundRef) return;
2968
2969 for (int i = 0; i < NUM_SOUNDS; i++) {
2970 if (mSoundPlayer[i] != 0) {
2971 mSoundPlayer[i]->disconnect();
2972 mSoundPlayer[i].clear();
2973 }
2974 }
2975}
2976
2977void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002978 ATRACE_CALL();
2979
Mathias Agopian65ab4712010-07-14 17:59:35 -07002980 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07002981 if (kind < 0 || kind >= NUM_SOUNDS) {
2982 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
2983 return;
2984 }
2985
Mathias Agopian65ab4712010-07-14 17:59:35 -07002986 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08002987 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002988 sp<MediaPlayer> player = mSoundPlayer[kind];
2989 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08002990 player->seekTo(0);
2991 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002992 }
2993}
2994
2995// ----------------------------------------------------------------------------
2996
2997CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07002998 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00002999 const String16& clientPackageName,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003000 const std::optional<String16>& clientFeatureId,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003001 const String8& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003002 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003003 int clientPid, uid_t clientUid,
3004 int servicePid) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003005 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003006 IInterface::asBinder(cameraClient),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003007 clientPackageName, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003008 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003009 clientPid, clientUid,
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003010 servicePid),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003011 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003012{
Jayant Chowdhary12361932018-08-27 14:46:13 -07003013 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003014 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003015
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003016 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003017
username5755fea2018-12-27 09:48:08 +08003018 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003019
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003020 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003021}
3022
Mathias Agopian65ab4712010-07-14 17:59:35 -07003023// tear down the client
3024CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003025 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08003026 mDestructionStarted = true;
3027
username5755fea2018-12-27 09:48:08 +08003028 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003029 // unconditionally disconnect. function is idempotent
3030 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003031}
3032
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003033sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
3034
Igor Murashkin634a5152013-02-20 17:15:11 -08003035CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003036 const sp<IBinder>& remoteCallback,
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003037 const String16& clientPackageName, const std::optional<String16>& clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003038 const String8& cameraIdStr, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003039 int clientPid, uid_t clientUid,
3040 int servicePid):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003041 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07003042 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jooyung Hanb3f7cd22020-01-23 12:27:18 +09003043 mClientPackageName(clientPackageName), mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003044 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003045 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07003046 mDisconnected(false), mUidIsTrusted(false),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003047 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003048 mRemoteBinder(remoteCallback),
3049 mOpsActive(false),
3050 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08003051{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003052 if (sCameraService == nullptr) {
3053 sCameraService = cameraService;
3054 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08003055
3056 // In some cases the calling code has no access to the package it runs under.
3057 // For example, NDK camera API.
3058 // In this case we will get the packages for the calling UID and pick the first one
3059 // for attributing the app op. This will work correctly for runtime permissions
3060 // as for legacy apps we will toggle the app op for all packages in the UID.
3061 // The caveat is that the operation may be attributed to the wrong package and
3062 // stats based on app ops may be slightly off.
3063 if (mClientPackageName.size() <= 0) {
3064 sp<IServiceManager> sm = defaultServiceManager();
3065 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName));
3066 if (binder == 0) {
3067 ALOGE("Cannot get permission service");
3068 // Leave mClientPackageName unchanged (empty) and the further interaction
3069 // with camera will fail in BasicClient::startCameraOps
3070 return;
3071 }
3072
3073 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
3074 Vector<String16> packages;
3075
3076 permCtrl->getPackagesForUid(mClientUid, packages);
3077
3078 if (packages.isEmpty()) {
3079 ALOGE("No packages for calling UID");
3080 // Leave mClientPackageName unchanged (empty) and the further interaction
3081 // with camera will fail in BasicClient::startCameraOps
3082 return;
3083 }
3084 mClientPackageName = packages[0];
3085 }
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003086 if (getCurrentServingCall() != BinderCallType::HWBINDER) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003087 mAppOpsManager = std::make_unique<AppOpsManager>();
3088 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07003089
3090 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08003091}
3092
3093CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003094 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08003095 mDestructionStarted = true;
3096}
3097
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003098binder::Status CameraService::BasicClient::disconnect() {
3099 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003100 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003101 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07003102 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07003103 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08003104
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003105 sCameraService->removeByClient(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003106 sCameraService->logDisconnected(mCameraIdStr, mClientPid, String8(mClientPackageName));
Peter Kalauskasa29c1352018-10-10 12:05:42 -07003107 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
3108 mCameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003109
3110 sp<IBinder> remote = getRemote();
3111 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003112 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08003113 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003114
3115 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07003116 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003117 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
3118 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(),
3119 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003120
Igor Murashkincba2c162013-03-20 15:56:31 -07003121 // client shouldn't be able to call into us anymore
3122 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003123
3124 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08003125}
3126
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003127status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
3128 // No dumping of clients directly over Binder,
3129 // must go through CameraService::dump
3130 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003131 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003132 return OK;
3133}
3134
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07003135status_t CameraService::BasicClient::startWatchingTags(const String8&, int) {
3136 // Can't watch tags directly, must go through CameraService::startWatchingTags
3137 return OK;
3138}
3139
3140status_t CameraService::BasicClient::stopWatchingTags(int) {
3141 // Can't watch tags directly, must go through CameraService::stopWatchingTags
3142 return OK;
3143}
3144
3145status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
3146 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
3147 return OK;
3148}
3149
Ruben Brunkcc776712015-02-17 20:18:47 -08003150String16 CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003151 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08003152}
3153
Emilian Peev8b64f282021-03-25 16:49:57 -07003154int CameraService::BasicClient::getCameraFacing() const {
3155 return mCameraFacing;
3156}
3157
3158int CameraService::BasicClient::getCameraOrientation() const {
3159 return mOrientation;
3160}
Ruben Brunkcc776712015-02-17 20:18:47 -08003161
3162int CameraService::BasicClient::getClientPid() const {
3163 return mClientPid;
3164}
3165
Ruben Brunk6267b532015-04-30 17:44:07 -07003166uid_t CameraService::BasicClient::getClientUid() const {
3167 return mClientUid;
3168}
3169
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003170bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
3171 // Defaults to API2.
3172 return level == API_2;
3173}
3174
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003175status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003176 {
3177 Mutex::Autolock l(mAudioRestrictionLock);
3178 mAudioRestriction = mode;
3179 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003180 sCameraService->updateAudioRestriction();
3181 return OK;
3182}
3183
3184int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003185 return sCameraService->updateAudioRestriction();
3186}
3187
3188int32_t CameraService::BasicClient::getAudioRestriction() const {
3189 Mutex::Autolock l(mAudioRestrictionLock);
3190 return mAudioRestriction;
3191}
3192
3193bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
3194 switch (mode) {
3195 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
3196 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
3197 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
3198 return true;
3199 default:
3200 return false;
3201 }
3202}
3203
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003204status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
3205 if (mode == AppOpsManager::MODE_ERRORED) {
3206 ALOGI("Camera %s: Access for \"%s\" has been revoked",
3207 mCameraIdStr.string(), String8(mClientPackageName).string());
3208 return PERMISSION_DENIED;
3209 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
3210 // If the calling Uid is trusted (a native service), the AppOpsManager could
3211 // return MODE_IGNORED. Do not treat such case as error.
3212 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
3213 mClientPackageName);
3214 bool isCameraPrivacyEnabled =
3215 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3216 multiuser_get_user_id(mClientUid));
3217 if (!isUidActive || !isCameraPrivacyEnabled) {
3218 ALOGI("Camera %s: Access for \"%s\" has been restricted",
3219 mCameraIdStr.string(), String8(mClientPackageName).string());
3220 // Return the same error as for device policy manager rejection
3221 return -EACCES;
3222 }
3223 }
3224 return OK;
3225}
3226
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003227status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003228 ATRACE_CALL();
3229
Igor Murashkine6800ce2013-03-04 17:25:57 -08003230 {
3231 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003232 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003233 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003234 if (mAppOpsManager != nullptr) {
3235 // Notify app ops that the camera is not available
3236 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003237 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
3238 mClientPackageName, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003239
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003240 // Just check for camera acccess here on open - delay startOp until
3241 // camera frames start streaming in startCameraStreamingOps
3242 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
3243 mClientPackageName);
3244 status_t res = handleAppOpMode(mode);
3245 if (res != OK) {
3246 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003247 }
Svetoslav28e8ef72015-05-11 19:21:31 -07003248 }
3249
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003250 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003251
3252 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003253 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003254
Emilian Peev53722fa2019-02-22 17:47:20 -08003255 sCameraService->mUidPolicy->registerMonitorUid(mClientUid);
3256
Shuzhen Wang695044d2020-03-06 09:02:23 -08003257 // Notify listeners of camera open/close status
3258 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
3259
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003260 return OK;
3261}
3262
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003263status_t CameraService::BasicClient::startCameraStreamingOps() {
3264 ATRACE_CALL();
3265
3266 if (!mOpsActive) {
3267 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3268 return INVALID_OPERATION;
3269 }
3270 if (mOpsStreaming) {
3271 ALOGV("%s: Streaming already active!", __FUNCTION__);
3272 return OK;
3273 }
3274
3275 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
3276 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3277
3278 if (mAppOpsManager != nullptr) {
3279 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
3280 mClientPackageName, /*startIfModeDefault*/ false, mClientFeatureId,
3281 String16("start camera ") + String16(mCameraIdStr));
3282 status_t res = handleAppOpMode(mode);
3283 if (res != OK) {
3284 return res;
3285 }
3286 }
3287
3288 mOpsStreaming = true;
3289
3290 return OK;
3291}
3292
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003293status_t CameraService::BasicClient::noteAppOp() {
3294 ATRACE_CALL();
3295
3296 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
3297 __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
3298
3299 // noteAppOp is only used for when camera mute is not supported, in order
3300 // to trigger the sensor privacy "Unblock" dialog
3301 if (mAppOpsManager != nullptr) {
3302 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
3303 mClientPackageName, mClientFeatureId,
3304 String16("start camera ") + String16(mCameraIdStr));
3305 status_t res = handleAppOpMode(mode);
3306 if (res != OK) {
3307 return res;
3308 }
3309 }
3310
3311 return OK;
3312}
3313
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003314status_t CameraService::BasicClient::finishCameraStreamingOps() {
3315 ATRACE_CALL();
3316
3317 if (!mOpsActive) {
3318 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3319 return INVALID_OPERATION;
3320 }
3321 if (!mOpsStreaming) {
3322 ALOGV("%s: Streaming not active!", __FUNCTION__);
3323 return OK;
3324 }
3325
3326 if (mAppOpsManager != nullptr) {
3327 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
3328 mClientPackageName, mClientFeatureId);
3329 mOpsStreaming = false;
3330 }
3331
3332 return OK;
3333}
3334
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003335status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003336 ATRACE_CALL();
3337
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003338 if (mOpsStreaming) {
3339 // Make sure we've notified everyone about camera stopping
3340 finishCameraStreamingOps();
3341 }
3342
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003343 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003344 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003345 mOpsActive = false;
3346
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003347 // This function is called when a client disconnects. This should
3348 // release the camera, but actually only if it was in a proper
3349 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003350 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003351 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003352
Ruben Brunkcc776712015-02-17 20:18:47 -08003353 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003354 sCameraService->updateStatus(StatusInternal::PRESENT,
3355 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003356 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003357 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003358 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3359 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003360 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003361 mOpsCallback.clear();
3362
Emilian Peev53722fa2019-02-22 17:47:20 -08003363 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid);
3364
Shuzhen Wang695044d2020-03-06 09:02:23 -08003365 // Notify listeners of camera open/close status
3366 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3367
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003368 return OK;
3369}
3370
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003371void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003372 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003373 if (mAppOpsManager == nullptr) {
3374 return;
3375 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003376 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003377 if (op != AppOpsManager::OP_CAMERA) {
3378 ALOGW("Unexpected app ops notification received: %d", op);
3379 return;
3380 }
3381
3382 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003383 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003384 mClientUid, mClientPackageName);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003385 ALOGV("checkOp returns: %d, %s ", res,
3386 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3387 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3388 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3389 "UNKNOWN");
3390
Shuzhen Wang64900852021-02-05 09:03:29 -08003391 if (res == AppOpsManager::MODE_ERRORED) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003392 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(),
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003393 String8(mClientPackageName).string());
Svet Ganova453d0d2018-01-11 15:37:58 -08003394 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003395 } else if (res == AppOpsManager::MODE_IGNORED) {
3396 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08003397 bool isCameraPrivacyEnabled =
3398 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled(
3399 multiuser_get_user_id(mClientUid));
Shuzhen Wang64900852021-02-05 09:03:29 -08003400 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
3401 mCameraIdStr.string(), String8(mClientPackageName).string(),
3402 mUidIsTrusted, isUidActive);
3403 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
3404 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
3405 // error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003406 if (!mUidIsTrusted) {
3407 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
3408 setCameraMute(true);
3409 } else if (!isUidActive
3410 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
3411 block();
3412 }
Shuzhen Wang64900852021-02-05 09:03:29 -08003413 }
Evan Severson09ab4002021-02-10 14:15:19 -08003414 } else if (res == AppOpsManager::MODE_ALLOWED) {
3415 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003416 }
3417}
3418
Svet Ganova453d0d2018-01-11 15:37:58 -08003419void CameraService::BasicClient::block() {
3420 ATRACE_CALL();
3421
3422 // Reset the client PID to allow server-initiated disconnect,
3423 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07003424 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08003425 CaptureResultExtras resultExtras; // a dummy result (invalid)
3426 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
3427 disconnect();
3428}
3429
Mathias Agopian65ab4712010-07-14 17:59:35 -07003430// ----------------------------------------------------------------------------
3431
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003432void CameraService::Client::notifyError(int32_t errorCode,
Jianing Weicb0652e2014-03-12 18:29:36 -07003433 const CaptureResultExtras& resultExtras) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08003434 (void) resultExtras;
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003435 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07003436 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
3437 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
3438 api1ErrorCode = CAMERA_ERROR_DISABLED;
3439 }
3440 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07003441 } else {
3442 ALOGE("mRemoteCallback is NULL!!");
3443 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003444}
3445
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003446// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003447binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003448 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003449 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08003450}
3451
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003452bool CameraService::Client::canCastToApiClient(apiLevel level) const {
3453 return level == API_1;
3454}
3455
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003456CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
3457 mClient(client) {
3458}
3459
3460void CameraService::Client::OpsCallback::opChanged(int32_t op,
3461 const String16& packageName) {
3462 sp<BasicClient> client = mClient.promote();
3463 if (client != NULL) {
3464 client->opChanged(op, packageName);
3465 }
3466}
3467
Mathias Agopian65ab4712010-07-14 17:59:35 -07003468// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08003469// UidPolicy
3470// ----------------------------------------------------------------------------
3471
3472void CameraService::UidPolicy::registerSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003473 Mutex::Autolock _l(mUidLock);
3474
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003475 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07003476 status_t res = mAm.linkToDeath(this);
3477 mAm.registerUidObserver(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08003478 | ActivityManager::UID_OBSERVER_IDLE
Emilian Peev53722fa2019-02-22 17:47:20 -08003479 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE,
Svet Ganova453d0d2018-01-11 15:37:58 -08003480 ActivityManager::PROCESS_STATE_UNKNOWN,
3481 String16("cameraserver"));
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003482 if (res == OK) {
3483 mRegistered = true;
3484 ALOGV("UidPolicy: Registered with ActivityManager");
3485 }
Svet Ganova453d0d2018-01-11 15:37:58 -08003486}
3487
3488void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003489 Mutex::Autolock _l(mUidLock);
3490
Steven Moreland2f348142019-07-02 15:59:07 -07003491 mAm.unregisterUidObserver(this);
3492 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003493 mRegistered = false;
3494 mActiveUids.clear();
3495 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08003496}
3497
3498void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
3499 onUidIdle(uid, disabled);
3500}
3501
3502void CameraService::UidPolicy::onUidActive(uid_t uid) {
3503 Mutex::Autolock _l(mUidLock);
3504 mActiveUids.insert(uid);
3505}
3506
3507void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
3508 bool deleted = false;
3509 {
3510 Mutex::Autolock _l(mUidLock);
3511 if (mActiveUids.erase(uid) > 0) {
3512 deleted = true;
3513 }
3514 }
3515 if (deleted) {
3516 sp<CameraService> service = mService.promote();
3517 if (service != nullptr) {
3518 service->blockClientsForUid(uid);
3519 }
3520 }
3521}
3522
Emilian Peev53722fa2019-02-22 17:47:20 -08003523void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07003524 int64_t procStateSeq __unused, int32_t capability __unused) {
Emilian Peev53722fa2019-02-22 17:47:20 -08003525 bool procStateChange = false;
3526 {
3527 Mutex::Autolock _l(mUidLock);
3528 if ((mMonitoredUids.find(uid) != mMonitoredUids.end()) &&
3529 (mMonitoredUids[uid].first != procState)) {
3530 mMonitoredUids[uid].first = procState;
3531 procStateChange = true;
3532 }
3533 }
3534
3535 if (procStateChange) {
3536 sp<CameraService> service = mService.promote();
3537 if (service != nullptr) {
3538 service->notifyMonitoredUids();
3539 }
3540 }
3541}
3542
3543void CameraService::UidPolicy::registerMonitorUid(uid_t uid) {
3544 Mutex::Autolock _l(mUidLock);
3545 auto it = mMonitoredUids.find(uid);
3546 if (it != mMonitoredUids.end()) {
3547 it->second.second++;
3548 } else {
3549 mMonitoredUids.emplace(
3550 std::pair<uid_t, std::pair<int32_t, size_t>> (uid,
3551 std::pair<int32_t, size_t> (ActivityManager::PROCESS_STATE_NONEXISTENT, 1)));
3552 }
3553}
3554
3555void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid) {
3556 Mutex::Autolock _l(mUidLock);
3557 auto it = mMonitoredUids.find(uid);
3558 if (it != mMonitoredUids.end()) {
3559 it->second.second--;
3560 if (it->second.second == 0) {
3561 mMonitoredUids.erase(it);
3562 }
3563 } else {
3564 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
3565 }
3566}
3567
Svet Ganov7b4ab782018-03-25 12:48:10 -07003568bool CameraService::UidPolicy::isUidActive(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003569 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003570 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003571}
3572
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003573static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
3574static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003575
Svet Ganov7b4ab782018-03-25 12:48:10 -07003576bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003577 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003578 // If activity manager is unreachable, assume everything is active
3579 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003580 return true;
3581 }
3582 auto it = mOverrideUids.find(uid);
3583 if (it != mOverrideUids.end()) {
3584 return it->second;
3585 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003586 bool active = mActiveUids.find(uid) != mActiveUids.end();
3587 if (!active) {
3588 // We want active UIDs to always access camera with their first attempt since
3589 // there is no guarantee the app is robustly written and would retry getting
3590 // the camera on failure. The inverse case is not a problem as we would take
3591 // camera away soon once we get the callback that the uid is no longer active.
3592 ActivityManager am;
3593 // Okay to access with a lock held as UID changes are dispatched without
3594 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07003595 int64_t startTimeMillis = 0;
3596 do {
3597 // TODO: Fix this b/109950150!
3598 // Okay this is a hack. There is a race between the UID turning active and
3599 // activity being resumed. The proper fix is very risky, so we temporary add
3600 // some polling which should happen pretty rarely anyway as the race is hard
3601 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003602 active = mActiveUids.find(uid) != mActiveUids.end();
Hui Yu12c7ec72020-05-04 17:40:52 +00003603 if (!active) active = am.isUidActive(uid, callingPackage);
Svet Ganov94ec46f2018-06-08 15:03:46 -07003604 if (active) {
3605 break;
3606 }
3607 if (startTimeMillis <= 0) {
3608 startTimeMillis = uptimeMillis();
3609 }
3610 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003611 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07003612 if (remainingTimeMillis <= 0) {
3613 break;
3614 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003615 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
3616
3617 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003618 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07003619 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07003620 } while (true);
3621
Svet Ganov7b4ab782018-03-25 12:48:10 -07003622 if (active) {
3623 // Now that we found out the UID is actually active, cache that
3624 mActiveUids.insert(uid);
3625 }
3626 }
3627 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08003628}
3629
Varun Shahb42f1eb2019-04-16 14:45:13 -07003630int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
3631 Mutex::Autolock _l(mUidLock);
3632 return getProcStateLocked(uid);
3633}
3634
3635int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
3636 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
3637 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
3638 procState = mMonitoredUids[uid].first;
3639 }
3640 return procState;
3641}
3642
Svet Ganov7b4ab782018-03-25 12:48:10 -07003643void CameraService::UidPolicy::UidPolicy::addOverrideUid(uid_t uid,
3644 String16 callingPackage, bool active) {
3645 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08003646}
3647
Svet Ganov7b4ab782018-03-25 12:48:10 -07003648void CameraService::UidPolicy::removeOverrideUid(uid_t uid, String16 callingPackage) {
3649 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08003650}
3651
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003652void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
3653 Mutex::Autolock _l(mUidLock);
3654 ALOGV("UidPolicy: ActivityManager has died");
3655 mRegistered = false;
3656 mActiveUids.clear();
3657}
3658
Svet Ganov7b4ab782018-03-25 12:48:10 -07003659void CameraService::UidPolicy::updateOverrideUid(uid_t uid, String16 callingPackage,
3660 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003661 bool wasActive = false;
3662 bool isActive = false;
3663 {
3664 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07003665 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003666 mOverrideUids.erase(uid);
3667 if (insert) {
3668 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
3669 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07003670 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08003671 }
3672 if (wasActive != isActive && !isActive) {
3673 sp<CameraService> service = mService.promote();
3674 if (service != nullptr) {
3675 service->blockClientsForUid(uid);
3676 }
3677 }
3678}
3679
3680// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08003681// SensorPrivacyPolicy
3682// ----------------------------------------------------------------------------
3683void CameraService::SensorPrivacyPolicy::registerSelf() {
3684 Mutex::Autolock _l(mSensorPrivacyLock);
3685 if (mRegistered) {
3686 return;
3687 }
Evan Severson09ab4002021-02-10 14:15:19 -08003688 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08003689 mSpm.addSensorPrivacyListener(this);
3690 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
3691 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003692 if (res == OK) {
3693 mRegistered = true;
3694 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
3695 }
3696}
3697
3698void CameraService::SensorPrivacyPolicy::unregisterSelf() {
3699 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08003700 mSpm.removeSensorPrivacyListener(this);
3701 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08003702 mRegistered = false;
3703 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
3704}
3705
3706bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
3707 Mutex::Autolock _l(mSensorPrivacyLock);
3708 return mSensorPrivacyEnabled;
3709}
3710
Evan Severson09ab4002021-02-10 14:15:19 -08003711bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(userid_t userId) {
3712 if (!hasCameraPrivacyFeature()) {
3713 return false;
3714 }
3715 return mSpm.isIndividualSensorPrivacyEnabled(userId,
3716 SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
3717}
3718
Michael Grooverd1d435a2018-12-18 17:39:42 -08003719binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
3720 {
3721 Mutex::Autolock _l(mSensorPrivacyLock);
3722 mSensorPrivacyEnabled = enabled;
3723 }
3724 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08003725 if (enabled) {
3726 sp<CameraService> service = mService.promote();
3727 if (service != nullptr) {
3728 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003729 }
3730 }
3731 return binder::Status::ok();
3732}
3733
3734void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
3735 Mutex::Autolock _l(mSensorPrivacyLock);
3736 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
3737 mRegistered = false;
3738}
3739
Evan Severson09ab4002021-02-10 14:15:19 -08003740bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Severson671806e2021-04-20 16:44:53 -07003741 return mSpm.supportsSensorToggle(SensorPrivacyManager::INDIVIDUAL_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08003742}
3743
Michael Grooverd1d435a2018-12-18 17:39:42 -08003744// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003745// CameraState
3746// ----------------------------------------------------------------------------
3747
3748CameraService::CameraState::CameraState(const String8& id, int cost,
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003749 const std::set<String8>& conflicting, SystemCameraKind systemCameraKind) : mId(id),
3750 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
3751 mSystemCameraKind(systemCameraKind) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08003752
3753CameraService::CameraState::~CameraState() {}
3754
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003755CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003756 Mutex::Autolock lock(mStatusLock);
3757 return mStatus;
3758}
3759
Shuzhen Wang43858162020-01-10 13:42:15 -08003760std::vector<String8> CameraService::CameraState::getUnavailablePhysicalIds() const {
3761 Mutex::Autolock lock(mStatusLock);
3762 std::vector<String8> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
3763 return res;
3764}
3765
Ruben Brunkcc776712015-02-17 20:18:47 -08003766CameraParameters CameraService::CameraState::getShimParams() const {
3767 return mShimParams;
3768}
3769
3770void CameraService::CameraState::setShimParams(const CameraParameters& params) {
3771 mShimParams = params;
3772}
3773
3774int CameraService::CameraState::getCost() const {
3775 return mCost;
3776}
3777
3778std::set<String8> CameraService::CameraState::getConflicting() const {
3779 return mConflicting;
3780}
3781
3782String8 CameraService::CameraState::getId() const {
3783 return mId;
3784}
3785
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003786SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
3787 return mSystemCameraKind;
3788}
3789
Shuzhen Wang43858162020-01-10 13:42:15 -08003790bool CameraService::CameraState::addUnavailablePhysicalId(const String8& physicalId) {
3791 Mutex::Autolock lock(mStatusLock);
3792 auto result = mUnavailablePhysicalIds.insert(physicalId);
3793 return result.second;
3794}
3795
3796bool CameraService::CameraState::removeUnavailablePhysicalId(const String8& physicalId) {
3797 Mutex::Autolock lock(mStatusLock);
3798 auto count = mUnavailablePhysicalIds.erase(physicalId);
3799 return count > 0;
3800}
3801
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003802void CameraService::CameraState::setClientPackage(const String8& clientPackage) {
3803 Mutex::Autolock lock(mStatusLock);
3804 mClientPackage = clientPackage;
3805}
3806
3807String8 CameraService::CameraState::getClientPackage() const {
3808 Mutex::Autolock lock(mStatusLock);
3809 return mClientPackage;
3810}
3811
Ruben Brunkcc776712015-02-17 20:18:47 -08003812// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07003813// ClientEventListener
3814// ----------------------------------------------------------------------------
3815
3816void CameraService::ClientEventListener::onClientAdded(
3817 const resource_policy::ClientDescriptor<String8,
3818 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003819 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003820 if (basicClient.get() != nullptr) {
3821 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3822 notifier.noteStartCamera(descriptor.getKey(),
3823 static_cast<int>(basicClient->getClientUid()));
3824 }
3825}
3826
3827void CameraService::ClientEventListener::onClientRemoved(
3828 const resource_policy::ClientDescriptor<String8,
3829 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07003830 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07003831 if (basicClient.get() != nullptr) {
3832 BatteryNotifier& notifier(BatteryNotifier::getInstance());
3833 notifier.noteStopCamera(descriptor.getKey(),
3834 static_cast<int>(basicClient->getClientUid()));
3835 }
3836}
3837
3838
3839// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08003840// CameraClientManager
3841// ----------------------------------------------------------------------------
3842
Ruben Brunk99e69712015-05-26 17:25:07 -07003843CameraService::CameraClientManager::CameraClientManager() {
3844 setListener(std::make_shared<ClientEventListener>());
3845}
3846
Ruben Brunkcc776712015-02-17 20:18:47 -08003847CameraService::CameraClientManager::~CameraClientManager() {}
3848
3849sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
3850 const String8& id) const {
3851 auto descriptor = get(id);
3852 if (descriptor == nullptr) {
3853 return sp<BasicClient>{nullptr};
3854 }
3855 return descriptor->getValue();
3856}
3857
3858String8 CameraService::CameraClientManager::toString() const {
3859 auto all = getAll();
3860 String8 ret("[");
3861 bool hasAny = false;
3862 for (auto& i : all) {
3863 hasAny = true;
3864 String8 key = i->getKey();
3865 int32_t cost = i->getCost();
3866 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00003867 int32_t score = i->getPriority().getScore();
3868 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08003869 auto conflicting = i->getConflicting();
3870 auto clientSp = i->getValue();
3871 String8 packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07003872 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08003873 if (clientSp.get() != nullptr) {
3874 packageName = String8{clientSp->getPackageName()};
Ruben Brunk6267b532015-04-30 17:44:07 -07003875 uid_t clientUid = clientSp->getClientUid();
3876 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003877 }
Emilian Peev8131a262017-02-01 12:33:43 +00003878 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
3879 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08003880
Ruben Brunk6267b532015-04-30 17:44:07 -07003881 if (clientSp.get() != nullptr) {
3882 ret.appendFormat("User Id: %d, ", clientUserId);
3883 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003884 if (packageName.size() != 0) {
3885 ret.appendFormat("Client Package Name: %s", packageName.string());
3886 }
3887
3888 ret.append(", Conflicting Client Devices: {");
3889 for (auto& j : conflicting) {
3890 ret.appendFormat("%s, ", j.string());
3891 }
3892 ret.append("})");
3893 }
3894 if (hasAny) ret.append("\n");
3895 ret.append("]\n");
3896 return ret;
3897}
3898
3899CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
3900 const String8& key, const sp<BasicClient>& value, int32_t cost,
Emilian Peev8131a262017-02-01 12:33:43 +00003901 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003902 int32_t state, int32_t oomScoreOffset) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003903
Steven Moreland89a2c5c2020-01-31 15:02:25 -08003904 bool isVendorClient = getCurrentServingCall() == BinderCallType::HWBINDER;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07003905 int32_t score_adj = isVendorClient ? kVendorClientScore : score;
3906 int32_t state_adj = isVendorClient ? kVendorClientState: state;
3907
Ruben Brunkcc776712015-02-17 20:18:47 -08003908 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003909 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj, isVendorClient,
3910 oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08003911}
3912
3913CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003914 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
3915 int32_t oomScoreOffset) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003916 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00003917 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00003918 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08003919}
3920
3921// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08003922// InjectionStatusListener
3923// ----------------------------------------------------------------------------
3924
3925void CameraService::InjectionStatusListener::addListener(
3926 const sp<ICameraInjectionCallback>& callback) {
3927 Mutex::Autolock lock(mListenerLock);
3928 if (mCameraInjectionCallback) return;
3929 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
3930 if (res == OK) {
3931 mCameraInjectionCallback = callback;
3932 }
3933}
3934
3935void CameraService::InjectionStatusListener::removeListener() {
3936 Mutex::Autolock lock(mListenerLock);
3937 if (mCameraInjectionCallback == nullptr) {
3938 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
3939 return;
3940 }
3941 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
3942 mCameraInjectionCallback = nullptr;
3943}
3944
3945void CameraService::InjectionStatusListener::notifyInjectionError(
Cliff Wud3a05312021-04-26 23:07:31 +08003946 String8 injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08003947 if (mCameraInjectionCallback == nullptr) {
3948 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
3949 return;
3950 }
Cliff Wud3a05312021-04-26 23:07:31 +08003951
3952 switch (err) {
3953 case -ENODEV:
3954 mCameraInjectionCallback->onInjectionError(
3955 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
3956 ALOGE("No camera device with ID \"%s\" currently available!",
3957 injectedCamId.string());
3958 break;
3959 case -EBUSY:
3960 mCameraInjectionCallback->onInjectionError(
3961 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
3962 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
3963 injectedCamId.string());
3964 break;
3965 case DEAD_OBJECT:
3966 mCameraInjectionCallback->onInjectionError(
3967 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
3968 ALOGE("Camera ID \"%s\" object is dead!",
3969 injectedCamId.string());
3970 break;
3971 case INVALID_OPERATION:
3972 mCameraInjectionCallback->onInjectionError(
3973 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
3974 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
3975 injectedCamId.string());
3976 break;
3977 case UNKNOWN_TRANSACTION:
3978 mCameraInjectionCallback->onInjectionError(
3979 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
3980 ALOGE("Camera ID \"%s\" method doesn't support!",
3981 injectedCamId.string());
3982 break;
3983 default:
3984 mCameraInjectionCallback->onInjectionError(
3985 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
3986 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
3987 strerror(-err), err, injectedCamId.string());
3988 }
Cliff Wud8cae102021-03-11 01:37:42 +08003989}
3990
3991void CameraService::InjectionStatusListener::binderDied(
3992 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08003993 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
3994 auto parent = mParent.promote();
3995 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08003996 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
3997 if (clientDescriptor != nullptr) {
3998 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
3999 baseClientPtr->stopInjection();
4000 }
Cliff Wu3b268182021-07-06 15:44:43 +08004001 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004002 }
4003}
4004
4005// ----------------------------------------------------------------------------
4006// CameraInjectionSession
4007// ----------------------------------------------------------------------------
4008
4009binder::Status CameraService::CameraInjectionSession::stopInjection() {
4010 Mutex::Autolock lock(mInjectionSessionLock);
4011 auto parent = mParent.promote();
4012 if (parent == nullptr) {
4013 ALOGE("CameraInjectionSession: Parent is gone");
4014 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
4015 "Camera service encountered error");
4016 }
Cliff Wud3a05312021-04-26 23:07:31 +08004017
4018 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08004019 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4020 if (clientDescriptor != nullptr) {
4021 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4022 res = baseClientPtr->stopInjection();
4023 if (res != OK) {
4024 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
4025 " ret != NO_ERROR: %d", res);
4026 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
4027 "Camera session encountered error");
4028 }
4029 }
Cliff Wu3b268182021-07-06 15:44:43 +08004030 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004031 return binder::Status::ok();
4032}
4033
4034// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07004035
4036static const int kDumpLockRetries = 50;
4037static const int kDumpLockSleep = 60000;
4038
4039static bool tryLock(Mutex& mutex)
4040{
4041 bool locked = false;
4042 for (int i = 0; i < kDumpLockRetries; ++i) {
4043 if (mutex.tryLock() == NO_ERROR) {
4044 locked = true;
4045 break;
4046 }
4047 usleep(kDumpLockSleep);
4048 }
4049 return locked;
4050}
4051
Rucha Katakwardf223072021-06-15 10:21:00 -07004052void CameraService::cacheDump() {
4053 if (mMemFd != -1) {
4054 const Vector<String16> args;
4055 ATRACE_CALL();
4056 // Acquiring service lock here will avoid the deadlock since
4057 // cacheDump will not be called during the second disconnect.
4058 Mutex::Autolock lock(mServiceLock);
4059
4060 Mutex::Autolock l(mCameraStatesLock);
4061 // Start collecting the info for open sessions and store it in temp file.
4062 for (const auto& state : mCameraStates) {
4063 String8 cameraId = state.first;
4064 auto clientDescriptor = mActiveClientManager.get(cameraId);
4065 if (clientDescriptor != nullptr) {
4066 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.string());
4067 // Log the current open session info before device is disconnected.
4068 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
4069 }
4070 }
4071 }
4072}
4073
Mathias Agopian65ab4712010-07-14 17:59:35 -07004074status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004075 ATRACE_CALL();
4076
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004077 if (checkCallingPermission(sDumpPermission) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004078 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004079 CameraThreadState::getCallingPid(),
4080 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004081 return NO_ERROR;
4082 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004083 bool locked = tryLock(mServiceLock);
4084 // failed to lock - CameraService is probably deadlocked
4085 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004086 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004087 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004088
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004089 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004090 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07004091
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004092 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004093 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08004094
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004095 if (locked) mServiceLock.unlock();
4096 return NO_ERROR;
4097 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004098 dprintf(fd, "\n== Service global info: ==\n\n");
4099 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004100 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07004101 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
4102 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004103 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
4104 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
4105 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004106 String8 activeClientString = mActiveClientManager.toString();
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004107 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string());
4108 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004109
4110 dumpEventLog(fd);
4111
4112 bool stateLocked = tryLock(mCameraStatesLock);
4113 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004114 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004115 }
4116
Emilian Peevbd8c5032018-02-14 23:05:40 +00004117 int argSize = args.size();
4118 for (int i = 0; i < argSize; i++) {
4119 if (args[i] == TagMonitor::kMonitorOption) {
4120 if (i + 1 < argSize) {
4121 mMonitorTags = String8(args[i + 1]);
4122 }
4123 break;
4124 }
4125 }
4126
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004127 for (auto& state : mCameraStates) {
4128 String8 cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004129
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004130 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004131
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004132 CameraParameters p = state.second->getShimParams();
4133 if (!p.isEmpty()) {
4134 dprintf(fd, " Camera1 API shim is using parameters:\n ");
4135 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004136 }
4137
4138 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004139 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004140 // log the current open session info
4141 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004142 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07004143 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004144 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004145
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004146 }
4147
4148 if (stateLocked) mCameraStatesLock.unlock();
4149
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004150 if (locked) mServiceLock.unlock();
4151
Emilian Peevf53f66e2017-04-11 14:29:43 +01004152 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004153
4154 dprintf(fd, "\n== Vendor tags: ==\n\n");
4155
4156 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
4157 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00004158 sp<VendorTagDescriptorCache> cache =
4159 VendorTagDescriptorCache::getGlobalVendorTagCache();
4160 if (cache == NULL) {
4161 dprintf(fd, "No vendor tags.\n");
4162 } else {
4163 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
4164 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004165 } else {
4166 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
4167 }
4168
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004169 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004170 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004171 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004172
4173 // Process dump arguments, if any
4174 int n = args.size();
4175 String16 verboseOption("-v");
4176 String16 unreachableOption("--unreachable");
4177 for (int i = 0; i < n; i++) {
4178 if (args[i] == verboseOption) {
4179 // change logging level
4180 if (i + 1 >= n) continue;
4181 String8 levelStr(args[i+1]);
4182 int level = atoi(levelStr.string());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004183 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004184 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004185 } else if (args[i] == unreachableOption) {
4186 // Dump memory analysis
4187 // TODO - should limit be an argument parameter?
4188 UnreachableMemoryInfo info;
4189 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
4190 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004191 dprintf(fd, "\n== Unable to dump unreachable memory. "
4192 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004193 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004194 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004195 std::string s = info.ToString(/*log_contents*/ true);
4196 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004197 }
4198 }
4199 }
Rucha Katakwardf223072021-06-15 10:21:00 -07004200
4201 bool serviceLocked = tryLock(mServiceLock);
4202
4203 // Dump info from previous open sessions.
4204 // Reposition the offset to beginning of the file before reading
4205
4206 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
4207 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
4208 ssize_t size_read;
4209 char buf[4096];
4210 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
4211 // Read data from file to a small buffer and write it to fd.
4212 write(fd, buf, size_read);
4213 if (size_read == -1) {
4214 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4215 break;
4216 }
4217 }
4218 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
4219 } else {
4220 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4221 }
4222
4223 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004224 return NO_ERROR;
4225}
4226
Rucha Katakwardf223072021-06-15 10:21:00 -07004227void CameraService::dumpOpenSessionClientLogs(int fd,
4228 const Vector<String16>& args, const String8& cameraId) {
4229 auto clientDescriptor = mActiveClientManager.get(cameraId);
4230 dprintf(fd, " Device %s is open. Client instance dump:\n",
4231 cameraId.string());
4232 dprintf(fd, " Client priority score: %d state: %d\n",
4233 clientDescriptor->getPriority().getScore(),
4234 clientDescriptor->getPriority().getState());
4235 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
4236
4237 auto client = clientDescriptor->getValue();
4238 dprintf(fd, " Client package: %s\n",
4239 String8(client->getPackageName()).string());
4240
4241 client->dumpClient(fd, args);
4242}
4243
4244void CameraService::dumpClosedSessionClientLogs(int fd, const String8& cameraId) {
4245 dprintf(fd, " Device %s is closed, no client instance\n",
4246 cameraId.string());
4247}
4248
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004249void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004250 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004251
4252 Mutex::Autolock l(mLogLock);
4253 for (const auto& msg : mEventLog) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004254 dprintf(fd, " %s\n", msg.string());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004255 }
4256
4257 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004258 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004259 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004260 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004261 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004262 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004263}
4264
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004265void CameraService::cacheClientTagDumpIfNeeded(const char *cameraId, BasicClient* client) {
4266 Mutex::Autolock lock(mLogLock);
4267 if (!isClientWatchedLocked(client)) { return; }
4268
4269 std::vector<std::string> dumpVector;
4270 client->dumpWatchedEventsToVector(dumpVector);
4271
4272 if (dumpVector.empty()) { return; }
4273
4274 std::string dumpString;
4275 size_t i = dumpVector.size();
4276
4277 // Store the string in reverse order (latest last)
4278 while (i > 0) {
4279 i--;
4280 dumpString += cameraId;
4281 dumpString += ":";
4282 dumpString += dumpVector[i]; // implicitly ends with '\n'
4283 }
4284
4285 const String16 &packageName = client->getPackageName();
4286 mWatchedClientsDumpCache[packageName] = dumpString;
4287}
4288
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004289void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004290 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004291 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
4292 if (mTorchClientMap[i] == who) {
4293 // turn off the torch mode that was turned on by dead client
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004294 String8 cameraId = mTorchClientMap.keyAt(i);
4295 status_t res = mFlashlight->setTorchMode(cameraId, false);
4296 if (res) {
4297 ALOGE("%s: torch client died but couldn't turn off torch: "
4298 "%s (%d)", __FUNCTION__, strerror(-res), res);
4299 return;
4300 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004301 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004302 break;
4303 }
4304 }
4305}
4306
Ruben Brunkcc776712015-02-17 20:18:47 -08004307/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07004308
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004309 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07004310 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
4311 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07004312 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08004313 // PID here is approximate and can be wrong.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004314 logClientDied(CameraThreadState::getCallingPid(), String8("Binder died unexpectedly"));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004315
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004316 // check torch client
4317 handleTorchClientBinderDied(who);
4318
4319 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08004320 if(!evictClientIdByRemote(who)) {
4321 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004322 return;
4323 }
4324
Ruben Brunkcc776712015-02-17 20:18:47 -08004325 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
4326 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07004327}
4328
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004329void CameraService::updateStatus(StatusInternal status, const String8& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004330 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08004331}
4332
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004333void CameraService::updateStatus(StatusInternal status, const String8& cameraId,
4334 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004335 // Do not lock mServiceLock here or can get into a deadlock from
4336 // connect() -> disconnect -> updateStatus
4337
4338 auto state = getCameraState(cameraId);
4339
4340 if (state == nullptr) {
4341 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4342 cameraId.string());
4343 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07004344 }
4345
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004346 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
4347 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
4348 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
4349 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.string());
4350 return;
4351 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004352
4353 // Collect the logical cameras without holding mStatusLock in updateStatus
4354 // as that can lead to a deadlock(b/162192331).
4355 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08004356 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08004357 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07004358 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004359 &logicalCameraIds]
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004360 (const String8& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004361
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004362 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004363 // Update torch status if it has a flash unit.
4364 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004365 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004366 if (getTorchStatusLocked(cameraId, &torchStatus) !=
4367 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004368 TorchModeStatus newTorchStatus =
4369 status == StatusInternal::PRESENT ?
4370 TorchModeStatus::AVAILABLE_OFF :
4371 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004372 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07004373 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07004374 }
4375 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004376 }
4377
4378 Mutex::Autolock lock(mStatusListenerLock);
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004379 notifyPhysicalCameraStatusLocked(mapToInterface(status), String16(cameraId),
4380 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08004381
Ruben Brunkcc776712015-02-17 20:18:47 -08004382 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07004383 bool isVendorListener = listener->isVendorListener();
4384 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
4385 listener->getListenerPid(), listener->getListenerUid()) ||
Shuzhen Wangb8259792021-05-27 09:27:06 -07004386 isVendorListener) {
4387 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004388 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08004389 continue;
4390 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07004391 listener->getListener()->onStatusChanged(mapToInterface(status),
Emilian Peev53722fa2019-02-22 17:47:20 -08004392 String16(cameraId));
Ruben Brunkcc776712015-02-17 20:18:47 -08004393 }
4394 });
Igor Murashkincba2c162013-03-20 15:56:31 -07004395}
4396
Shuzhen Wang695044d2020-03-06 09:02:23 -08004397void CameraService::updateOpenCloseStatus(const String8& cameraId, bool open,
4398 const String16& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004399 auto state = getCameraState(cameraId);
4400 if (state == nullptr) {
4401 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
4402 cameraId.string());
4403 return;
4404 }
4405 if (open) {
4406 state->setClientPackage(String8(clientPackageName));
4407 } else {
4408 state->setClientPackage(String8::empty());
4409 }
4410
Shuzhen Wang695044d2020-03-06 09:02:23 -08004411 Mutex::Autolock lock(mStatusListenerLock);
4412
4413 for (const auto& it : mListenerList) {
4414 if (!it->isOpenCloseCallbackAllowed()) {
4415 continue;
4416 }
4417
4418 binder::Status ret;
4419 String16 cameraId64(cameraId);
4420 if (open) {
4421 ret = it->getListener()->onCameraOpened(cameraId64, clientPackageName);
4422 } else {
4423 ret = it->getListener()->onCameraClosed(cameraId64);
4424 }
4425 if (!ret.isOk()) {
4426 ALOGE("%s: Failed to trigger onCameraOpened/onCameraClosed callback: %d", __FUNCTION__,
4427 ret.exceptionCode());
4428 }
4429 }
4430}
4431
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004432template<class Func>
4433void CameraService::CameraState::updateStatus(StatusInternal status,
4434 const String8& cameraId,
4435 std::initializer_list<StatusInternal> rejectSourceStates,
4436 Func onStatusUpdatedLocked) {
4437 Mutex::Autolock lock(mStatusLock);
4438 StatusInternal oldStatus = mStatus;
4439 mStatus = status;
4440
4441 if (oldStatus == status) {
4442 return;
4443 }
4444
4445 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
4446 cameraId.string(), oldStatus, status);
4447
4448 if (oldStatus == StatusInternal::NOT_PRESENT &&
4449 (status != StatusInternal::PRESENT &&
4450 status != StatusInternal::ENUMERATING)) {
4451
4452 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
4453 __FUNCTION__);
4454 mStatus = oldStatus;
4455 return;
4456 }
4457
4458 /**
4459 * Sometimes we want to conditionally do a transition.
4460 * For example if a client disconnects, we want to go to PRESENT
4461 * only if we weren't already in NOT_PRESENT or ENUMERATING.
4462 */
4463 for (auto& rejectStatus : rejectSourceStates) {
4464 if (oldStatus == rejectStatus) {
4465 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
4466 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
4467 mStatus = oldStatus;
4468 return;
4469 }
4470 }
4471
4472 onStatusUpdatedLocked(cameraId, status);
4473}
4474
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004475status_t CameraService::getTorchStatusLocked(
4476 const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004477 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004478 if (!status) {
4479 return BAD_VALUE;
4480 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004481 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4482 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004483 // invalid camera ID or the camera doesn't have a flash unit
4484 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004485 }
4486
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004487 *status = mTorchStatusMap.valueAt(index);
4488 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004489}
4490
Chien-Yu Chen88da5262015-02-17 13:56:46 -08004491status_t CameraService::setTorchStatusLocked(const String8& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004492 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004493 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
4494 if (index == NAME_NOT_FOUND) {
4495 return BAD_VALUE;
4496 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004497 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08004498
4499 return OK;
4500}
4501
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004502std::list<String16> CameraService::getLogicalCameras(
4503 const String8& physicalCameraId) {
4504 std::list<String16> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08004505 Mutex::Autolock lock(mCameraStatesLock);
4506 for (const auto& state : mCameraStates) {
4507 std::vector<std::string> physicalCameraIds;
4508 if (!mCameraProviderManager->isLogicalCamera(state.first.c_str(), &physicalCameraIds)) {
4509 // This is not a logical multi-camera.
4510 continue;
4511 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004512 if (std::find(physicalCameraIds.begin(), physicalCameraIds.end(), physicalCameraId.c_str())
Shuzhen Wang43858162020-01-10 13:42:15 -08004513 == physicalCameraIds.end()) {
4514 // cameraId is not a physical camera of this logical multi-camera.
4515 continue;
4516 }
4517
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004518 retList.emplace_back(String16(state.first));
4519 }
4520 return retList;
4521}
4522
4523void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
4524 const String16& physicalCameraId, const std::list<String16>& logicalCameraIds,
4525 SystemCameraKind deviceKind) {
4526 // mStatusListenerLock is expected to be locked
4527 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004528 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004529 // Note: we check only the deviceKind of the physical camera id
4530 // since, logical camera ids and their physical camera ids are
4531 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004532 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
4533 listener->getListenerPid(), listener->getListenerUid())) {
4534 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004535 String8(physicalCameraId).c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07004536 continue;
4537 }
Shuzhen Wang43858162020-01-10 13:42:15 -08004538 listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004539 logicalCameraId, physicalCameraId);
Shuzhen Wang43858162020-01-10 13:42:15 -08004540 }
4541 }
4542}
4543
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00004544
Svet Ganova453d0d2018-01-11 15:37:58 -08004545void CameraService::blockClientsForUid(uid_t uid) {
4546 const auto clients = mActiveClientManager.getAll();
4547 for (auto& current : clients) {
4548 if (current != nullptr) {
4549 const auto basicClient = current->getValue();
4550 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
4551 basicClient->block();
4552 }
4553 }
4554 }
4555}
4556
Michael Grooverd1d435a2018-12-18 17:39:42 -08004557void CameraService::blockAllClients() {
4558 const auto clients = mActiveClientManager.getAll();
4559 for (auto& current : clients) {
4560 if (current != nullptr) {
4561 const auto basicClient = current->getValue();
4562 if (basicClient.get() != nullptr) {
4563 basicClient->block();
4564 }
4565 }
4566 }
4567}
4568
Svet Ganova453d0d2018-01-11 15:37:58 -08004569// NOTE: This is a remote API - make sure all args are validated
4570status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
4571 if (!checkCallingPermission(sManageCameraPermission, nullptr, nullptr)) {
4572 return PERMISSION_DENIED;
4573 }
4574 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
4575 return BAD_VALUE;
4576 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004577 if (args.size() >= 3 && args[0] == String16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004578 return handleSetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004579 } else if (args.size() >= 2 && args[0] == String16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004580 return handleResetUidState(args, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07004581 } else if (args.size() >= 2 && args[0] == String16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004582 return handleGetUidState(args, out, err);
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004583 } else if (args.size() >= 2 && args[0] == String16("set-rotate-and-crop")) {
4584 return handleSetRotateAndCrop(args);
4585 } else if (args.size() >= 1 && args[0] == String16("get-rotate-and-crop")) {
4586 return handleGetRotateAndCrop(out);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004587 } else if (args.size() >= 2 && args[0] == String16("set-image-dump-mask")) {
4588 return handleSetImageDumpMask(args);
4589 } else if (args.size() >= 1 && args[0] == String16("get-image-dump-mask")) {
4590 return handleGetImageDumpMask(out);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004591 } else if (args.size() >= 2 && args[0] == String16("set-camera-mute")) {
4592 return handleSetCameraMute(args);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004593 } else if (args.size() >= 2 && args[0] == String16("watch")) {
4594 return handleWatchCommand(args, out);
Svet Ganova453d0d2018-01-11 15:37:58 -08004595 } else if (args.size() == 1 && args[0] == String16("help")) {
4596 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004597 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08004598 }
4599 printHelp(err);
4600 return BAD_VALUE;
4601}
4602
4603status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004604 String16 packageName = args[1];
4605
Svet Ganova453d0d2018-01-11 15:37:58 -08004606 bool active = false;
4607 if (args[2] == String16("active")) {
4608 active = true;
4609 } else if ((args[2] != String16("idle"))) {
4610 ALOGE("Expected active or idle but got: '%s'", String8(args[2]).string());
4611 return BAD_VALUE;
4612 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004613
4614 int userId = 0;
4615 if (args.size() >= 5 && args[3] == String16("--user")) {
4616 userId = atoi(String8(args[4]));
4617 }
4618
4619 uid_t uid;
4620 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
4621 return BAD_VALUE;
4622 }
4623
4624 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08004625 return NO_ERROR;
4626}
4627
4628status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004629 String16 packageName = args[1];
4630
4631 int userId = 0;
4632 if (args.size() >= 4 && args[2] == String16("--user")) {
4633 userId = atoi(String8(args[3]));
4634 }
4635
4636 uid_t uid;
4637 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004638 return BAD_VALUE;
4639 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004640
4641 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08004642 return NO_ERROR;
4643}
4644
4645status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07004646 String16 packageName = args[1];
4647
4648 int userId = 0;
4649 if (args.size() >= 4 && args[2] == String16("--user")) {
4650 userId = atoi(String8(args[3]));
4651 }
4652
4653 uid_t uid;
4654 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004655 return BAD_VALUE;
4656 }
Nicholas Sauera3620332019-04-03 14:05:17 -07004657
4658 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004659 return dprintf(out, "active\n");
4660 } else {
4661 return dprintf(out, "idle\n");
4662 }
4663}
4664
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004665status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
4666 int rotateValue = atoi(String8(args[1]));
4667 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
4668 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
4669 Mutex::Autolock lock(mServiceLock);
4670
4671 mOverrideRotateAndCropMode = rotateValue;
4672
4673 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
4674
4675 const auto clients = mActiveClientManager.getAll();
4676 for (auto& current : clients) {
4677 if (current != nullptr) {
4678 const auto basicClient = current->getValue();
4679 if (basicClient.get() != nullptr) {
4680 basicClient->setRotateAndCropOverride(rotateValue);
4681 }
4682 }
4683 }
4684
4685 return OK;
4686}
4687
4688status_t CameraService::handleGetRotateAndCrop(int out) {
4689 Mutex::Autolock lock(mServiceLock);
4690
4691 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
4692}
4693
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004694status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
4695 char *endPtr;
4696 errno = 0;
4697 String8 maskString8 = String8(args[1]);
4698 long maskValue = strtol(maskString8.c_str(), &endPtr, 10);
4699
4700 if (errno != 0) return BAD_VALUE;
4701 if (endPtr != maskString8.c_str() + maskString8.size()) return BAD_VALUE;
4702 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
4703
4704 Mutex::Autolock lock(mServiceLock);
4705
4706 mImageDumpMask = maskValue;
4707
4708 return OK;
4709}
4710
4711status_t CameraService::handleGetImageDumpMask(int out) {
4712 Mutex::Autolock lock(mServiceLock);
4713
4714 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
4715}
4716
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004717status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
4718 int muteValue = strtol(String8(args[1]), nullptr, 10);
4719 if (errno != 0) return BAD_VALUE;
4720
4721 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
4722 Mutex::Autolock lock(mServiceLock);
4723
4724 mOverrideCameraMuteMode = (muteValue == 1);
4725
4726 const auto clients = mActiveClientManager.getAll();
4727 for (auto& current : clients) {
4728 if (current != nullptr) {
4729 const auto basicClient = current->getValue();
4730 if (basicClient.get() != nullptr) {
4731 if (basicClient->supportsCameraMute()) {
4732 basicClient->setCameraMute(mOverrideCameraMuteMode);
4733 }
4734 }
4735 }
4736 }
4737
4738 return OK;
4739}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004740
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004741status_t CameraService::handleWatchCommand(const Vector<String16>& args, int outFd) {
4742 if (args.size() >= 3 && args[1] == String16("start")) {
4743 return startWatchingTags(args, outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004744 } else if (args.size() == 2 && args[1] == String16("dump")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004745 return camera3::CameraTraces::dump(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004746 } else if (args.size() == 2 && args[1] == String16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004747 return stopWatchingTags(outFd);
4748 } else if (args.size() >= 2 && args[1] == String16("print")) {
4749 return printWatchedTags(args, outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004750 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004751 dprintf(outFd, "Camera service watch commands:\n"
4752 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
4753 " starts watching the provided tags for clients with provided package\n"
4754 " recognizes tag shorthands like '3a'\n"
4755 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004756 " dump dumps camera trace\n"
4757 " stop stops watching all tags\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004758 " print [-n <refresh_interval_ms>]\n"
4759 " prints the monitored information in real time\n"
4760 " Hit Ctrl+C to exit\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004761 return BAD_VALUE;
4762}
4763
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004764status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
4765 Mutex::Autolock lock(mLogLock);
4766 size_t tagsIdx; // index of '-m'
4767 String16 tags("");
4768 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != String16("-m"); tagsIdx++);
4769 if (tagsIdx < args.size() - 1) {
4770 tags = args[tagsIdx + 1];
4771 } else {
4772 dprintf(outFd, "No tags provided.\n");
4773 return BAD_VALUE;
4774 }
4775
4776 size_t clientsIdx; // index of '-c'
4777 String16 clients = kWatchAllClientsFlag; // watch all clients if no clients are provided
4778 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != String16("-c");
4779 clientsIdx++);
4780 if (clientsIdx < args.size() - 1) {
4781 clients = args[clientsIdx + 1];
4782 }
4783 parseClientsToWatchLocked(String8(clients));
4784
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004785 // track tags to initialize future clients with the monitoring information
4786 mMonitorTags = String8(tags);
4787
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004788 bool serviceLock = tryLock(mServiceLock);
4789 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004790 auto cameraClients = mActiveClientManager.getAll();
4791 for (const auto &clientDescriptor: cameraClients) {
4792 if (clientDescriptor == nullptr) { continue; }
4793 sp<BasicClient> client = clientDescriptor->getValue();
4794 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004795
4796 if (isClientWatchedLocked(client.get())) {
4797 client->startWatchingTags(mMonitorTags, outFd);
4798 numWatchedClients++;
4799 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004800 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004801 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
4802
4803 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004804 return OK;
4805}
4806
4807status_t CameraService::stopWatchingTags(int outFd) {
4808 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004809 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004810 mMonitorTags = String8::empty();
4811
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004812 mWatchedClientPackages.clear();
4813 mWatchedClientsDumpCache.clear();
4814
4815 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004816 auto cameraClients = mActiveClientManager.getAll();
4817 for (const auto &clientDescriptor : cameraClients) {
4818 if (clientDescriptor == nullptr) { continue; }
4819 sp<BasicClient> client = clientDescriptor->getValue();
4820 if (client.get() == nullptr) { continue; }
4821 client->stopWatchingTags(outFd);
4822 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004823 dprintf(outFd, "Stopped watching all clients.\n");
4824 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004825 return OK;
4826}
4827
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004828status_t CameraService::printWatchedTags(const Vector<String16> &args, int outFd) {
4829 // Figure outFd refresh interval, if present in args
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004830 useconds_t refreshTimeoutMs = 1000; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004831 if (args.size() > 2) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004832 size_t intervalIdx; // index of '-n'
4833 for (intervalIdx = 2; intervalIdx < args.size() && String16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004834 intervalIdx++);
4835
4836 size_t intervalValIdx = intervalIdx + 1;
4837 if (intervalValIdx < args.size()) {
4838 refreshTimeoutMs = strtol(String8(args[intervalValIdx].string()), nullptr, 10);
4839 if (errno) { return BAD_VALUE; }
4840 }
4841 }
4842
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004843 mLogLock.lock();
4844 bool serviceLock = tryLock(mServiceLock);
4845 // get all watched clients that are currently connected
4846 std::set<String16> connectedMoniterdClients;
4847 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
4848 if (clientDescriptor == nullptr) { continue; }
4849
4850 sp<BasicClient> client = clientDescriptor->getValue();
4851 if (client.get() == nullptr) { continue; }
4852 if (!isClientWatchedLocked(client.get())) { continue; }
4853
4854 connectedMoniterdClients.emplace(client->getPackageName());
4855 }
4856 if (serviceLock) { mServiceLock.unlock(); }
4857
4858 // Print entries in mWatchedClientsDumpCache for clients that are not connected
4859 for (const auto &kv: mWatchedClientsDumpCache) {
4860 const String16 &package = kv.first;
4861 if (connectedMoniterdClients.find(package) != connectedMoniterdClients.end()) {
4862 continue;
4863 }
4864
4865 dprintf(outFd, "Client: %s\n", String8(package).string());
4866 dprintf(outFd, "%s\n", kv.second.c_str());
4867 }
4868 mLogLock.unlock();
4869
4870 if (connectedMoniterdClients.empty()) {
4871 dprintf(outFd, "No watched client active.\n");
4872 return OK;
4873 }
4874
4875 // For connected watched clients, print monitored tags live
4876 return printWatchedTagsUntilInterrupt(refreshTimeoutMs * 1000, outFd);
4877}
4878
4879status_t CameraService::printWatchedTagsUntilInterrupt(useconds_t refreshMicros, int outFd) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004880 std::unordered_map<std::string, std::string> cameraToLastEvent;
4881 auto cameraClients = mActiveClientManager.getAll();
4882
4883 if (cameraClients.empty()) {
4884 dprintf(outFd, "No clients connected.\n");
4885 return OK;
4886 }
4887
4888 dprintf(outFd, "Press Ctrl + C to exit...\n\n");
4889 while (true) {
4890 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004891 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004892 if (clientDescriptor == nullptr) { continue; }
4893 const char* cameraId = clientDescriptor->getKey().string();
4894
4895 // This also initializes the map entries with an empty string
4896 const std::string& lastPrintedEvent = cameraToLastEvent[cameraId];
4897
4898 sp<BasicClient> client = clientDescriptor->getValue();
4899 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004900 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004901
4902 std::vector<std::string> latestEvents;
4903 client->dumpWatchedEventsToVector(latestEvents);
4904
4905 if (!latestEvents.empty()) {
4906 printNewWatchedEvents(outFd,
4907 cameraId,
4908 client->getPackageName(),
4909 latestEvents,
4910 lastPrintedEvent);
4911 cameraToLastEvent[cameraId] = latestEvents[0];
4912 }
4913 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004914 usleep(refreshMicros); // convert ms to us
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004915 }
4916 return OK;
4917}
4918
4919void CameraService::printNewWatchedEvents(int outFd,
4920 const char *cameraId,
4921 const String16 &packageName,
4922 const std::vector<std::string> &events,
4923 const std::string &lastPrintedEvent) {
4924 if (events.empty()) { return; }
4925
4926 // index of lastPrintedEvent in events.
4927 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
4928 size_t lastPrintedIdx;
4929 for (lastPrintedIdx = 0;
4930 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
4931 lastPrintedIdx++);
4932
4933 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
4934
4935 const char *printPackageName = String8(packageName).string();
4936 // print events in chronological order (latest event last)
4937 size_t idxToPrint = lastPrintedIdx;
4938 do {
4939 idxToPrint--;
4940 dprintf(outFd, "%s:%s %s", cameraId, printPackageName, events[idxToPrint].c_str());
4941 } while (idxToPrint != 0);
4942}
4943
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004944void CameraService::parseClientsToWatchLocked(String8 clients) {
4945 mWatchedClientPackages.clear();
4946
4947 const char *allSentinel = String8(kWatchAllClientsFlag).string();
4948
4949 char *tokenized = clients.lockBuffer(clients.size());
4950 char *savePtr;
4951 char *nextClient = strtok_r(tokenized, ",", &savePtr);
4952
4953 while (nextClient != nullptr) {
4954 if (strcmp(nextClient, allSentinel) == 0) {
4955 // Don't need to track any other package if 'all' is present
4956 mWatchedClientPackages.clear();
4957 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
4958 break;
4959 }
4960
4961 // track package names
4962 mWatchedClientPackages.emplace(nextClient);
4963 nextClient = strtok_r(nullptr, ",", &savePtr);
4964 }
4965 clients.unlockBuffer();
4966}
4967
Svet Ganova453d0d2018-01-11 15:37:58 -08004968status_t CameraService::printHelp(int out) {
4969 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07004970 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
4971 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
4972 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004973 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
4974 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
4975 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08004976 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
4977 " Valid values 0=OFF, 1=ON for JPEG\n"
4978 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08004979 " set-camera-mute <0/1> enable or disable camera muting\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004980 " watch <start|stop|dump|live> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08004981 " help print this message\n");
4982}
4983
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07004984bool CameraService::isClientWatched(const BasicClient *client) {
4985 Mutex::Autolock lock(mLogLock);
4986 return isClientWatchedLocked(client);
4987}
4988
4989bool CameraService::isClientWatchedLocked(const BasicClient *client) {
4990 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
4991 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
4992}
4993
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004994int32_t CameraService::updateAudioRestriction() {
4995 Mutex::Autolock lock(mServiceLock);
4996 return updateAudioRestrictionLocked();
4997}
4998
4999int32_t CameraService::updateAudioRestrictionLocked() {
5000 int32_t mode = 0;
5001 // iterate through all active client
5002 for (const auto& i : mActiveClientManager.getAll()) {
5003 const auto clientSp = i->getValue();
5004 mode |= clientSp->getAudioRestriction();
5005 }
5006
5007 bool modeChanged = (mAudioRestriction != mode);
5008 mAudioRestriction = mode;
5009 if (modeChanged) {
5010 mAppOps.setCameraAudioRestriction(mode);
5011 }
5012 return mode;
5013}
5014
Cliff Wud3a05312021-04-26 23:07:31 +08005015void CameraService::clearInjectionParameters() {
5016 {
5017 Mutex::Autolock lock(mInjectionParametersLock);
5018 mInjectionInitPending = true;
5019 mInjectionInternalCamId = "";
5020 }
5021 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08005022 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08005023}
5024
Mathias Agopian65ab4712010-07-14 17:59:35 -07005025}; // namespace android