blob: 516e8f000f6a9de92f69ecb0720142fbe43a1ec3 [file] [log] [blame] [edit]
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "CameraService"
#define ATRACE_TAG ATRACE_TAG_CAMERA
//#define LOG_NDEBUG 0
#include <algorithm>
#include <climits>
#include <stdio.h>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iostream>
#include <sstream>
#include <string>
#include <sys/types.h>
#include <inttypes.h>
#include <pthread.h>
#include <poll.h>
#include <android/hardware/ICamera.h>
#include <android/hardware/ICameraClient.h>
#include <aidl/AidlCameraService.h>
#include <android-base/macros.h>
#include <android-base/parseint.h>
#include <android_companion_virtualdevice_flags.h>
#include <android/companion/virtualnative/IVirtualDeviceManagerNative.h>
#include <binder/ActivityManager.h>
#include <binder/AppOpsManager.h>
#include <binder/IPCThreadState.h>
#include <binder/MemoryBase.h>
#include <binder/MemoryHeapBase.h>
#include <binder/PermissionController.h>
#include <binder/IResultReceiver.h>
#include <binderthreadstate/CallerUtils.h>
#include <com_android_internal_camera_flags.h>
#include <cutils/atomic.h>
#include <cutils/properties.h>
#include <cutils/misc.h>
#include <gui/Surface.h>
#include <hardware/hardware.h>
#include "hidl/HidlCameraService.h"
#include <hidl/HidlTransportSupport.h>
#include <hwbinder/IPCThreadState.h>
#include <memunreachable/memunreachable.h>
#include <media/AudioSystem.h>
#include <media/IMediaHTTPService.h>
#include <media/mediaplayer.h>
#include <mediautils/BatteryNotifier.h>
#include <processinfo/ProcessInfoService.h>
#include <utils/Errors.h>
#include <utils/Log.h>
#include <utils/String16.h>
#include <utils/SystemClock.h>
#include <utils/Trace.h>
#include <utils/CallStack.h>
#include <private/android_filesystem_config.h>
#include <system/camera_vendor_tags.h>
#include <system/camera_metadata.h>
#include <binder/IServiceManager.h>
#include <binder/IActivityManager.h>
#include <camera/CameraUtils.h>
#include <camera/StringUtils.h>
#include <system/camera.h>
#include "CameraService.h"
#include "api1/Camera2Client.h"
#include "api2/CameraDeviceClient.h"
#include "utils/CameraServiceProxyWrapper.h"
#include "utils/CameraTraces.h"
#include "utils/SessionConfigurationUtils.h"
#include "utils/TagMonitor.h"
#include "utils/Utils.h"
namespace {
const char* kPermissionServiceName = "permission";
const char* kActivityServiceName = "activity";
const char* kSensorPrivacyServiceName = "sensor_privacy";
const char* kAppopsServiceName = "appops";
const char* kProcessInfoServiceName = "processinfo";
const char* kVirtualDeviceBackCameraId = "0";
const char* kVirtualDeviceFrontCameraId = "1";
int32_t getDeviceId(const android::CameraMetadata& cameraInfo) {
if (!cameraInfo.exists(ANDROID_INFO_DEVICE_ID)) {
return android::kDefaultDeviceId;
}
const auto &deviceIdEntry = cameraInfo.find(ANDROID_INFO_DEVICE_ID);
return deviceIdEntry.data.i32[0];
}
} // namespace anonymous
namespace android {
using namespace camera3;
using namespace camera3::SessionConfigurationUtils;
using binder::Status;
using companion::virtualnative::IVirtualDeviceManagerNative;
using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
using frameworks::cameraservice::service::implementation::AidlCameraService;
using hardware::ICamera;
using hardware::ICameraClient;
using hardware::ICameraServiceListener;
using hardware::camera2::ICameraInjectionCallback;
using hardware::camera2::ICameraInjectionSession;
using hardware::camera2::utils::CameraIdAndSessionConfiguration;
using hardware::camera2::utils::ConcurrentCameraIdCombination;
namespace flags = com::android::internal::camera::flags;
namespace vd_flags = android::companion::virtualdevice::flags;
// ----------------------------------------------------------------------------
// Logging support -- this is for debugging only
// Use "adb shell dumpsys media.camera -v 1" to change it.
volatile int32_t gLogLevel = 0;
#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
static void setLogLevel(int level) {
android_atomic_write(level, &gLogLevel);
}
int32_t format_as(CameraService::StatusInternal s) {
return fmt::underlying(s);
}
// ----------------------------------------------------------------------------
// Permission strings (references to AttributionAndPermissionUtils for brevity)
static const std::string &sDumpPermission =
AttributionAndPermissionUtils::sDumpPermission;
static const std::string &sManageCameraPermission =
AttributionAndPermissionUtils::sManageCameraPermission;
static const std::string &sCameraSendSystemEventsPermission =
AttributionAndPermissionUtils::sCameraSendSystemEventsPermission;
static const std::string &sCameraInjectExternalCameraPermission =
AttributionAndPermissionUtils::sCameraInjectExternalCameraPermission;
// Constant integer for FGS Logging, used to denote the API type for logger
static const int LOG_FGS_CAMERA_API = 1;
const char *sFileName = "lastOpenSessionDumpFile";
static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
static constexpr int32_t kSystemNativeClientState =
ActivityManager::PROCESS_STATE_PERSISTENT_UI;
static const std::string kServiceName("cameraserver");
const std::string CameraService::kOfflineDevice("offline-");
const std::string CameraService::kWatchAllClientsFlag("all");
constexpr int32_t kInvalidDeviceId = -1;
// Set to keep track of logged service error events.
static std::set<std::string> sServiceErrorEventSet;
CameraService::CameraService(
std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,
std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils) :
AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils == nullptr ?
std::make_shared<AttributionAndPermissionUtils>()\
: attributionAndPermissionUtils),
mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
mEventLog(DEFAULT_EVENT_LOG_LENGTH),
mNumberOfCameras(0),
mNumberOfCamerasWithoutSystemCamera(0),
mSoundRef(0), mInitialized(false),
mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
ALOGI("CameraService started (pid=%d)", getpid());
mAttributionAndPermissionUtils->setCameraService(this);
mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
if (mMemFd == -1) {
ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
}
}
// Enable processes with isolated AID to request the binder
void CameraService::instantiate() {
CameraService::publish(true);
}
void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
if (name != toString16(kAppopsServiceName)) {
return;
}
ALOGV("appops service registered. setting camera audio restriction");
mAppOps.setCameraAudioRestriction(mAudioRestriction);
}
void CameraService::onFirstRef()
{
ALOGI("CameraService process starting");
BnCameraService::onFirstRef();
// Update battery life tracking if service is restarting
BatteryNotifier& notifier(BatteryNotifier::getInstance());
notifier.noteResetCamera();
notifier.noteResetFlashlight();
status_t res = INVALID_OPERATION;
res = enumerateProviders();
if (res == OK) {
mInitialized = true;
}
mUidPolicy = new UidPolicy(this);
mUidPolicy->registerSelf();
mSensorPrivacyPolicy = new SensorPrivacyPolicy(this, mAttributionAndPermissionUtils);
mSensorPrivacyPolicy->registerSelf();
mInjectionStatusListener = new InjectionStatusListener(this);
// appops function setCamerAudioRestriction uses getService which
// is blocking till the appops service is ready. To enable early
// boot availability for cameraservice, use checkService which is
// non blocking and register for notifications
sp<IServiceManager> sm = defaultServiceManager();
sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
if (!binder) {
sm->registerForNotifications(toString16(kAppopsServiceName), this);
} else {
mAppOps.setCameraAudioRestriction(mAudioRestriction);
}
sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
if (hcs->registerAsService() != android::OK) {
// Deprecated, so it will fail to register on newer devices
ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
__FUNCTION__);
}
if (!AidlCameraService::registerService(this)) {
ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
}
// This needs to be last call in this function, so that it's as close to
// ServiceManager::addService() as possible.
mCameraServiceProxyWrapper->pingCameraServiceProxy();
ALOGI("CameraService pinged cameraservice proxy");
}
status_t CameraService::enumerateProviders() {
status_t res;
std::vector<std::string> deviceIds;
std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
{
Mutex::Autolock l(mServiceLock);
if (nullptr == mCameraProviderManager.get()) {
mCameraProviderManager = new CameraProviderManager();
res = mCameraProviderManager->initialize(this);
if (res != OK) {
ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
__FUNCTION__, strerror(-res), res);
logServiceError("Unable to initialize camera provider manager",
ERROR_DISCONNECTED);
return res;
}
}
// Setup vendor tags before we call get_camera_info the first time
// because HAL might need to setup static vendor keys in get_camera_info
// TODO: maybe put this into CameraProviderManager::initialize()?
mCameraProviderManager->setUpVendorTags();
if (nullptr == mFlashlight.get()) {
mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
}
res = mFlashlight->findFlashUnits();
if (res != OK) {
ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
}
deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
}
for (auto& cameraId : deviceIds) {
if (getCameraState(cameraId) == nullptr) {
onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
}
if (unavailPhysicalIds.count(cameraId) > 0) {
for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
}
}
}
// Derive primary rear/front cameras, and filter their charactierstics.
// This needs to be done after all cameras are enumerated and camera ids are sorted.
if (SessionConfigurationUtils::IS_PERF_CLASS) {
// Assume internal cameras are advertised from the same
// provider. If multiple providers are registered at different time,
// and each provider contains multiple internal color cameras, the current
// logic may filter the characteristics of more than one front/rear color
// cameras.
Mutex::Autolock l(mServiceLock);
filterSPerfClassCharacteristicsLocked();
}
return OK;
}
void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
SystemCameraKind systemCameraKind) {
// Get the device id and app-visible camera id for the given HAL-visible camera id.
auto [deviceId, mappedCameraId] =
mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Mutex::Autolock lock(mStatusListenerLock);
for (auto& i : mListenerList) {
if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
i->getListenerUid())) {
ALOGV("%s: Skipping torch callback for system-only camera device %s",
__FUNCTION__, cameraId.c_str());
continue;
}
auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
mappedCameraId, deviceId);
i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
__FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
}
}
CameraService::~CameraService() {
VendorTagDescriptor::clearGlobalVendorTagDescriptor();
mUidPolicy->unregisterSelf();
mSensorPrivacyPolicy->unregisterSelf();
mInjectionStatusListener->removeListener();
}
void CameraService::onNewProviderRegistered() {
enumerateProviders();
}
void CameraService::filterAPI1SystemCameraLocked(
const std::vector<std::string> &normalDeviceIds) {
mNormalDeviceIdsWithoutSystemCamera.clear();
for (auto &cameraId : normalDeviceIds) {
if (vd_flags::camera_device_awareness()) {
CameraMetadata cameraInfo;
status_t res = mCameraProviderManager->getCameraCharacteristics(
cameraId, false, &cameraInfo,
hardware::ICameraService::ROTATION_OVERRIDE_NONE);
int32_t deviceId = kDefaultDeviceId;
if (res != OK) {
ALOGW("%s: Not able to get camera characteristics for camera id %s",
__FUNCTION__, cameraId.c_str());
} else {
deviceId = getDeviceId(cameraInfo);
}
// Cameras associated with non-default device id's (i.e., virtual cameras) can never be
// system cameras, so skip for non-default device id's.
if (deviceId != kDefaultDeviceId) {
continue;
}
}
SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
continue;
}
if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
// All system camera ids will necessarily come after public camera
// device ids as per the HAL interface contract.
break;
}
mNormalDeviceIdsWithoutSystemCamera.push_back(cameraId);
}
ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
mNormalDeviceIdsWithoutSystemCamera.size());
}
status_t CameraService::getSystemCameraKind(const std::string& cameraId,
SystemCameraKind *kind) const {
auto state = getCameraState(cameraId);
if (state != nullptr) {
*kind = state->getSystemCameraKind();
return OK;
}
// Hidden physical camera ids won't have CameraState
return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
}
void CameraService::updateCameraNumAndIds() {
Mutex::Autolock l(mServiceLock);
std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
// Excludes hidden secure cameras
mNumberOfCameras =
systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
mNormalDeviceIds =
mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
filterAPI1SystemCameraLocked(mNormalDeviceIds);
}
void CameraService::filterSPerfClassCharacteristicsLocked() {
// To claim to be S Performance primary cameras, the cameras must be
// backward compatible. So performance class primary camera Ids must be API1
// compatible.
bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
int facing = -1;
int orientation = 0;
int portraitRotation;
getDeviceVersion(cameraId,
/*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
/*out*/&portraitRotation, /*out*/&facing, /*out*/&orientation);
if (facing == -1) {
ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
return;
}
if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
(facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
if (res == OK) {
mPerfClassPrimaryCameraIds.insert(cameraId);
} else {
ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
"camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
break;
}
if (facing == hardware::CAMERA_FACING_BACK) {
firstRearCameraSeen = true;
}
if (facing == hardware::CAMERA_FACING_FRONT) {
firstFrontCameraSeen = true;
}
}
if (firstRearCameraSeen && firstFrontCameraSeen) {
break;
}
}
}
void CameraService::addStates(const std::string& cameraId) {
CameraResourceCost cost;
status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
if (res != OK) {
ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
return;
}
SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
if (res != OK) {
ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
return;
}
std::vector<std::string> physicalCameraIds;
mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
std::set<std::string> conflicting;
for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
conflicting.emplace(cost.conflictingDevices[i]);
}
{
Mutex::Autolock lock(mCameraStatesLock);
mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
conflicting, deviceKind, physicalCameraIds));
}
if (mFlashlight->hasFlashUnit(cameraId)) {
Mutex::Autolock al(mTorchStatusMutex);
mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
}
updateCameraNumAndIds();
logDeviceAdded(cameraId, "Device added");
}
void CameraService::removeStates(const std::string& cameraId) {
updateCameraNumAndIds();
if (mFlashlight->hasFlashUnit(cameraId)) {
Mutex::Autolock al(mTorchStatusMutex);
mTorchStatusMap.removeItem(cameraId);
}
{
Mutex::Autolock lock(mCameraStatesLock);
mCameraStates.erase(cameraId);
}
}
void CameraService::onDeviceStatusChanged(const std::string& cameraId,
CameraDeviceStatus newHalStatus) {
ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
cameraId.c_str(), eToI(newHalStatus));
StatusInternal newStatus = mapToInternal(newHalStatus);
std::shared_ptr<CameraState> state = getCameraState(cameraId);
if (state == nullptr) {
if (newStatus == StatusInternal::PRESENT) {
ALOGI("%s: Unknown camera ID %s, a new camera is added",
__FUNCTION__, cameraId.c_str());
// First add as absent to make sure clients are notified below
addStates(cameraId);
updateStatus(newStatus, cameraId);
} else {
ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
}
return;
}
StatusInternal oldStatus = state->getStatus();
if (oldStatus == newStatus) {
ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__,
eToI(newStatus));
return;
}
if (newStatus == StatusInternal::NOT_PRESENT) {
logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
oldStatus, newStatus));
// Set the device status to NOT_PRESENT, clients will no longer be able to connect
// to this device until the status changes
updateStatus(StatusInternal::NOT_PRESENT, cameraId);
mVirtualDeviceCameraIdMapper.removeCamera(cameraId);
sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
{
// Don't do this in updateStatus to avoid deadlock over mServiceLock
Mutex::Autolock lock(mServiceLock);
// Remove cached shim parameters
state->setShimParams(CameraParameters());
// Remove online as well as offline client from the list of active clients,
// if they are present
clientToDisconnectOnline = removeClientLocked(cameraId);
clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
}
disconnectClient(cameraId, clientToDisconnectOnline);
disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
removeStates(cameraId);
} else {
if (oldStatus == StatusInternal::NOT_PRESENT) {
logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
oldStatus, newStatus));
}
updateStatus(newStatus, cameraId);
}
}
void CameraService::onDeviceStatusChanged(const std::string& id,
const std::string& physicalId,
CameraDeviceStatus newHalStatus) {
ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
__FUNCTION__, id.c_str(), physicalId.c_str(), eToI(newHalStatus));
StatusInternal newStatus = mapToInternal(newHalStatus);
std::shared_ptr<CameraState> state = getCameraState(id);
if (state == nullptr) {
ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
__FUNCTION__, physicalId.c_str(), id.c_str());
return;
}
StatusInternal logicalCameraStatus = state->getStatus();
if (logicalCameraStatus != StatusInternal::PRESENT &&
logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
__FUNCTION__, physicalId.c_str(), eToI(newHalStatus), eToI(logicalCameraStatus));
return;
}
bool updated = false;
if (newStatus == StatusInternal::PRESENT) {
updated = state->removeUnavailablePhysicalId(physicalId);
} else {
updated = state->addUnavailablePhysicalId(physicalId);
}
if (updated) {
std::string idCombo = id + " : " + physicalId;
if (newStatus == StatusInternal::PRESENT) {
logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
} else {
logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
}
// Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
if (getSystemCameraKind(id, &deviceKind) != OK) {
ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
return;
}
Mutex::Autolock lock(mStatusListenerLock);
for (auto& listener : mListenerList) {
if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
listener->getListenerPid(), listener->getListenerUid())) {
ALOGV("Skipping discovery callback for system-only camera device %s",
id.c_str());
continue;
}
auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
mapToInterface(newStatus), id, physicalId, kDefaultDeviceId);
listener->handleBinderStatus(ret,
"%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
__FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
ret.exceptionCode());
}
}
}
void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
if (clientToDisconnect.get() != nullptr) {
ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
__FUNCTION__, id.c_str());
// Notify the client of disconnection
clientToDisconnect->notifyError(
hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
CaptureResultExtras{});
clientToDisconnect->disconnect();
}
}
void CameraService::onTorchStatusChanged(const std::string& cameraId,
TorchModeStatus newStatus) {
SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
if (res != OK) {
ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
cameraId.c_str());
return;
}
Mutex::Autolock al(mTorchStatusMutex);
onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
}
void CameraService::onTorchStatusChanged(const std::string& cameraId,
TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Mutex::Autolock al(mTorchStatusMutex);
onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
}
void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
int32_t newStrengthLevel) {
// Get the device id and app-visible camera id for the given HAL-visible camera id.
auto [deviceId, mappedCameraId] =
mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Mutex::Autolock lock(mStatusListenerLock);
for (auto& i : mListenerList) {
auto ret = i->getListener()->onTorchStrengthLevelChanged(mappedCameraId,
newStrengthLevel, deviceId);
i->handleBinderStatus(ret,
"%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
}
}
void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
__FUNCTION__, cameraId.c_str(), eToI(newStatus));
TorchModeStatus status;
status_t res = getTorchStatusLocked(cameraId, &status);
if (res) {
ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
__FUNCTION__, cameraId.c_str(), strerror(-res), res);
return;
}
if (status == newStatus) {
return;
}
res = setTorchStatusLocked(cameraId, newStatus);
if (res) {
ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
(uint32_t)newStatus, strerror(-res), res);
return;
}
{
// Update battery life logging for flashlight
Mutex::Autolock al(mTorchUidMapMutex);
auto iter = mTorchUidMap.find(cameraId);
if (iter != mTorchUidMap.end()) {
int oldUid = iter->second.second;
int newUid = iter->second.first;
BatteryNotifier& notifier(BatteryNotifier::getInstance());
if (oldUid != newUid) {
// If the UID has changed, log the status and update current UID in mTorchUidMap
if (status == TorchModeStatus::AVAILABLE_ON) {
notifier.noteFlashlightOff(toString8(cameraId), oldUid);
}
if (newStatus == TorchModeStatus::AVAILABLE_ON) {
notifier.noteFlashlightOn(toString8(cameraId), newUid);
}
iter->second.second = newUid;
} else {
// If the UID has not changed, log the status
if (newStatus == TorchModeStatus::AVAILABLE_ON) {
notifier.noteFlashlightOn(toString8(cameraId), oldUid);
} else {
notifier.noteFlashlightOff(toString8(cameraId), oldUid);
}
}
}
}
broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
}
bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const {
// Returns false if this is not an automotive device type.
if (!isAutomotiveDevice())
return false;
// Returns false if no camera id is provided.
if (cam_id.empty())
return false;
SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
// This isn't a known camera ID, so it's not a system camera.
ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
return false;
}
if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
return false;
}
CameraMetadata cameraInfo;
status_t res = mCameraProviderManager->getCameraCharacteristics(
cam_id, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
if (res != OK){
ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
cam_id.c_str());
return false;
}
camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
if (auto_location.count != 1)
return false;
uint8_t location = auto_location.data.u8[0];
if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
(location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
(location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
(location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
return false;
}
return true;
}
Status CameraService::getNumberOfCameras(int32_t type, int32_t deviceId, int32_t devicePolicy,
int32_t* numCameras) {
ATRACE_CALL();
if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
&& (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
*numCameras = mVirtualDeviceCameraIdMapper.getNumberOfCameras(deviceId);
return Status::ok();
}
Mutex::Autolock l(mServiceLock);
bool hasSystemCameraPermissions =
hasPermissionsForSystemCamera(std::string(), getCallingPid(),
getCallingUid());
switch (type) {
case CAMERA_TYPE_BACKWARD_COMPATIBLE:
if (hasSystemCameraPermissions) {
*numCameras = static_cast<int>(mNormalDeviceIds.size());
} else {
*numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
}
break;
case CAMERA_TYPE_ALL:
if (hasSystemCameraPermissions) {
*numCameras = mNumberOfCameras;
} else {
*numCameras = mNumberOfCamerasWithoutSystemCamera;
}
break;
default:
ALOGW("%s: Unknown camera type %d",
__FUNCTION__, type);
return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
"Unknown camera type %d", type);
}
return Status::ok();
}
Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
int32_t deviceId, int32_t devicePolicy,
/* out */
hardware::camera2::impl::CameraMetadataNative* request) {
ATRACE_CALL();
if (!flags::feature_combination_query()) {
return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
"Camera subsystem doesn't support this method!");
}
if (!mInitialized) {
ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
}
std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
devicePolicy);
if (!cameraIdOptional.has_value()) {
std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
unresolvedCameraId.c_str(), deviceId);
ALOGE("%s: %s", __FUNCTION__, msg.c_str());
return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
}
std::string cameraId = cameraIdOptional.value();
binder::Status res;
if (request == nullptr) {
res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
"Camera %s: Error creating default request", cameraId.c_str());
return res;
}
camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
res = SessionConfigurationUtils::mapRequestTemplateFromClient(
cameraId, templateId, &tempId);
if (!res.isOk()) {
ALOGE("%s: Camera %s: failed to map request Template %d",
__FUNCTION__, cameraId.c_str(), templateId);
return res;
}
if (shouldRejectSystemCameraConnection(cameraId)) {
return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
"request for system only device %s: ", cameraId.c_str());
}
CameraMetadata metadata;
status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
if (err == OK) {
request->swap(metadata);
} else if (err == BAD_VALUE) {
res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
"Camera %s: Template ID %d is invalid or not supported: %s (%d)",
cameraId.c_str(), templateId, strerror(-err), err);
} else {
res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
"Camera %s: Error creating default request for template %d: %s (%d)",
cameraId.c_str(), templateId, strerror(-err), err);
}
return res;
}
Status CameraService::isSessionConfigurationWithParametersSupported(
const std::string& unresolvedCameraId, int targetSdkVersion,
const SessionConfiguration& sessionConfiguration,
int32_t deviceId, int32_t devicePolicy,
/*out*/ bool* supported) {
ATRACE_CALL();
if (!flags::feature_combination_query()) {
return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
"Camera subsystem doesn't support this method!");
}
if (!mInitialized) {
ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
}
std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
devicePolicy);
if (!cameraIdOptional.has_value()) {
std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
unresolvedCameraId.c_str(), deviceId);
ALOGE("%s: %s", __FUNCTION__, msg.c_str());
return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
}
std::string cameraId = cameraIdOptional.value();
if (supported == nullptr) {
std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
unresolvedCameraId.c_str());
ALOGE("%s: %s", __FUNCTION__, msg.c_str());
return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
}
if (shouldRejectSystemCameraConnection(cameraId)) {
return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
"session configuration with parameters support for system only device %s: ",
cameraId.c_str());
}
bool overrideForPerfClass = flags::calculate_perf_override_during_session_support() &&
SessionConfigurationUtils::targetPerfClassPrimaryCamera(
mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
auto ret = isSessionConfigurationWithParametersSupportedUnsafe(cameraId,
sessionConfiguration, overrideForPerfClass, supported);
if (flags::analytics_24q3()) {
mCameraServiceProxyWrapper->logFeatureCombinationQuery(cameraId,
getCallingUid(), sessionConfiguration, ret);
}
return ret;
}
Status CameraService::isSessionConfigurationWithParametersSupportedUnsafe(
const std::string& cameraId, const SessionConfiguration& sessionConfiguration,
bool overrideForPerfClass, /*out*/ bool* supported) {
*supported = false;
status_t ret = mCameraProviderManager->isSessionConfigurationSupported(
cameraId, sessionConfiguration, overrideForPerfClass,
/*checkSessionParams=*/true, supported);
binder::Status res;
switch (ret) {
case OK:
// Expected. Do Nothing.
return Status::ok();
case INVALID_OPERATION: {
std::string msg = fmt::sprintf(
"Camera %s: Session configuration with parameters supported query not "
"supported!",
cameraId.c_str());
ALOGW("%s: %s", __FUNCTION__, msg.c_str());
logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
*supported = false;
return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
}
break;
case NAME_NOT_FOUND: {
std::string msg = fmt::sprintf("Camera %s: Unknown camera ID.", cameraId.c_str());
ALOGW("%s: %s", __FUNCTION__, msg.c_str());
logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
*supported = false;
return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
}
break;
default: {
std::string msg = fmt::sprintf(
"Unable to retrieve session configuration support for camera "
"device %s: Error: %s (%d)",
cameraId.c_str(), strerror(-ret), ret);
ALOGE("%s: %s", __FUNCTION__, msg.c_str());
logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
*supported = false;
return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
}
break;
}
}
Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
int targetSdkVersion, int rotationOverride,
const SessionConfiguration& sessionConfiguration, int32_t deviceId, int32_t devicePolicy,
/*out*/ CameraMetadata* outMetadata) {
ATRACE_CALL();
if (outMetadata == nullptr) {
std::string msg =
fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
ALOGE("%s: %s", __FUNCTION__, msg.c_str());
return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
}
if (!mInitialized) {
ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
}
std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
devicePolicy);
if (!cameraIdOptional.has_value()) {
std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
unresolvedCameraId.c_str(), deviceId);
ALOGE("%s: %s", __FUNCTION__, msg.c_str());
return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
}
std::string cameraId = cameraIdOptional.value();
if (shouldRejectSystemCameraConnection(cameraId)) {
return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
"Unable to retrieve camera"
"characteristics for system only device %s: ",
cameraId.c_str());
}
bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
if (flags::check_session_support_before_session_char()) {
bool sessionConfigSupported;
Status res = isSessionConfigurationWithParametersSupportedUnsafe(
cameraId, sessionConfiguration, overrideForPerfClass, &sessionConfigSupported);
if (!res.isOk()) {
// isSessionConfigurationWithParametersSupportedUnsafe should log what went wrong and
// report the correct Status to send to the client. Simply forward the error to
// the client.
outMetadata->clear();
return res;
}
if (!sessionConfigSupported) {
std::string msg = fmt::sprintf(
"Session configuration not supported for camera device %s.", cameraId.c_str());
outMetadata->clear();
return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
}
}
status_t ret = mCameraProviderManager->getSessionCharacteristics(
cameraId, sessionConfiguration, overrideForPerfClass, rotationOverride, outMetadata);
switch (ret) {
case OK:
// Expected, no handling needed.
break;
case INVALID_OPERATION: {
std::string msg = fmt::sprintf(
"Camera %s: Session characteristics query not supported!",
cameraId.c_str());
ALOGW("%s: %s", __FUNCTION__, msg.c_str());
logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
outMetadata->clear();
return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
}
break;
case NAME_NOT_FOUND: {
std::string msg = fmt::sprintf(
"Camera %s: Unknown camera ID.",
cameraId.c_str());
ALOGW("%s: %s", __FUNCTION__, msg.c_str());
logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
outMetadata->clear();
return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
}
break;
default: {
std::string msg = fmt::sprintf(
"Unable to retrieve session characteristics for camera device %s: "
"Error: %s (%d)",
cameraId.c_str(), strerror(-ret), ret);
ALOGE("%s: %s", __FUNCTION__, msg.c_str());
logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
outMetadata->clear();
return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
}
}
Status res = filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
if (flags::analytics_24q3()) {
mCameraServiceProxyWrapper->logSessionCharacteristicsQuery(cameraId,
getCallingUid(), sessionConfiguration, res);
}
return res;
}
Status CameraService::filterSensitiveMetadataIfNeeded(
const std::string& cameraId, CameraMetadata* metadata) {
int callingPid = getCallingPid();
int callingUid = getCallingUid();
if (callingPid == getpid()) {
// Caller is cameraserver; no need to remove keys
return Status::ok();
}
SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
metadata->clear();
return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
"Unable to retrieve camera kind for device %s", cameraId.c_str());
}
if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
// Attempting to query system only camera without system camera permission would have
// failed the shouldRejectSystemCameraConnection in the caller. So if we get here
// for a system only camera, then the caller has the required permission.
// No need to remove keys
return Status::ok();
}
std::vector<int32_t> tagsRemoved;
// Get the device id that owns this camera.
auto [cameraOwnerDeviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
cameraId);
bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid,
cameraOwnerDeviceId);
if (hasCameraPermission) {
// Caller has camera permission; no need to remove keys
return Status::ok();
}
status_t ret = metadata->removePermissionEntries(
mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
if (ret != OK) {
metadata->clear();
return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
"Failed to remove camera characteristics needing camera permission "
"for device %s:%s (%d)",
cameraId.c_str(), strerror(-ret), ret);
}
if (!tagsRemoved.empty()) {
ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
tagsRemoved.data(), tagsRemoved.size());
if (ret != OK) {
metadata->clear();
return STATUS_ERROR_FMT(
ERROR_INVALID_OPERATION,
"Failed to insert camera keys needing permission for device %s: %s (%d)",
cameraId.c_str(), strerror(-ret), ret);
}
}
return Status::ok();
}
Status CameraService::injectSessionParams(
const std::string& cameraId,
const CameraMetadata& sessionParams) {
if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
const int pid = getCallingPid();
const int uid = getCallingUid();
ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
__FUNCTION__, pid, uid);
return STATUS_ERROR(ERROR_PERMISSION_DENIED,
"Permission Denial: no permission to inject session params");
}
// Do not allow session params injection for a virtual camera.
auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
if (deviceId != kDefaultDeviceId) {
return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
"Cannot inject session params for a virtual camera");
}
std::unique_ptr<AutoConditionLock> serviceLockWrapper =
AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
auto clientDescriptor = mActiveClientManager.get(cameraId);
if (clientDescriptor == nullptr) {
ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
"No active client for camera id %s", cameraId.c_str());
}
sp<BasicClient> clientSp = clientDescriptor->getValue();
status_t res = clientSp->injectSessionParams(sessionParams);
if (res != OK) {
return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
"Error injecting session params into camera \"%s\": %s (%d)",
cameraId.c_str(), strerror(-res), res);
}
return Status::ok();
}
std::optional<std::string> CameraService::resolveCameraId(
const std::string& inputCameraId,
int32_t deviceId,
int32_t devicePolicy) {
if ((deviceId == kDefaultDeviceId)
|| (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
auto [storedDeviceId, _] =
mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
if (storedDeviceId != kDefaultDeviceId) {
// Trying to access a virtual camera from default-policy device context, we should fail.
std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
inputCameraId.c_str(), deviceId);
ALOGE("%s: %s", __FUNCTION__, msg.c_str());
return std::nullopt;
}
return inputCameraId;
}
return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
}
Status CameraService::getCameraInfo(int cameraId, int rotationOverride, int32_t deviceId,
int32_t devicePolicy, CameraInfo* cameraInfo) {
ATRACE_CALL();
Mutex::Autolock l(mServiceLock);
std::string cameraIdStr = cameraIdIntToStrLocked(cameraId, deviceId, devicePolicy);
if (cameraIdStr.empty()) {
std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
cameraId, deviceId);
ALOGE("%s: %s", __FUNCTION__, msg.c_str());
return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
}
if (shouldRejectSystemCameraConnection(cameraIdStr)) {
return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
"characteristics for system only device %s: ", cameraIdStr.c_str());
}
if (!mInitialized) {
logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
return STATUS_ERROR(ERROR_DISCONNECTED,
"Camera subsystem is not available");
}
bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
getCallingPid(), getCallingUid());
int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
if (hasSystemCameraPermissions) {
cameraIdBound = mNumberOfCameras;
}
if (cameraId < 0 || cameraId >= cameraIdBound) {
return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
"CameraId is not valid");
}
Status ret = Status::ok();
int portraitRotation;
status_t err = mCameraProviderManager->getCameraInfo(
cameraIdStr, rotationOverride, &portraitRotation, cameraInfo);
if (err != OK) {
ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
"Error retrieving camera info from device %d: %s (%d)", cameraId,
strerror(-err), err);
logServiceError(std::string("Error retrieving camera info from device ")
+ std::to_string(cameraId), ERROR_INVALID_OPERATION);
}
return ret;
}
std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
int32_t deviceId, int32_t devicePolicy) {
if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
&& (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
std::optional<std::string> cameraIdOptional =
mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
}
const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
auto callingPid = getCallingPid();
auto callingUid = getCallingUid();
bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
callingPid, callingUid, /* checkCameraPermissions= */ false);
if (systemCameraPermissions || getpid() == callingPid) {
cameraIds = &mNormalDeviceIds;
}
if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
ALOGE("%s: input id %d invalid: valid range (0, %zu)",
__FUNCTION__, cameraIdInt, cameraIds->size());
return std::string{};
}
return (*cameraIds)[cameraIdInt];
}
std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
int32_t devicePolicy) {
Mutex::Autolock lock(mServiceLock);
return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
}
Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
int targetSdkVersion, int rotationOverride, int32_t deviceId, int32_t devicePolicy,
CameraMetadata* cameraInfo) {
ATRACE_CALL();
if (!cameraInfo) {
ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
}
if (!mInitialized) {
ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
return STATUS_ERROR(ERROR_DISCONNECTED,
"Camera subsystem is not available");;
}
std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
devicePolicy);
if (!cameraIdOptional.has_value()) {
std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
unresolvedCameraId.c_str(), deviceId);
ALOGE("%s: %s", __FUNCTION__, msg.c_str());
return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
}
std::string cameraId = cameraIdOptional.value();
if (shouldRejectSystemCameraConnection(cameraId)) {
return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
"characteristics for system only device %s: ", cameraId.c_str());
}
bool overrideForPerfClass =
SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
cameraId, targetSdkVersion);
status_t res = mCameraProviderManager->getCameraCharacteristics(
cameraId, overrideForPerfClass, cameraInfo, rotationOverride);
if (res != OK) {
if (res == NAME_NOT_FOUND) {
return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
"characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
strerror(-res), res);
} else {
logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
cameraId.c_str()), ERROR_INVALID_OPERATION);
return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
"characteristics for device %s: %s (%d)", cameraId.c_str(),
strerror(-res), res);
}
}
return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
}
Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId, int32_t deviceId,
int32_t devicePolicy, int32_t* torchStrength) {
ATRACE_CALL();
Mutex::Autolock l(mServiceLock);
std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
devicePolicy);
if (!cameraIdOptional.has_value()) {
std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
unresolvedCameraId.c_str(), deviceId);
ALOGE("%s: %s", __FUNCTION__, msg.c_str());
return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
}
std::string cameraId = cameraIdOptional.value();
if (!mInitialized) {
ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
}
if (torchStrength == NULL) {
ALOGE("%s: strength level must not be null.", __FUNCTION__);
return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
}
status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
if (res != OK) {
return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
"strength level for device %s: %s (%d)", cameraId.c_str(),
strerror(-res), res);
}
ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
return Status::ok();
}
std::string CameraService::getFormattedCurrentTime() {
time_t now = time(nullptr);
char formattedTime[64];
strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
return std::string(formattedTime);
}
Status CameraService::getCameraVendorTagDescriptor(
/*out*/
hardware::camera2::params::VendorTagDescriptor* desc) {
ATRACE_CALL();
if (!mInitialized) {
ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
}
sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
if (globalDescriptor != nullptr) {
*desc = *(globalDescriptor.get());
}
return Status::ok();
}
Status CameraService::getCameraVendorTagCache(
/*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
ATRACE_CALL();
if (!mInitialized) {
ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
return STATUS_ERROR(ERROR_DISCONNECTED,
"Camera subsystem not available");
}
sp<VendorTagDescriptorCache> globalCache =
VendorTagDescriptorCache::getGlobalVendorTagCache();
if (globalCache != nullptr) {
*cache = *(globalCache.get());
}
return Status::ok();
}
void CameraService::clearCachedVariables() {
BasicClient::BasicClient::sCameraService = nullptr;
}
std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
int rotationOverride, int* portraitRotation, int* facing,
int* orientation) {
ATRACE_CALL();
int deviceVersion = 0;
status_t res;
hardware::hidl_version maxVersion{0,0};
IPCTransport transport = IPCTransport::INVALID;
res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
if (res != OK || transport == IPCTransport::INVALID) {
ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
cameraId.c_str());
return std::make_pair(-1, IPCTransport::INVALID) ;
}
deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
hardware::CameraInfo info;
if (facing) {
res = mCameraProviderManager->getCameraInfo(cameraId, rotationOverride,
portraitRotation, &info);
if (res != OK) {
return std::make_pair(-1, IPCTransport::INVALID);
}
*facing = info.facing;
if (orientation) {
*orientation = info.orientation;
}
}
return std::make_pair(deviceVersion, transport);
}
Status CameraService::filterGetInfoErrorCode(status_t err) {
switch(err) {
case NO_ERROR:
return Status::ok();
case BAD_VALUE:
return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
"CameraId is not valid for HAL module");
case NO_INIT:
return STATUS_ERROR(ERROR_DISCONNECTED,
"Camera device not available");
default:
return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
"Camera HAL encountered error %d: %s",
err, strerror(-err));
}
}
Status CameraService::makeClient(const sp<CameraService>& cameraService,
const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
const std::optional<std::string>& featureId, const std::string& cameraId,
int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
apiLevel effectiveApiLevel, bool overrideForPerfClass, int rotationOverride,
bool forceSlowJpegMode, const std::string& originalCameraId,
/*out*/sp<BasicClient>* client) {
// For HIDL devices
if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
// Create CameraClient based on device version reported by the HAL.
int deviceVersion = deviceVersionAndTransport.first;
switch(deviceVersion) {
case CAMERA_DEVICE_API_VERSION_1_0:
ALOGE("Camera using old HAL version: %d", deviceVersion);
return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
"Camera device \"%s\" HAL version %d no longer supported",
cameraId.c_str(), deviceVersion);
break;
case CAMERA_DEVICE_API_VERSION_3_0:
case CAMERA_DEVICE_API_VERSION_3_1:
case CAMERA_DEVICE_API_VERSION_3_2:
case CAMERA_DEVICE_API_VERSION_3_3:
case CAMERA_DEVICE_API_VERSION_3_4:
case CAMERA_DEVICE_API_VERSION_3_5:
case CAMERA_DEVICE_API_VERSION_3_6:
case CAMERA_DEVICE_API_VERSION_3_7:
break;
default:
// Should not be reachable
ALOGE("Unknown camera device HAL version: %d", deviceVersion);
return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
"Camera device \"%s\" has unknown HAL version %d",
cameraId.c_str(), deviceVersion);
}
}
if (effectiveApiLevel == API_1) { // Camera1 API route
sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
*client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
api1CameraId, facing, sensorOrientation,
clientPid, clientUid, servicePid, overrideForPerfClass, rotationOverride,
forceSlowJpegMode);
ALOGI("%s: Camera1 API (legacy), rotationOverride %d, forceSlowJpegMode %d",
__FUNCTION__, rotationOverride, forceSlowJpegMode);
} else { // Camera2 API route
sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
*client = new CameraDeviceClient(cameraService, tmp,
cameraService->mCameraServiceProxyWrapper,
cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
overrideForPerfClass, rotationOverride, originalCameraId);
ALOGI("%s: Camera2 API, rotationOverride %d", __FUNCTION__, rotationOverride);
}
return Status::ok();
}
std::string CameraService::toString(std::set<userid_t> intSet) {
std::ostringstream s;
bool first = true;
for (userid_t i : intSet) {
if (first) {
s << std::to_string(i);
first = false;
} else {
s << ", " << std::to_string(i);
}
}
return s.str();
}
int32_t CameraService::mapToInterface(TorchModeStatus status) {
int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
switch (status) {
case TorchModeStatus::NOT_AVAILABLE:
serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
break;
case TorchModeStatus::AVAILABLE_OFF:
serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
break;
case TorchModeStatus::AVAILABLE_ON:
serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
break;
default:
ALOGW("Unknown new flash status: %d", eToI(status));
}
return serviceStatus;
}
CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
switch (status) {
case CameraDeviceStatus::NOT_PRESENT:
serviceStatus = StatusInternal::NOT_PRESENT;
break;
case CameraDeviceStatus::PRESENT:
serviceStatus = StatusInternal::PRESENT;
break;
case CameraDeviceStatus::ENUMERATING:
serviceStatus = StatusInternal::ENUMERATING;
break;
default:
ALOGW("Unknown new HAL device status: %d", eToI(status));
}
return serviceStatus;
}
int32_t CameraService::mapToInterface(StatusInternal status) {
int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
switch (status) {
case StatusInternal::NOT_PRESENT:
serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
break;
case StatusInternal::PRESENT:
serviceStatus = ICameraServiceListener::STATUS_PRESENT;
break;
case StatusInternal::ENUMERATING:
serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
break;
case StatusInternal::NOT_AVAILABLE:
serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
break;
case StatusInternal::UNKNOWN:
serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
break;
default:
ALOGW("Unknown new internal device status: %d", eToI(status));
}
return serviceStatus;
}
Status CameraService::initializeShimMetadata(int cameraId) {
int uid = getCallingUid();
std::string cameraIdStr = std::to_string(cameraId);
Status ret = Status::ok();
sp<Client> tmp = nullptr;
if (!(ret = connectHelper<ICameraClient,Client>(
sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
/*targetSdkVersion*/ __ANDROID_API_FUTURE__,
/*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_OVERRIDE_TO_PORTRAIT,
/*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
).isOk()) {
ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
}
return ret;
}
Status CameraService::getLegacyParametersLazy(int cameraId,
/*out*/
CameraParameters* parameters) {
ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
Status ret = Status::ok();
if (parameters == NULL) {
ALOGE("%s: parameters must not be null", __FUNCTION__);
return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
}
std::string cameraIdStr = std::to_string(cameraId);
// Check if we already have parameters
{
// Scope for service lock
Mutex::Autolock lock(mServiceLock);
auto cameraState = getCameraState(cameraIdStr);
if (cameraState == nullptr) {
ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
"Invalid camera ID: %s", cameraIdStr.c_str());
}
CameraParameters p = cameraState->getShimParams();
if (!p.isEmpty()) {
*parameters = p;
return ret;
}
}
int64_t token = clearCallingIdentity();
ret = initializeShimMetadata(cameraId);
restoreCallingIdentity(token);
if (!ret.isOk()) {
// Error already logged by callee
return ret;
}
// Check for parameters again
{
// Scope for service lock
Mutex::Autolock lock(mServiceLock);
auto cameraState = getCameraState(cameraIdStr);
if (cameraState == nullptr) {
ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
"Invalid camera ID: %s", cameraIdStr.c_str());
}
CameraParameters p = cameraState->getShimParams();
if (!p.isEmpty()) {
*parameters = p;
return ret;
}
}
ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
__FUNCTION__);
return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
}
Status CameraService::validateConnectLocked(const std::string& cameraId,
const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
/*out*/int& originalClientPid) const {
#ifdef __BRILLO__
UNUSED(clientName8);
UNUSED(clientUid);
UNUSED(clientPid);
UNUSED(originalClientPid);
#else
Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
originalClientPid);
if (!allowed.isOk()) {
return allowed;
}
#endif // __BRILLO__
int callingPid = getCallingPid();
if (!mInitialized) {
ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
callingPid);
return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
"No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
}
if (getCameraState(cameraId) == nullptr) {
ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
cameraId.c_str());
return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
"No camera device with ID \"%s\" available", cameraId.c_str());
}
status_t err = checkIfDeviceIsUsable(cameraId);
if (err != NO_ERROR) {
switch(err) {
case -ENODEV:
case -EBUSY:
return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
"No camera device with ID \"%s\" currently available", cameraId.c_str());
default:
return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
"Unknown error connecting to ID \"%s\"", cameraId.c_str());
}
}
return Status::ok();
}
Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
const std::string& clientName, int& clientUid, int& clientPid,
/*out*/int& originalClientPid) const {
int callingPid = getCallingPid();
int callingUid = getCallingUid();
// Check if we can trust clientUid
if (clientUid == USE_CALLING_UID) {
clientUid = callingUid;
} else if (!isTrustedCallingUid(callingUid)) {
ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
"(don't trust clientUid %d)", callingPid, callingUid, clientUid);
return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
"Untrusted caller (calling PID %d, UID %d) trying to "
"forward camera access to camera %s for client %s (PID %d, UID %d)",
callingPid, callingUid, cameraId.c_str(),
clientName.c_str(), clientPid, clientUid);
}
// Check if we can trust clientPid
if (clientPid == USE_CALLING_PID) {
clientPid = callingPid;
} else if (!isTrustedCallingUid(callingUid)) {
ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
"(don't trust clientPid %d)", callingPid, callingUid, clientPid);
return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
"Untrusted caller (calling PID %d, UID %d) trying to "
"forward camera access to camera %s for client %s (PID %d, UID %d)",
callingPid, callingUid, cameraId.c_str(),
clientName.c_str(), clientPid, clientUid);
}
if (shouldRejectSystemCameraConnection(cameraId)) {
ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
cameraId.c_str());
return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
"available", cameraId.c_str());
}
SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
"found while trying to query device kind", cameraId.c_str());
}
// Get the device id that owns this camera.
auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
// If it's not calling from cameraserver, check the permission if the
// device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
// android.permission.SYSTEM_CAMERA for system only camera devices).
bool checkPermissionForCamera =
hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName, deviceId);
if (callingPid != getpid() &&
(deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
"Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
clientName.c_str(), clientPid, clientUid, cameraId.c_str());
}
// Make sure the UID is in an active state to use the camera
if (!mUidPolicy->isUidActive(callingUid, clientName)) {
int32_t procState = mUidPolicy->getProcState(callingUid);
ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
clientPid, clientUid);
return STATUS_ERROR_FMT(ERROR_DISABLED,
"Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
"calling UID %d proc state %" PRId32 ")",
clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
callingUid, procState);
}
// Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
// such as rear view and surround view cannot be disabled and are exempt from sensor privacy
// policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
if ((!isAutomotivePrivilegedClient(callingUid) ||
!isAutomotiveExteriorSystemCamera(cameraId)) &&
mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
return STATUS_ERROR_FMT(ERROR_DISABLED,
"Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
"is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
}
// Only use passed in clientPid to check permission. Use calling PID as the client PID that's
// connected to camera service directly.
originalClientPid = clientPid;
clientPid = callingPid;
userid_t clientUserId = multiuser_get_user_id(clientUid);
// For non-system clients : Only allow clients who are being used by the current foreground
// device user, unless calling from our own process.
if (!callerHasSystemUid() && callingPid != getpid() &&
(mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
"device user %d, currently allowed device users: %s)", callingPid, clientUserId,
toString(mAllowedUsers).c_str());
return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
"Callers from device user %d are not currently allowed to connect to camera \"%s\"",
clientUserId, cameraId.c_str());
}
if (flags::camera_hsum_permission()) {
// If the System User tries to access the camera when the device is running in
// headless system user mode, ensure that client has the required permission
// CAMERA_HEADLESS_SYSTEM_USER.
if (isHeadlessSystemUserMode()
&& (clientUserId == USER_SYSTEM)
&& !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
"Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
User without camera headless system user permission",
clientName.c_str(), clientPid, clientUid, cameraId.c_str());
}
}
return Status::ok();
}
status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
auto cameraState = getCameraState(cameraId);
int callingPid = getCallingPid();
if (cameraState == nullptr) {
ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
cameraId.c_str());
return -ENODEV;
}
StatusInternal currentStatus = cameraState->getStatus();
if (currentStatus == StatusInternal::NOT_PRESENT) {
ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
callingPid, cameraId.c_str());
return -ENODEV;
} else if (currentStatus == StatusInternal::ENUMERATING) {
ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
callingPid, cameraId.c_str());
return -EBUSY;
}
return NO_ERROR;
}
void CameraService::finishConnectLocked(const sp<BasicClient>& client,
const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
// Make a descriptor for the incoming client
auto clientDescriptor =
CameraService::CameraClientManager::makeClientDescriptor(client, desc,
oomScoreOffset, systemNativeClient);
auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
client->getPackageName());
if (evicted.size() > 0) {
// This should never happen - clients should already have been removed in disconnect
for (auto& i : evicted) {
ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
__FUNCTION__, i->getKey().c_str());
}
LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
__FUNCTION__);
}
// And register a death notification for the client callback. Do
// this last to avoid Binder policy where a nested Binder
// transaction might be pre-empted to service the client death
// notification if the client process dies before linkToDeath is
// invoked.
sp<IBinder> remoteCallback = client->getRemote();
if (remoteCallback != nullptr) {
remoteCallback->linkToDeath(this);
}
}
status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
/*out*/
sp<BasicClient>* client,
std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
ATRACE_CALL();
status_t ret = NO_ERROR;
std::vector<DescriptorPtr> evictedClients;
DescriptorPtr clientDescriptor;
{
if (effectiveApiLevel == API_1) {
// If we are using API1, any existing client for this camera ID with the same remote
// should be returned rather than evicted to allow MediaRecorder to work properly.
auto current = mActiveClientManager.get(cameraId);
if (current != nullptr) {
auto clientSp = current->getValue();
if (clientSp.get() != nullptr) { // should never be needed
if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
ALOGW("CameraService connect called with a different"
" API level, evicting prior client...");
} else if (clientSp->getRemote() == remoteCallback) {
ALOGI("CameraService::connect X (PID %d) (second call from same"
" app binder, returning the same client)", clientPid);
*client = clientSp;
return NO_ERROR;
}
}
}
}
// Get state for the given cameraId
auto state = getCameraState(cameraId);
if (state == nullptr) {
ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
clientPid, cameraId.c_str());
// Should never get here because validateConnectLocked should have errored out
return BAD_VALUE;
}
sp<IServiceManager> sm = defaultServiceManager();
sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
// If processinfo service is not available and the client is automotive privileged
// client used for safety critical uses cases such as rear-view and surround-view which
// needs to be available before android boot completes, then use the hardcoded values
// for the process state and priority score. As this scenario is before android system
// services are up and client is native client, hence using NATIVE_ADJ as the priority
// score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
// visible on the top.
clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
} else {
// Get current active client PIDs
std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
ownerPids.push_back(clientPid);
std::vector<int> priorityScores(ownerPids.size());
std::vector<int> states(ownerPids.size());
// Get priority scores of all active PIDs
status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
&ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
if (err != OK) {
ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
return err;
}
// Update all active clients' priorities
std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
for (size_t i = 0; i < ownerPids.size() - 1; i++) {
pidToPriorityMap.emplace(ownerPids[i],
resource_policy::ClientPriority(priorityScores[i], states[i],
/* isVendorClient won't get copied over*/ false,
/* oomScoreOffset won't get copied over*/ 0));
}
mActiveClientManager.updatePriorities(pidToPriorityMap);
int32_t actualScore = priorityScores[priorityScores.size() - 1];
int32_t actualState = states[states.size() - 1];
// Make descriptor for incoming client. We store the oomScoreOffset
// since we might need it later on new handleEvictionsLocked and
// ProcessInfoService would not take that into account.
clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
state->getConflicting(), actualScore, clientPid, actualState,
oomScoreOffset, systemNativeClient);
}
resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
// Find clients that would be evicted
auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
// If the incoming client was 'evicted,' higher priority clients have the camera in the
// background, so we cannot do evictions
if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
" priority).", clientPid);
sp<BasicClient> clientSp = clientDescriptor->getValue();
std::string curTime = getFormattedCurrentTime();
auto incompatibleClients =
mActiveClientManager.getIncompatibleClients(clientDescriptor);
std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
"(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
cameraId.c_str(), packageName.c_str(), clientPid,
clientPriority.getScore(), clientPriority.getState());
for (auto& i : incompatibleClients) {
msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
"(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
i->getKey().c_str(),
i->getValue()->getPackageName().c_str(),
i->getOwnerId(), i->getPriority().getScore(),
i->getPriority().getState());
ALOGE(" Conflicts with: Device %s, client package %s (PID %"
PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
i->getValue()->getPackageName().c_str(), i->getOwnerId(),
i->getPriority().getScore(), i->getPriority().getState());
}
// Log the client's attempt
Mutex::Autolock l(mLogLock);
mEventLog.add(msg);
auto current = mActiveClientManager.get(cameraId);
if (current != nullptr) {
return -EBUSY; // CAMERA_IN_USE
} else {
return -EUSERS; // MAX_CAMERAS_IN_USE
}
}
for (auto& i : evicted) {
sp<BasicClient> clientSp = i->getValue();
if (clientSp.get() == nullptr) {
ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
// TODO: Remove this
LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
__FUNCTION__);
mActiveClientManager.remove(i);
continue;
}
ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
i->getKey().c_str());
evictedClients.push_back(i);
// Log the clients evicted
logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
" %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
" package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
i->getKey().c_str(), clientSp->getPackageName().c_str(),
i->getOwnerId(), i->getPriority().getScore(),
i->getPriority().getState(), cameraId.c_str(),
packageName.c_str(), clientPid, clientPriority.getScore(),
clientPriority.getState()));
// Notify the client of disconnection
clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
CaptureResultExtras());
}
}
// Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
// other clients from connecting in mServiceLockWrapper if held
mServiceLock.unlock();
// Clear caller identity temporarily so client disconnect PID checks work correctly
int64_t token = clearCallingIdentity();
// Destroy evicted clients
for (auto& i : evictedClients) {
// Disconnect is blocking, and should only have returned when HAL has cleaned up
i->getValue()->disconnect(); // Clients will remove themselves from the active client list
}
restoreCallingIdentity(token);
for (const auto& i : evictedClients) {
ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
__FUNCTION__, i->getKey().c_str(), i->getOwnerId());
ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
if (ret == TIMED_OUT) {
ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
"current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
mActiveClientManager.toString().c_str());
return -EBUSY;
}
if (ret != NO_ERROR) {
ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
"current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
ret, mActiveClientManager.toString().c_str());
return ret;
}
}
evictedClients.clear();
// Once clients have been disconnected, relock
mServiceLock.lock();
// Check again if the device was unplugged or something while we weren't holding mServiceLock
if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
return ret;
}
*partial = clientDescriptor;
return NO_ERROR;
}
Status CameraService::connect(
const sp<ICameraClient>& cameraClient,
int api1CameraId,
const std::string& clientPackageName,
int clientUid,
int clientPid,
int targetSdkVersion,
int rotationOverride,
bool forceSlowJpegMode,
int32_t deviceId,
int32_t devicePolicy,
/*out*/
sp<ICamera>* device) {
ATRACE_CALL();
Status ret = Status::ok();
std::string cameraIdStr = cameraIdIntToStr(api1CameraId, deviceId, devicePolicy);
if (cameraIdStr.empty()) {
std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
api1CameraId, deviceId);
ALOGE("%s: %s", __FUNCTION__, msg.c_str());
return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
}
sp<Client> client = nullptr;
ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
/*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
rotationOverride, forceSlowJpegMode, cameraIdStr, /*out*/client);
if (!ret.isOk()) {
logRejected(cameraIdStr, getCallingPid(), clientPackageName, toStdString(ret.toString8()));
return ret;
}
*device = client;
const sp<IServiceManager> sm(defaultServiceManager());
const auto& mActivityManager = getActivityManager();
if (mActivityManager) {
mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
getCallingUid(),
getCallingPid());
}
return ret;
}
bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
bool isVendorListener, int clientPid, int clientUid) {
// If the client is not a vendor client, don't add listener if
// a) the camera is a publicly hidden secure camera OR
// b) the camera is a system only camera and the client doesn't
// have android.permission.SYSTEM_CAMERA permissions.
if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
(systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
!hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
return true;
}
return false;
}
bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
// Rules for rejection:
// 1) If cameraserver tries to access this camera device, accept the
// connection.
// 2) The camera device is a publicly hidden secure camera device AND some
// non system component is trying to access it.
// 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
// and the serving thread is a non hwbinder thread, the client must have
// android.permission.SYSTEM_CAMERA permissions to connect.
int cPid = getCallingPid();
int cUid = getCallingUid();
bool systemClient = callerHasSystemUid();
SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
// This isn't a known camera ID, so it's not a system camera
ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
return false;
}
// (1) Cameraserver trying to connect, accept.
if (isCallerCameraServerNotDelegating()) {
return false;
}
// (2)
if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
return true;
}
// (3) Here we only check for permissions if it is a system only camera device. This is since
// getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
// characteristics) even if clients don't have android.permission.CAMERA. We do not want the
// same behavior for system camera devices.
if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
!hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
ALOGW("Rejecting access to system only camera %s, inadequete permissions",
cameraId.c_str());
return true;
}
return false;
}
Status CameraService::connectDevice(
const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
const std::string& unresolvedCameraId,
const std::string& clientPackageName,
const std::optional<std::string>& clientFeatureId,
int clientUid, int oomScoreOffset, int targetSdkVersion,
int rotationOverride, int32_t deviceId, int32_t devicePolicy,
/*out*/
sp<hardware::camera2::ICameraDeviceUser>* device) {
ATRACE_CALL();
RunThreadWithRealtimePriority priorityBump;
Status ret = Status::ok();
sp<CameraDeviceClient> client = nullptr;
std::string clientPackageNameAdj = clientPackageName;
int callingPid = getCallingPid();
int callingUid = getCallingUid();
bool systemNativeClient = false;
if (callerHasSystemUid() && (clientPackageNameAdj.size() == 0)) {
std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
clientPackageNameAdj = systemClient;
systemNativeClient = true;
}
std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
devicePolicy);
if (!cameraIdOptional.has_value()) {
std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
unresolvedCameraId.c_str(), deviceId);
ALOGE("%s: %s", __FUNCTION__, msg.c_str());
return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
}
std::string cameraId = cameraIdOptional.value();
if (oomScoreOffset < 0) {
std::string msg =
fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
"camera id %s", clientPackageNameAdj.c_str(), callingPid,
cameraId.c_str());
ALOGE("%s: %s", __FUNCTION__, msg.c_str());
return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
}
userid_t clientUserId = multiuser_get_user_id(clientUid);
if (clientUid == USE_CALLING_UID) {
clientUserId = multiuser_get_user_id(callingUid);
}
// Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
// such as rear view and surround view cannot be disabled.
if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
&& mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
std::string msg = "Camera disabled by device policy";
ALOGE("%s: %s", __FUNCTION__, msg.c_str());
return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
}
// enforce system camera permissions
if (oomScoreOffset > 0
&& !hasPermissionsForSystemCamera(cameraId, callingPid,
callingUid)
&& !isTrustedCallingUid(callingUid)) {
std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
"camera id %s without SYSTEM_CAMERA permissions",
clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
ALOGE("%s: %s", __FUNCTION__, msg.c_str());
return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
}
ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
targetSdkVersion, rotationOverride, /*forceSlowJpegMode*/false, unresolvedCameraId,
/*out*/client);
if (!ret.isOk()) {
logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
return ret;
}
*device = client;
Mutex::Autolock lock(mServiceLock);
// Clear the previous cached logs and reposition the
// file offset to beginning of the file to log new data.
// If either truncate or lseek fails, close the previous file and create a new one.
if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
// Close the previous memfd.
close(mMemFd);
// If failure to wipe the data, then create a new file and
// assign the new value to mMemFd.
mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
if (mMemFd == -1) {
ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
}
}
const sp<IServiceManager> sm(defaultServiceManager());
const auto& mActivityManager = getActivityManager();
if (mActivityManager) {
mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
callingUid,
callingPid);
}
return ret;
}
bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
int callingPid, int callingUid) {
if (!isAutomotiveDevice()) {
return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
}
// Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
// safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
"using camera %s", callingUid, cam_id.c_str());
return false;
}
if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
return true;
} else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
return false;
} else if (mSensorPrivacyPolicy->getCameraPrivacyState()
== SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
return false;
} else {
return true;
}
}
return false;
}
std::string CameraService::getPackageNameFromUid(int clientUid) {
std::string packageName("");
sp<IPermissionController> permCtrl;
if (flags::cache_permission_services()) {
permCtrl = getPermissionController();
} else {
sp<IServiceManager> sm = defaultServiceManager();
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
// Using deprecated function to preserve functionality until the
// cache_permission_services flag is removed.
sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
#pragma clang diagnostic pop
if (binder == 0) {
ALOGE("Cannot get permission service");
permCtrl = nullptr;
} else {
permCtrl = interface_cast<IPermissionController>(binder);
}
}
if (permCtrl == nullptr) {
// Return empty package name and the further interaction
// with camera will likely fail
return packageName;
}
Vector<String16> packages;
permCtrl->getPackagesForUid(clientUid, packages);
if (packages.isEmpty()) {
ALOGE("No packages for calling UID %d", clientUid);
// Return empty package name and the further interaction
// with camera will likely fail
return packageName;
}
// Arbitrarily pick the first name in the list
packageName = toStdString(packages[0]);
return packageName;
}
template<class CALLBACK, class CLIENT>
Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
int rotationOverride, bool forceSlowJpegMode,
const std::string& originalCameraId, /*out*/sp<CLIENT>& device) {
binder::Status ret = binder::Status::ok();
bool isNonSystemNdk = false;
std::string clientPackageName;
int packageUid = (clientUid == USE_CALLING_UID) ?
getCallingUid() : clientUid;
if (clientPackageNameMaybe.size() <= 0) {
// NDK calls don't come with package names, but we need one for various cases.
// Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
// do exist. For all authentication cases, all packages under the same UID get the
// same permissions, so picking any associated package name is sufficient. For some
// other cases, this may give inaccurate names for clients in logs.
isNonSystemNdk = true;
clientPackageName = getPackageNameFromUid(packageUid);
} else {
clientPackageName = clientPackageNameMaybe;
}
int originalClientPid = 0;
int packagePid = (clientPid == USE_CALLING_PID) ?
getCallingPid() : clientPid;
ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
"Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
static_cast<int>(effectiveApiLevel));
nsecs_t openTimeNs = systemTime();
sp<CLIENT> client = nullptr;
int facing = -1;
int orientation = 0;
{
// Acquire mServiceLock and prevent other clients from connecting
std::unique_ptr<AutoConditionLock> lock =
AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
if (lock == nullptr) {
ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
, clientPid);
return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
"Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
cameraId.c_str(), clientPackageName.c_str(), clientPid);
}
// Enforce client permissions and do basic validity checks
if (!(ret = validateConnectLocked(cameraId, clientPackageName,
/*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
return ret;
}
// Check the shim parameters after acquiring lock, if they have already been updated and
// we were doing a shim update, return immediately
if (shimUpdateOnly) {
auto cameraState = getCameraState(cameraId);
if (cameraState != nullptr) {
if (!cameraState->getShimParams().isEmpty()) return ret;
}
}
status_t err;
sp<BasicClient> clientTmp = nullptr;
std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
switch (err) {
case -ENODEV:
return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
"No camera device with ID \"%s\" currently available",
cameraId.c_str());
case -EBUSY:
return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
"Higher-priority client using camera, ID \"%s\" currently unavailable",
cameraId.c_str());
case -EUSERS:
return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
"Too many cameras already open, cannot open camera \"%s\"",
cameraId.c_str());
default:
return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
"Unexpected error %s (%d) opening camera \"%s\"",
strerror(-err), err, cameraId.c_str());
}
}
if (clientTmp.get() != nullptr) {
// Handle special case for API1 MediaRecorder where the existing client is returned
device = static_cast<CLIENT*>(clientTmp.get());
return ret;
}
// give flashlight a chance to close devices if necessary.
mFlashlight->prepareDeviceOpen(cameraId);
int portraitRotation;
auto deviceVersionAndTransport =
getDeviceVersion(cameraId, rotationOverride, /*out*/&portraitRotation,
/*out*/&facing, /*out*/&orientation);
if (facing == -1) {
ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
"Unable to get camera device \"%s\" facing", cameraId.c_str());
}
sp<BasicClient> tmp = nullptr;
bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
clientFeatureId, cameraId, api1CameraId, facing,
orientation, clientPid, clientUid, getpid(),
deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
rotationOverride, forceSlowJpegMode, originalCameraId,
/*out*/&tmp)).isOk()) {
return ret;
}
client = static_cast<CLIENT*>(tmp.get());
LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
__FUNCTION__);
std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
err = client->initialize(mCameraProviderManager, monitorTags);
if (err != OK) {
ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
// Errors could be from the HAL module open call or from AppOpsManager
mServiceLock.unlock();
client->disconnect();
mServiceLock.lock();
switch(err) {
case BAD_VALUE:
return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
"Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
case -EBUSY:
return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
"Camera \"%s\" is already open", cameraId.c_str());
case -EUSERS:
return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
"Too many cameras already open, cannot open camera \"%s\"",
cameraId.c_str());
case PERMISSION_DENIED:
return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
"No permission to open camera \"%s\"", cameraId.c_str());
case -EACCES:
return STATUS_ERROR_FMT(ERROR_DISABLED,
"Camera \"%s\" disabled by policy", cameraId.c_str());
case -ENODEV:
default:
return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
"Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
strerror(-err), err);
}
}
// Update shim paremeters for legacy clients
if (effectiveApiLevel == API_1) {
// Assume we have always received a Client subclass for API1
sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
String8 rawParams = shimClient->getParameters();
CameraParameters params(rawParams);
auto cameraState = getCameraState(cameraId);
if (cameraState != nullptr) {
cameraState->setShimParams(params);
} else {
ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
__FUNCTION__, cameraId.c_str());
}
}
// Enable/disable camera service watchdog
client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
CameraMetadata chars;
bool rotateAndCropSupported = true;
err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
&chars, rotationOverride);
if (err == OK) {
auto availableRotateCropEntry = chars.find(
ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
if (availableRotateCropEntry.count <= 1) {
rotateAndCropSupported = false;
}
} else {
ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
cameraId.c_str(), strerror(-err), err);
}
if (rotateAndCropSupported) {
// Set rotate-and-crop override behavior
if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
} else if (rotationOverride != hardware::ICameraService::ROTATION_OVERRIDE_NONE &&
portraitRotation != 0) {
uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
switch (portraitRotation) {
case 90:
rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
break;
case 180:
rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
break;
case 270:
rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
break;
default:
ALOGE("Unexpected portrait rotation: %d", portraitRotation);
break;
}
// Here we're communicating to the client the chosen rotate
// and crop mode to send to the HAL
client->setRotateAndCropOverride(rotateAndCropMode);
} else {
client->setRotateAndCropOverride(
mCameraServiceProxyWrapper->getRotateAndCropOverride(
clientPackageName, facing, multiuser_get_user_id(clientUid)));
}
}
bool autoframingSupported = true;
auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
autoframingSupported = false;
}
if (autoframingSupported) {
// Set autoframing override behaviour
if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
client->setAutoframingOverride(mOverrideAutoframingMode);
} else {
client->setAutoframingOverride(
mCameraServiceProxyWrapper->getAutoframingOverride(
clientPackageName));
}
}
bool isCameraPrivacyEnabled;
if (flags::camera_privacy_allowlist()) {
// Set camera muting behavior.
isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
toString16(client->getPackageName()), cameraId, packagePid, packageUid);
} else {
isCameraPrivacyEnabled =
mSensorPrivacyPolicy->isCameraPrivacyEnabled();
}
if (client->supportsCameraMute()) {
client->setCameraMute(
mOverrideCameraMuteMode || isCameraPrivacyEnabled);
} else if (isCameraPrivacyEnabled) {
// no camera mute supported, but privacy is on! => disconnect
ALOGI("Camera mute not supported for package: %s, camera id: %s",
client->getPackageName().c_str(), cameraId.c_str());
// Do not hold mServiceLock while disconnecting clients, but
// retain the condition blocking other clients from connecting
// in mServiceLockWrapper if held.
mServiceLock.unlock();
// Clear caller identity temporarily so client disconnect PID
// checks work correctly
int64_t token = clearCallingIdentity();
// Note AppOp to trigger the "Unblock" dialog
client->noteAppOp();
client->disconnect();
restoreCallingIdentity(token);
// Reacquire mServiceLock
mServiceLock.lock();
return STATUS_ERROR_FMT(ERROR_DISABLED,
"Camera \"%s\" disabled due to camera mute", cameraId.c_str());
}
if (shimUpdateOnly) {
// If only updating legacy shim parameters, immediately disconnect client
mServiceLock.unlock();
client->disconnect();
mServiceLock.lock();
} else {
// Otherwise, add client to active clients list
finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
}
client->setImageDumpMask(mImageDumpMask);
client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
client->setZoomOverride(mZoomOverrideValue);
} // lock is destroyed, allow further connect calls
// Important: release the mutex here so the client can call back into the service from its
// destructor (can be at the end of the call)
device = client;
int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
effectiveApiLevel, isNonSystemNdk, openLatencyMs);
{
Mutex::Autolock lock(mInjectionParametersLock);
if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
mInjectionInitPending = false;
status_t res = NO_ERROR;
auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
if (clientDescriptor != nullptr) {
sp<BasicClient> clientSp = clientDescriptor->getValue();
res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
if(res != OK) {
return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
"No camera device with ID \"%s\" currently available",
mInjectionExternalCamId.c_str());
}
res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
if (res != OK) {
mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
}
} else {
ALOGE("%s: Internal camera ID = %s 's client does not exist!",
__FUNCTION__, mInjectionInternalCamId.c_str());
res = NO_INIT;
mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
}
}
}
return ret;
}
status_t CameraService::addOfflineClient(const std::string &cameraId,
sp<BasicClient> offlineClient) {
if (offlineClient.get() == nullptr) {
return BAD_VALUE;
}
{
// Acquire mServiceLock and prevent other clients from connecting
std::unique_ptr<AutoConditionLock> lock =
AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
if (lock == nullptr) {
ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
, __FUNCTION__, offlineClient->getClientPid());
return TIMED_OUT;
}
auto onlineClientDesc = mActiveClientManager.get(cameraId);
if (onlineClientDesc.get() == nullptr) {
ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
cameraId.c_str());
return BAD_VALUE;
}
// Offline clients do not evict or conflict with other online devices. Resource sharing
// conflicts are handled by the camera provider which will either succeed or fail before
// reaching this method.
const auto& onlinePriority = onlineClientDesc->getPriority();
auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
/*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
onlineClientDesc->getOwnerId(), onlinePriority.getState(),
// native clients don't have offline processing support.
/*ommScoreOffset*/ 0, /*systemNativeClient*/false);
if (offlineClientDesc == nullptr) {
ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
return BAD_VALUE;
}
// Allow only one offline device per camera
auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
if