blob: 28bb781cccc4d1562fd6181b1d957de98df7b4bf [file] [log] [blame]
/*
* 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 <android-base/macros.h>
#include <android-base/parseint.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 <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 <camera/StringUtils.h>
#include <system/camera.h>
#include "CameraService.h"
#include "api1/Camera2Client.h"
#include "api2/CameraDeviceClient.h"
#include "utils/CameraTraces.h"
#include "utils/TagMonitor.h"
#include "utils/CameraThreadState.h"
#include "utils/CameraServiceProxyWrapper.h"
namespace {
const char* kPermissionServiceName = "permission";
}; // namespace anonymous
namespace android {
using binder::Status;
using namespace camera3;
using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
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;
// ----------------------------------------------------------------------------
// 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);
}
// ----------------------------------------------------------------------------
static const std::string sDumpPermission("android.permission.DUMP");
static const std::string sManageCameraPermission("android.permission.MANAGE_CAMERA");
static const std::string sCameraPermission("android.permission.CAMERA");
static const std::string sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
static const std::string
sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
static const std::string sCameraOpenCloseListenerPermission(
"android.permission.CAMERA_OPEN_CLOSE_LISTENER");
static const std::string
sCameraInjectExternalCameraPermission("android.permission.CAMERA_INJECT_EXTERNAL_CAMERA");
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");
// Set to keep track of logged service error events.
static std::set<std::string> sServiceErrorEventSet;
CameraService::CameraService() :
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());
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);
}
}
// The word 'System' here does not refer to clients only on the system
// partition. They just need to have a android system uid.
static bool doesClientHaveSystemUid() {
return (CameraThreadState::getCallingUid() < AID_APP_START);
}
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);
mSensorPrivacyPolicy->registerSelf();
mInjectionStatusListener = new InjectionStatusListener(this);
mAppOps.setCameraAudioRestriction(mAudioRestriction);
sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
if (hcs->registerAsService() != android::OK) {
ALOGE("%s: Failed to register default android.frameworks.cameraservice.service@1.0",
__FUNCTION__);
}
// This needs to be last call in this function, so that it's as close to
// ServiceManager::addService() as possible.
CameraServiceProxyWrapper::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) {
Mutex::Autolock lock(mStatusListenerLock);
for (auto& i : mListenerList) {
if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
i->getListenerUid())) {
ALOGV("Skipping torch callback for system-only camera device %s",
cameraId.c_str());
continue;
}
i->getListener()->onTorchStatusChanged(mapToInterface(status), cameraId);
}
}
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 &deviceId : normalDeviceIds) {
SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
if (getSystemCameraKind(deviceId, &deviceKind) != OK) {
ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.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(deviceId);
}
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, /*overrideToPortrait*/false, /*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(), 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__, newStatus);
return;
}
if (newStatus == StatusInternal::NOT_PRESENT) {
logDeviceRemoved(cameraId, fmt::sprintf("Device status changed from %d to %d", 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);
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::sprintf("Device status changed from %d to %d", 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(), 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(), newHalStatus, 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::sprintf("Device status changed to %d", newStatus));
} else {
logDeviceRemoved(idCombo, fmt::sprintf("Device status changed to %d", 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;
}
listener->getListener()->onPhysicalCameraStatusChanged(mapToInterface(newStatus),
id, physicalId);
}
}
}
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) {
Mutex::Autolock lock(mStatusListenerLock);
for (auto& i : mListenerList) {
i->getListener()->onTorchStrengthLevelChanged(cameraId, newStrengthLevel);
}
}
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(), 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);
}
static bool hasPermissionsForSystemCamera(int callingPid, int callingUid,
bool logPermissionFailure = false) {
return checkPermission(toString16(sSystemCameraPermission), callingPid, callingUid,
logPermissionFailure) &&
checkPermission(toString16(sCameraPermission), callingPid, callingUid);
}
Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
ATRACE_CALL();
Mutex::Autolock l(mServiceLock);
bool hasSystemCameraPermissions =
hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
CameraThreadState::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::getCameraInfo(int cameraId, bool overrideToPortrait,
CameraInfo* cameraInfo) {
ATRACE_CALL();
Mutex::Autolock l(mServiceLock);
std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
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(CameraThreadState::getCallingPid(),
CameraThreadState::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, overrideToPortrait, &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) {
const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
auto callingPid = CameraThreadState::getCallingPid();
auto callingUid = CameraThreadState::getCallingUid();
if (checkPermission(toString16(sSystemCameraPermission), callingPid, callingUid,
/*logPermissionFailure*/false) || getpid() == callingPid) {
deviceIds = &mNormalDeviceIds;
}
if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
ALOGE("%s: input id %d invalid: valid range (0, %zu)",
__FUNCTION__, cameraIdInt, deviceIds->size());
return std::string{};
}
return (*deviceIds)[cameraIdInt];
}
std::string CameraService::cameraIdIntToStr(int cameraIdInt) {
Mutex::Autolock lock(mServiceLock);
return cameraIdIntToStrLocked(cameraIdInt);
}
Status CameraService::getCameraCharacteristics(const std::string& cameraId,
int targetSdkVersion, bool overrideToPortrait, 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");;
}
if (shouldRejectSystemCameraConnection(cameraId)) {
return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
"characteristics for system only device %s: ", cameraId.c_str());
}
Status ret{};
bool overrideForPerfClass =
SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
cameraId, targetSdkVersion);
status_t res = mCameraProviderManager->getCameraCharacteristics(
cameraId, overrideForPerfClass, cameraInfo, overrideToPortrait);
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);
}
}
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_INVALID_OPERATION, "Unable to retrieve camera kind "
"for device %s", cameraId.c_str());
}
int callingPid = CameraThreadState::getCallingPid();
int callingUid = CameraThreadState::getCallingUid();
std::vector<int32_t> tagsRemoved;
// If it's not calling from cameraserver, check the permission only if
// android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
// it would've already been checked in shouldRejectSystemCameraConnection.
if ((callingPid != getpid()) &&
(deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
!checkPermission(toString16(sCameraPermission), callingPid, callingUid)) {
res = cameraInfo->removePermissionEntries(
mCameraProviderManager->getProviderTagIdLocked(cameraId),
&tagsRemoved);
if (res != OK) {
cameraInfo->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(-res), res);
}
}
if (!tagsRemoved.empty()) {
res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
tagsRemoved.data(), tagsRemoved.size());
if (res != OK) {
cameraInfo->clear();
return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
"keys needing permission for device %s: %s (%d)", cameraId.c_str(),
strerror(-res), res);
}
}
return ret;
}
Status CameraService::getTorchStrengthLevel(const std::string& cameraId,
int32_t* torchStrength) {
ATRACE_CALL();
Mutex::Autolock l(mServiceLock);
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,
bool overrideToPortrait, 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, overrideToPortrait,
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, bool overrideToPortrait,
bool forceSlowJpegMode, /*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, packageName, featureId,
cameraId, api1CameraId, facing, sensorOrientation, clientPid, clientUid,
servicePid, overrideForPerfClass, overrideToPortrait, forceSlowJpegMode);
ALOGI("%s: Camera1 API (legacy), override to portrait %d, forceSlowJpegMode %d",
__FUNCTION__, overrideToPortrait, forceSlowJpegMode);
} else { // Camera2 API route
sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
*client = new CameraDeviceClient(cameraService, tmp, packageName,
systemNativeClient, featureId, cameraId, facing, sensorOrientation,
clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait);
ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
}
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 std::move(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", 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", 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", status);
}
return serviceStatus;
}
Status CameraService::initializeShimMetadata(int cameraId) {
int uid = CameraThreadState::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__, /*overrideToPortrait*/ true,
/*forceSlowJpegMode*/false, /*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 = CameraThreadState::clearCallingIdentity();
ret = initializeShimMetadata(cameraId);
CameraThreadState::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");
}
// Can camera service trust the caller based on the calling UID?
static bool isTrustedCallingUid(uid_t uid) {
switch (uid) {
case AID_MEDIA: // mediaserver
case AID_CAMERASERVER: // cameraserver
case AID_RADIO: // telephony
return true;
default:
return false;
}
}
static status_t getUidForPackage(const std::string &packageName, int userId, /*inout*/uid_t& uid,
int err) {
PermissionController pc;
uid = pc.getPackageUid(toString16(packageName), 0);
if (uid <= 0) {
ALOGE("Unknown package: '%s'", packageName.c_str());
dprintf(err, "Unknown package: '%s'\n", packageName.c_str());
return BAD_VALUE;
}
if (userId < 0) {
ALOGE("Invalid user: %d", userId);
dprintf(err, "Invalid user: %d\n", userId);
return BAD_VALUE;
}
uid = multiuser_get_uid(userId, uid);
return NO_ERROR;
}
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 = CameraThreadState::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 = CameraThreadState::getCallingPid();
int callingUid = CameraThreadState::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(), clientUid, clientPid);
}
// 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(), clientUid, clientPid);
}
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());
}
// 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).
if (callingPid != getpid() &&
(deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
!checkPermission(toString16(sCameraPermission), clientPid, clientUid)) {
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(), clientUid, clientPid, 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(), clientUid, clientPid, cameraId.c_str(),
callingUid, procState);
}
// If sensor privacy is enabled then prevent access to the camera
if (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(), clientUid, clientPid, 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 (!doesClientHaveSystemUid() && 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());
}
return Status::ok();
}
status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
auto cameraState = getCameraState(cameraId);
int callingPid = CameraThreadState::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 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);
// 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;
}
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 = CameraThreadState::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
}
CameraThreadState::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,
bool overrideToPortrait,
bool forceSlowJpegMode,
/*out*/
sp<ICamera>* device) {
ATRACE_CALL();
Status ret = Status::ok();
std::string cameraIdStr = cameraIdIntToStr(api1CameraId);
sp<Client> client = nullptr;
ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
/*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
overrideToPortrait, forceSlowJpegMode, /*out*/client);
if(!ret.isOk()) {
logRejected(cameraIdStr, CameraThreadState::getCallingPid(), clientPackageName,
toStdString(ret.toString8()));
return ret;
}
*device = client;
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(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 = CameraThreadState::getCallingPid();
int cUid = CameraThreadState::getCallingUid();
bool systemClient = doesClientHaveSystemUid();
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 (CameraThreadState::getCallingPid() == getpid()) {
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(cPid, cUid, /*logPermissionFailure*/true)) {
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& cameraId,
const std::string& clientPackageName,
const std::optional<std::string>& clientFeatureId,
int clientUid, int oomScoreOffset, int targetSdkVersion,
bool overrideToPortrait,
/*out*/
sp<hardware::camera2::ICameraDeviceUser>* device) {
ATRACE_CALL();
Status ret = Status::ok();
sp<CameraDeviceClient> client = nullptr;
std::string clientPackageNameAdj = clientPackageName;
int callingPid = CameraThreadState::getCallingPid();
bool systemNativeClient = false;
if (doesClientHaveSystemUid() && (clientPackageNameAdj.size() == 0)) {
std::string systemClient =
fmt::sprintf("client.pid<%d>", CameraThreadState::getCallingPid());
clientPackageNameAdj = systemClient;
systemNativeClient = true;
}
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);
int callingUid = CameraThreadState::getCallingUid();
if (clientUid == USE_CALLING_UID) {
clientUserId = multiuser_get_user_id(callingUid);
}
if (CameraServiceProxyWrapper::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(callingPid, CameraThreadState::getCallingUid())) {
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, overrideToPortrait, /*forceSlowJpegMode*/false,
/*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);
}
}
return ret;
}
std::string CameraService::getPackageNameFromUid(int clientUid) {
std::string packageName("");
sp<IServiceManager> sm = defaultServiceManager();
sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
if (binder == 0) {
ALOGE("Cannot get permission service");
// Return empty package name and the further interaction
// with camera will likely fail
return packageName;
}
sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
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,
bool overrideToPortrait, bool forceSlowJpegMode,
/*out*/sp<CLIENT>& device) {
binder::Status ret = binder::Status::ok();
bool isNonSystemNdk = false;
std::string clientPackageName;
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;
int packageUid = (clientUid == USE_CALLING_UID) ?
CameraThreadState::getCallingUid() : clientUid;
clientPackageName = getPackageNameFromUid(packageUid);
} else {
clientPackageName = clientPackageNameMaybe;
}
int originalClientPid = 0;
int packagePid = (clientPid == USE_CALLING_PID) ?
CameraThreadState::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, overrideToPortrait, /*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,
overrideToPortrait, forceSlowJpegMode,
/*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
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);
// Set rotate-and-crop override behavior
if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
} else if (overrideToPortrait && 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;
}
client->setRotateAndCropOverride(rotateAndCropMode);
} else {
client->setRotateAndCropOverride(
CameraServiceProxyWrapper::getRotateAndCropOverride(
clientPackageName, facing, multiuser_get_user_id(clientUid)));
}
// Set camera muting behavior
bool 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 = CameraThreadState::clearCallingIdentity();
// Note AppOp to trigger the "Unblock" dialog
client->noteAppOp();
client->disconnect();
CameraThreadState::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);
} // 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);
CameraServiceProxyWrapper::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);
// Allow only one offline device per camera
auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
if (!incompatibleClients.empty()) {
ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
return BAD_VALUE;
}
std::string monitorTags = isClientWatched(offlineClient.get())
? mMonitorTags : std::string();
auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
if (err != OK) {
ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
return err;
}
auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
if (evicted.size() > 0) {
for (auto& i : evicted) {
ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
__FUNCTION__, i->getKey().c_str());
}
LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
"properly", __FUNCTION__);
return BAD_VALUE;
}
logConnectedOffline(offlineClientDesc->getKey(),
static_cast<int>(offlineClientDesc->getOwnerId()),
offlineClient->getPackageName());
sp<IBinder> remoteCallback = offlineClient->getRemote();
if (remoteCallback != nullptr) {
remoteCallback->linkToDeath(this);
}
} // lock is destroyed, allow further connect calls
return OK;
}
Status CameraService::turnOnTorchWithStrengthLevel(const std::string& cameraId,
int32_t torchStrength, const sp<IBinder>& clientBinder) {
Mutex::Autolock lock(mServiceLock);
ATRACE_CALL();
if (clientBinder == nullptr) {
ALOGE("%s: torch client binder is NULL", __FUNCTION__);
return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
"Torch client binder in null.");
}
int uid = CameraThreadState::getCallingUid();
if (shouldRejectSystemCameraConnection(cameraId)) {
return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
"for system only device %s: ", cameraId.c_str());
}
// verify id is valid
auto state = getCameraState(cameraId);
if (state == nullptr) {
ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
"Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
}
StatusInternal cameraStatus = state->getStatus();
if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
cameraStatus != StatusInternal::PRESENT) {
ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
(int)cameraStatus);
return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
"Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
}
{
Mutex::Autolock al(mTorchStatusMutex);
TorchModeStatus status;
status_t err = getTorchStatusLocked(cameraId, &status);
if (err != OK) {
if (err == NAME_NOT_FOUND) {
return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
"Camera \"%s\" does not have a flash unit", cameraId.c_str());
}
ALOGE("%s: getting current torch status failed for camera %s",
__FUNCTION__, cameraId.c_str());
return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
"Error changing torch strength level for camera \"%s\": %s (%d)",
cameraId.c_str(), strerror(-err), err);
}
if (status == TorchModeStatus::NOT_AVAILABLE) {
if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
ALOGE("%s: torch mode of camera %s is not available because "
"camera is in use.", __FUNCTION__, cameraId.c_str());
return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
"Torch for camera \"%s\" is not available due to an existing camera user",
cameraId.c_str());
} else {
ALOGE("%s: torch mode of camera %s is not available due to "
"insufficient resources", __FUNCTION__, cameraId.c_str());
return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
"Torch for camera \"%s\" is not available due to insufficient resources",
cameraId.c_str());
}
}
}
{
Mutex::Autolock al(mTorchUidMapMutex);
updateTorchUidMapLocked(cameraId, uid);
}
// Check if the current torch strength level is same as the new one.
bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
cameraId, torchStrength);
status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
if (err != OK) {
int32_t errorCode;
std::string msg;
switch (err) {
case -ENOSYS:
msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
cameraId.c_str());
errorCode = ERROR_ILLEGAL_ARGUMENT;
break;
case -EBUSY:
msg = fmt::sprintf("Camera \"%s\" is in use",
cameraId.c_str());
errorCode = ERROR_CAMERA_IN_USE;
break;
case -EINVAL:
msg = fmt::sprintf("Torch strength level %d is not within the "
"valid range.", torchStrength);
errorCode = ERROR_ILLEGAL_ARGUMENT;
break;
default:
msg = "Changing torch strength level failed.";
errorCode = ERROR_INVALID_OPERATION;
}
ALOGE("%s: %s", __FUNCTION__, msg.c_str());
return STATUS_ERROR(errorCode, msg.c_str());
}
{
// update the link to client's death
// Store the last client that turns on each camera's torch mode.
Mutex::Autolock al(mTorchClientMapMutex);
ssize_t index = mTorchClientMap.indexOfKey(cameraId);
if (index == NAME_NOT_FOUND) {
mTorchClientMap.add(cameraId, clientBinder);
} else {
mTorchClientMap.valueAt(index)->unlinkToDeath(this);
mTorchClientMap.replaceValueAt(index, clientBinder);
}
clientBinder->linkToDeath(this);
}
int clientPid = CameraThreadState::getCallingPid();
ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
__FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
if (!shouldSkipTorchStrengthUpdates) {
broadcastTorchStrengthLevel(cameraId, torchStrength);
}
return Status::ok();
}
Status CameraService::setTorchMode(const std::string& cameraId, bool enabled,
const sp<IBinder>& clientBinder) {
Mutex::Autolock lock(mServiceLock);
ATRACE_CALL();
if (enabled && clientBinder == nullptr) {
ALOGE("%s: torch client binder is NULL", __FUNCTION__);
return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
"Torch client Binder is null");
}
int uid = CameraThreadState::getCallingUid();
if (shouldRejectSystemCameraConnection(cameraId)) {
return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
" for system only device %s: ", cameraId.c_str());
}
// verify id is valid.
auto state = getCameraState(cameraId);
if (state == nullptr) {
ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
"Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
}
StatusInternal cameraStatus = state->getStatus();
if (cameraStatus != StatusInternal::PRESENT &&
cameraStatus != StatusInternal::NOT_AVAILABLE) {
ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
(int)cameraStatus);
return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
"Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
}
{
Mutex::Autolock al(mTorchStatusMutex);
TorchModeStatus status;
status_t err = getTorchStatusLocked(cameraId, &status);
if (err != OK) {
if (err == NAME_NOT_FOUND) {
return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
"Camera \"%s\" does not have a flash unit", cameraId.c_str());
}
ALOGE("%s: getting current torch status failed for camera %s",
__FUNCTION__, cameraId.c_str());
return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
"Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
strerror(-err), err);
}
if (status == TorchModeStatus::NOT_AVAILABLE) {
if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
ALOGE("%s: torch mode of camera %s is not available because "
"camera is in use", __FUNCTION__, cameraId.c_str());
return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
"Torch for camera \"%s\" is not available due to an existing camera user",
cameraId.c_str());
} else {
ALOGE("%s: torch mode of camera %s is not available due to "
"insufficient resources", __FUNCTION__, cameraId.c_str());
return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
"Torch for camera \"%s\" is not available due to insufficient resources",
cameraId.c_str());
}
}
}
{
// Update UID map - this is used in the torch status changed callbacks, so must be done
// before setTorchMode
Mutex::Autolock al(mTorchUidMapMutex);
updateTorchUidMapLocked(cameraId, uid);
}
status_t err = mFlashlight->setTorchMode(cameraId, enabled);
if (err != OK) {
int32_t errorCode;
std::string msg;
switch (err) {
case -ENOSYS:
msg = fmt::sprintf("Camera \"%s\" has no flashlight",
cameraId.c_str());
errorCode = ERROR_ILLEGAL_ARGUMENT;
break;
case -EBUSY:
msg = fmt::sprintf("Camera \"%s\" is in use",
cameraId.c_str());
errorCode = ERROR_CAMERA_IN_USE;
break;
default:
msg = fmt::sprintf(
"Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
cameraId.c_str(), enabled, strerror(-err), err);
errorCode = ERROR_INVALID_OPERATION;
}
ALOGE("%s: %s", __FUNCTION__, msg.c_str());
logServiceError(msg, errorCode);
return STATUS_ERROR(errorCode, msg.c_str());
}
{
// update the link to client's death
Mutex::Autolock al(mTorchClientMapMutex);
ssize_t index = mTorchClientMap.indexOfKey(cameraId);
if (enabled) {
if (index == NAME_NOT_FOUND) {
mTorchClientMap.add(cameraId, clientBinder);
} else {
mTorchClientMap.valueAt(index)->unlinkToDeath(this);
mTorchClientMap.replaceValueAt(index, clientBinder);
}
clientBinder->linkToDeath(this);
} else if (index != NAME_NOT_FOUND) {
mTorchClientMap.valueAt(index)->unlinkToDeath(this);
}
}
int clientPid = CameraThreadState::getCallingPid();
std::string torchState = enabled ? "on" : "off";
ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
torchState.c_str(), clientPid);
logTorchEvent(cameraId, torchState, clientPid);
return Status::ok();
}
void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
mTorchUidMap[cameraId].first = uid;
mTorchUidMap[cameraId].second = uid;
} else {
// Set the pending UID
mTorchUidMap[cameraId].first = uid;
}
}
Status CameraService::notifySystemEvent(int32_t eventId,
const std::vector<int32_t>& args) {
const int pid = CameraThreadState::getCallingPid();
const int selfPid = getpid();
// Permission checks
if (pid != selfPid) {
// Ensure we're being called by system_server, or similar process with
// permissions to notify the camera service about system events
if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
const int uid = CameraThreadState::getCallingUid();
ALOGE("Permission Denial: cannot send updates to camera service about system"
" events from pid=%d, uid=%d", pid, uid);
return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
"No permission to send updates to camera service about system events"
" from pid=%d, uid=%d", pid, uid);
}
}
ATRACE_CALL();
switch(eventId) {
case ICameraService::EVENT_USER_SWITCHED: {
// Try to register for UID and sensor privacy policy updates, in case we're recovering
// from a system server crash
mUidPolicy->registerSelf();
mSensorPrivacyPolicy->registerSelf();
doUserSwitch(/*newUserIds*/ args);
break;
}
case ICameraService::EVENT_USB_DEVICE_ATTACHED:
case ICameraService::EVENT_USB_DEVICE_DETACHED: {
if (args.size() != 1) {
return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
"USB Device Event requires 1 argument");
}
// Notify CameraProviderManager for lazy HALs
mCameraProviderManager->notifyUsbDeviceEvent(eventId,
std::to_string(args[0]));
break;
}
case ICameraService::EVENT_NONE:
default: {
ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
eventId);
break;
}
}
return Status::ok();
}
void CameraService::notifyMonitoredUids() {
Mutex::Autolock lock(mStatusListenerLock);
for (const auto& it : mListenerList) {
auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
if (!ret.isOk()) {
ALOGE("%s: Failed to trigger permission callback: %d", __FUNCTION__,
ret.exceptionCode());
}
}
}
Status CameraService::notifyDeviceStateChange(int64_t newState) {
const int pid = CameraThreadState::getCallingPid();
const int selfPid = getpid();
// Permission checks
if (pid != selfPid) {
// Ensure we're being called by system_server, or similar process with
// permissions to notify the camera service about system events
if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
const int uid = CameraThreadState::getCallingUid();
ALOGE("Permission Denial: cannot send updates to camera service about device"
" state changes from pid=%d, uid=%d", pid, uid);
return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
"No permission to send updates to camera service about device state"
" changes from pid=%d, uid=%d", pid, uid);
}
}
ATRACE_CALL();
{
Mutex::Autolock lock(mServiceLock);
mDeviceState = newState;
}
mCameraProviderManager->notifyDeviceStateChange(newState);
return Status::ok();
}
Status CameraService::notifyDisplayConfigurationChange() {
ATRACE_CALL();
const int callingPid = CameraThreadState::getCallingPid();
const int selfPid = getpid();
// Permission checks
if (callingPid != selfPid) {
// Ensure we're being called by system_server, or similar process with
// permissions to notify the camera service about system events
if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
const int uid = CameraThreadState::getCallingUid();
ALOGE("Permission Denial: cannot send updates to camera service about orientation"
" changes from pid=%d, uid=%d", callingPid, uid);
return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
"No permission to send updates to camera service about orientation"
" changes from pid=%d, uid=%d", callingPid, uid);
}
}
Mutex::Autolock lock(mServiceLock);
// Don't do anything if rotate-and-crop override via cmd is active
if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
const auto clients = mActiveClientManager.getAll();
for (auto& current : clients) {
if (current != nullptr) {
const auto basicClient = current->getValue();
if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
basicClient->setRotateAndCropOverride(
CameraServiceProxyWrapper::getRotateAndCropOverride(
basicClient->getPackageName(),
basicClient->getCameraFacing(),
multiuser_get_user_id(basicClient->getClientUid())));
}
}
}
return Status::ok();
}
Status CameraService::getConcurrentCameraIds(
std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
ATRACE_CALL();
if (!concurrentCameraIds) {
ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds 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");
}
// First call into the provider and get the set of concurrent camera
// combinations
std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
mCameraProviderManager->getConcurrentCameraIds();
for (auto &combination : concurrentCameraCombinations) {
std::vector<std::string> validCombination;
for (auto &cameraId : combination) {
// if the camera state is not present, skip
auto state = getCameraState(cameraId);
if (state == nullptr) {
ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
continue;
}
StatusInternal status = state->getStatus();
if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
continue;
}
if (shouldRejectSystemCameraConnection(cameraId)) {
continue;
}
validCombination.push_back(cameraId);
}
if (validCombination.size() != 0) {
concurrentCameraIds->push_back(std::move(validCombination));
}
}
return Status::ok();
}
Status CameraService::isConcurrentSessionConfigurationSupported(
const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
int targetSdkVersion, /*out*/bool* isSupported) {
if (!isSupported) {
ALOGE("%s: isSupported is NULL", __FUNCTION__);
return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
}
if (!mInitialized) {
ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
return STATUS_ERROR(ERROR_DISCONNECTED,
"Camera subsystem is not available");
}
// Check for camera permissions
int callingPid = CameraThreadState::getCallingPid();
int callingUid = CameraThreadState::getCallingUid();
if ((callingPid != getpid()) && !checkPermission(toString16(sCameraPermission), callingPid,
callingUid)) {
ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
return STATUS_ERROR(ERROR_PERMISSION_DENIED,
"android.permission.CAMERA needed to call"
"isConcurrentSessionConfigurationSupported");
}
status_t res =
mCameraProviderManager->isConcurrentSessionConfigurationSupported(
cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
targetSdkVersion, isSupported);
if (res != OK) {
logServiceError("Unable to query session configuration support",
ERROR_INVALID_OPERATION);
return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
"support %s (%d)", strerror(-res), res);
}
return Status::ok();
}
Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
/*out*/
std::vector<hardware::CameraStatus> *cameraStatuses) {
return addListenerHelper(listener, cameraStatuses);
}
binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
std::vector<hardware::CameraStatus>* cameraStatuses) {
return addListenerHelper(listener, cameraStatuses, false, true);
}
Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
/*out*/
std::vector<hardware::CameraStatus> *cameraStatuses,
bool isVendorListener, bool isProcessLocalTest) {
ATRACE_CALL();
ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
if (listener == nullptr) {
ALOGE("%s: Listener must not be null", __FUNCTION__);
return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
}
auto clientUid = CameraThreadState::getCallingUid();
auto clientPid = CameraThreadState::getCallingPid();
bool openCloseCallbackAllowed = checkPermission(toString16(sCameraOpenCloseListenerPermission),
clientPid, clientUid, /*logPermissionFailure*/false);
Mutex::Autolock lock(mServiceLock);
{
Mutex::Autolock lock(mStatusListenerLock);
for (const auto &it : mListenerList) {
if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
ALOGW("%s: Tried to add listener %p which was already subscribed",
__FUNCTION__, listener.get());
return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
}
}
sp<ServiceListener> serviceListener =
new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
openCloseCallbackAllowed);
auto ret = serviceListener->initialize(isProcessLocalTest);
if (ret != NO_ERROR) {
std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
strerror(-ret), ret);
logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
ALOGE("%s: %s", __FUNCTION__, msg.c_str());
return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
}
// The listener still needs to be added to the list of listeners, regardless of what
// permissions the listener process has / whether it is a vendor listener. Since it might be
// eligible to listen to other camera ids.
mListenerList.emplace_back(serviceListener);
mUidPolicy->registerMonitorUid(clientUid);
}
/* Collect current devices and status */
{
Mutex::Autolock lock(mCameraStatesLock);
for (auto& i : mCameraStates) {
cameraStatuses->emplace_back(i.first,
mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
openCloseCallbackAllowed ? i.second->getClientPackage() : std::string());
}
}
// Remove the camera statuses that should be hidden from the client, we do
// this after collecting the states in order to avoid holding
// mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
// the same time.
cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
[this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
ALOGE("%s: Invalid camera id %s, skipping status update",
__FUNCTION__, s.cameraId.c_str());
return true;
}
return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
clientUid);}), cameraStatuses->end());
//cameraStatuses will have non-eligible camera ids removed.
std::set<std::string> idsChosenForCallback;
for (const auto &s : *cameraStatuses) {
idsChosenForCallback.insert(s.cameraId);
}
/*
* Immediately signal current torch status to this listener only
* This may be a subset of all the devices, so don't include it in the response directly
*/
{
Mutex::Autolock al(mTorchStatusMutex);
for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
const std::string &id = mTorchStatusMap.keyAt(i);
// The camera id is visible to the client. Fine to send torch
// callback.
if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
}
}
}
return Status::ok();
}
Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
ATRACE_CALL();
ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
if (listener == 0) {
ALOGE("%s: Listener must not be null", __FUNCTION__);
return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
}
Mutex::Autolock lock(mServiceLock);
{
Mutex::Autolock lock(mStatusListenerLock);
for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
mUidPolicy->unregisterMonitorUid((*it)->getListenerUid());
IInterface::asBinder(listener)->unlinkToDeath(*it);
mListenerList.erase(it);
return Status::ok();
}
}
}
ALOGW("%s: Tried to remove a listener %p which was not subscribed",
__FUNCTION__, listener.get());
return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
}
Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
ATRACE_CALL();
ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
if (parameters == NULL) {
ALOGE("%s: parameters must not be null", __FUNCTION__);
return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
}
Status ret = Status::ok();
CameraParameters shimParams;
if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
// Error logged by caller
return ret;
}
String8 shimParamsString8 = shimParams.flatten();
*parameters = toStdString(shimParamsString8);
return ret;
}
Status CameraService::supportsCameraApi(const std::string& cameraId, int apiVersion,
/*out*/ bool *isSupported) {
ATRACE_CALL();
ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
switch (apiVersion) {
case API_VERSION_1:
case API_VERSION_2:
break;
default:
std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
ALOGE("%s: %s", __FUNCTION__, msg.c_str());
return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
}
int portraitRotation;
auto deviceVersionAndTransport = getDeviceVersion(cameraId, false, &portraitRotation);
if (deviceVersionAndTransport.first == -1) {
std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
ALOGE("%s: %s", __FUNCTION__, msg.c_str());
return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
}
if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
int deviceVersion = deviceVersionAndTransport.first;
switch (deviceVersion) {
case CAMERA_DEVICE_API_VERSION_1_0:
case CAMERA_DEVICE_API_VERSION_3_0:
case CAMERA_DEVICE_API_VERSION_3_1:
if (apiVersion == API_VERSION_2) {
ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "