CameraService.cpp revision 8d942f9a5c5affcdc6f1138d4ce3bac4b7ee53d5
1/* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#define LOG_TAG "CameraService" 18#define ATRACE_TAG ATRACE_TAG_CAMERA 19//#define LOG_NDEBUG 0 20 21#include <algorithm> 22#include <climits> 23#include <stdio.h> 24#include <cstring> 25#include <ctime> 26#include <string> 27#include <sys/types.h> 28#include <inttypes.h> 29#include <pthread.h> 30 31#include <android/hardware/ICamera.h> 32#include <android/hardware/ICameraClient.h> 33 34#include <android-base/macros.h> 35#include <android-base/parseint.h> 36#include <binder/AppOpsManager.h> 37#include <binder/IPCThreadState.h> 38#include <binder/IServiceManager.h> 39#include <binder/MemoryBase.h> 40#include <binder/MemoryHeapBase.h> 41#include <binder/ProcessInfoService.h> 42#include <cutils/atomic.h> 43#include <cutils/properties.h> 44#include <gui/Surface.h> 45#include <hardware/hardware.h> 46#include <memunreachable/memunreachable.h> 47#include <media/AudioSystem.h> 48#include <media/IMediaHTTPService.h> 49#include <media/mediaplayer.h> 50#include <mediautils/BatteryNotifier.h> 51#include <utils/Errors.h> 52#include <utils/Log.h> 53#include <utils/String16.h> 54#include <utils/Trace.h> 55#include <private/android_filesystem_config.h> 56#include <system/camera_vendor_tags.h> 57#include <system/camera_metadata.h> 58 59#include <system/camera.h> 60 61#include "CameraService.h" 62#include "api1/CameraClient.h" 63#include "api1/Camera2Client.h" 64#include "api2/CameraDeviceClient.h" 65#include "utils/CameraTraces.h" 66 67namespace { 68 const char* kPermissionServiceName = "permission"; 69}; // namespace anonymous 70 71namespace android { 72 73using binder::Status; 74using hardware::ICamera; 75using hardware::ICameraClient; 76using hardware::ICameraServiceListener; 77using hardware::camera::common::V1_0::CameraDeviceStatus; 78using hardware::camera::common::V1_0::TorchModeStatus; 79 80// ---------------------------------------------------------------------------- 81// Logging support -- this is for debugging only 82// Use "adb shell dumpsys media.camera -v 1" to change it. 83volatile int32_t gLogLevel = 0; 84 85#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__); 86#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__); 87 88static void setLogLevel(int level) { 89 android_atomic_write(level, &gLogLevel); 90} 91 92// Convenience methods for constructing binder::Status objects for error returns 93 94#define STATUS_ERROR(errorCode, errorString) \ 95 binder::Status::fromServiceSpecificError(errorCode, \ 96 String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString)) 97 98#define STATUS_ERROR_FMT(errorCode, errorString, ...) \ 99 binder::Status::fromServiceSpecificError(errorCode, \ 100 String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, \ 101 __VA_ARGS__)) 102 103// ---------------------------------------------------------------------------- 104 105extern "C" { 106static void camera_device_status_change( 107 const struct camera_module_callbacks* callbacks, 108 int camera_id, 109 int new_status) { 110 sp<CameraService> cs = const_cast<CameraService*>( 111 static_cast<const CameraService*>(callbacks)); 112 String8 id = String8::format("%d", camera_id); 113 114 CameraDeviceStatus newStatus{CameraDeviceStatus::NOT_PRESENT}; 115 switch (new_status) { 116 case CAMERA_DEVICE_STATUS_NOT_PRESENT: 117 newStatus = CameraDeviceStatus::NOT_PRESENT; 118 break; 119 case CAMERA_DEVICE_STATUS_PRESENT: 120 newStatus = CameraDeviceStatus::PRESENT; 121 break; 122 case CAMERA_DEVICE_STATUS_ENUMERATING: 123 newStatus = CameraDeviceStatus::ENUMERATING; 124 break; 125 default: 126 ALOGW("Unknown device status change to %d", new_status); 127 break; 128 } 129 cs->onDeviceStatusChanged(id, newStatus); 130} 131 132static void torch_mode_status_change( 133 const struct camera_module_callbacks* callbacks, 134 const char* camera_id, 135 int new_status) { 136 if (!callbacks || !camera_id) { 137 ALOGE("%s invalid parameters. callbacks %p, camera_id %p", __FUNCTION__, 138 callbacks, camera_id); 139 } 140 sp<CameraService> cs = const_cast<CameraService*>( 141 static_cast<const CameraService*>(callbacks)); 142 143 TorchModeStatus status; 144 switch (new_status) { 145 case TORCH_MODE_STATUS_NOT_AVAILABLE: 146 status = TorchModeStatus::NOT_AVAILABLE; 147 break; 148 case TORCH_MODE_STATUS_AVAILABLE_OFF: 149 status = TorchModeStatus::AVAILABLE_OFF; 150 break; 151 case TORCH_MODE_STATUS_AVAILABLE_ON: 152 status = TorchModeStatus::AVAILABLE_ON; 153 break; 154 default: 155 ALOGE("Unknown torch status %d", new_status); 156 return; 157 } 158 159 cs->onTorchStatusChanged( 160 String8(camera_id), 161 status); 162} 163} // extern "C" 164 165// ---------------------------------------------------------------------------- 166 167CameraService::CameraService() : 168 mEventLog(DEFAULT_EVENT_LOG_LENGTH), 169 mNumberOfCameras(0), mNumberOfNormalCameras(0), 170 mSoundRef(0), mInitialized(false), mModule(nullptr) { 171 ALOGI("CameraService started (pid=%d)", getpid()); 172 173 this->camera_device_status_change = android::camera_device_status_change; 174 this->torch_mode_status_change = android::torch_mode_status_change; 175 176 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock); 177} 178 179void CameraService::onFirstRef() 180{ 181 ALOGI("CameraService process starting"); 182 183 BnCameraService::onFirstRef(); 184 185 // Update battery life tracking if service is restarting 186 BatteryNotifier& notifier(BatteryNotifier::getInstance()); 187 notifier.noteResetCamera(); 188 notifier.noteResetFlashlight(); 189 190 status_t res = INVALID_OPERATION; 191 192 bool disableTreble = property_get_bool("camera.disable_treble", false); 193 if (disableTreble) { 194 ALOGI("Treble disabled - using legacy path"); 195 res = loadLegacyHalModule(); 196 } else { 197 res = enumerateProviders(); 198 } 199 if (res == OK) { 200 mInitialized = true; 201 } 202 203 CameraService::pingCameraServiceProxy(); 204} 205 206status_t CameraService::loadLegacyHalModule() { 207 camera_module_t *rawModule; 208 int err = hw_get_module(CAMERA_HARDWARE_MODULE_ID, 209 (const hw_module_t **)&rawModule); 210 if (err < 0) { 211 ALOGE("Could not load camera HAL module: %d (%s)", err, strerror(-err)); 212 logServiceError("Could not load camera HAL module", err); 213 return INVALID_OPERATION; 214 } 215 216 mModule = new CameraModule(rawModule); 217 err = mModule->init(); 218 if (err != OK) { 219 ALOGE("Could not initialize camera HAL module: %d (%s)", err, 220 strerror(-err)); 221 logServiceError("Could not initialize camera HAL module", err); 222 223 delete mModule; 224 mModule = nullptr; 225 return INVALID_OPERATION; 226 } 227 ALOGI("Loaded \"%s\" camera module", mModule->getModuleName()); 228 229 mNumberOfCameras = mModule->getNumberOfCameras(); 230 mNumberOfNormalCameras = mNumberOfCameras; 231 232 // Setup vendor tags before we call get_camera_info the first time 233 // because HAL might need to setup static vendor keys in get_camera_info 234 VendorTagDescriptor::clearGlobalVendorTagDescriptor(); 235 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_2) { 236 setUpVendorTags(); 237 } 238 239 mFlashlight = new CameraFlashlight(mModule, this); 240 status_t res = mFlashlight->findFlashUnits(); 241 if (res) { 242 // impossible because we haven't open any camera devices. 243 ALOGE("Failed to find flash units."); 244 } 245 246 int latestStrangeCameraId = INT_MAX; 247 for (int i = 0; i < mNumberOfCameras; i++) { 248 String8 cameraId = String8::format("%d", i); 249 250 // Get camera info 251 252 struct camera_info info; 253 bool haveInfo = true; 254 status_t rc = mModule->getCameraInfo(i, &info); 255 if (rc != NO_ERROR) { 256 ALOGE("%s: Received error loading camera info for device %d, cost and" 257 " conflicting devices fields set to defaults for this device.", 258 __FUNCTION__, i); 259 haveInfo = false; 260 } 261 262 // Check for backwards-compatibility support 263 if (haveInfo) { 264 if (checkCameraCapabilities(i, info, &latestStrangeCameraId) != OK) { 265 delete mModule; 266 mModule = nullptr; 267 return INVALID_OPERATION; 268 } 269 } 270 271 // Defaults to use for cost and conflicting devices 272 int cost = 100; 273 char** conflicting_devices = nullptr; 274 size_t conflicting_devices_length = 0; 275 276 // If using post-2.4 module version, query the cost + conflicting devices from the HAL 277 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_4 && haveInfo) { 278 cost = info.resource_cost; 279 conflicting_devices = info.conflicting_devices; 280 conflicting_devices_length = info.conflicting_devices_length; 281 } 282 283 std::set<String8> conflicting; 284 for (size_t i = 0; i < conflicting_devices_length; i++) { 285 conflicting.emplace(String8(conflicting_devices[i])); 286 } 287 288 // Initialize state for each camera device 289 { 290 Mutex::Autolock lock(mCameraStatesLock); 291 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost, 292 conflicting)); 293 } 294 295 if (mFlashlight->hasFlashUnit(cameraId)) { 296 mTorchStatusMap.add(cameraId, 297 TorchModeStatus::AVAILABLE_OFF); 298 } 299 } 300 301 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_1) { 302 mModule->setCallbacks(this); 303 } 304 305 return OK; 306} 307 308status_t CameraService::enumerateProviders() { 309 mCameraProviderManager = new CameraProviderManager(); 310 status_t res; 311 res = mCameraProviderManager->initialize(this); 312 if (res != OK) { 313 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)", 314 __FUNCTION__, strerror(-res), res); 315 return res; 316 } 317 318 mNumberOfCameras = mCameraProviderManager->getCameraCount(); 319 mNumberOfNormalCameras = mCameraProviderManager->getStandardCameraCount(); 320 321 // Setup vendor tags before we call get_camera_info the first time 322 // because HAL might need to setup static vendor keys in get_camera_info 323 // TODO: maybe put this into CameraProviderManager::initialize()? 324 mCameraProviderManager->setUpVendorTags(); 325 326 mFlashlight = new CameraFlashlight(mCameraProviderManager, this); 327 res = mFlashlight->findFlashUnits(); 328 if (res != OK) { 329 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res); 330 } 331 332 // TODO: Verify device versions are in support 333 334 for (auto& cameraId : mCameraProviderManager->getCameraDeviceIds()) { 335 hardware::camera::common::V1_0::CameraResourceCost cost; 336 res = mCameraProviderManager->getResourceCost(cameraId, &cost); 337 if (res != OK) { 338 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res); 339 continue; 340 } 341 std::set<String8> conflicting; 342 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) { 343 conflicting.emplace(String8(cost.conflictingDevices[i].c_str())); 344 } 345 String8 id8 = String8(cameraId.c_str()); 346 347 Mutex::Autolock lock(mCameraStatesLock); 348 mCameraStates.emplace(id8, 349 std::make_shared<CameraState>(id8, cost.resourceCost, conflicting)); 350 351 if (mFlashlight->hasFlashUnit(id8)) { 352 mTorchStatusMap.add(id8, 353 TorchModeStatus::AVAILABLE_OFF); 354 } 355 } 356 357 return OK; 358} 359 360 361sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() { 362 sp<ICameraServiceProxy> proxyBinder = nullptr; 363#ifndef __BRILLO__ 364 sp<IServiceManager> sm = defaultServiceManager(); 365 // Use checkService because cameraserver normally starts before the 366 // system server and the proxy service. So the long timeout that getService 367 // has before giving up is inappropriate. 368 sp<IBinder> binder = sm->checkService(String16("media.camera.proxy")); 369 if (binder != nullptr) { 370 proxyBinder = interface_cast<ICameraServiceProxy>(binder); 371 } 372#endif 373 return proxyBinder; 374} 375 376void CameraService::pingCameraServiceProxy() { 377 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy(); 378 if (proxyBinder == nullptr) return; 379 proxyBinder->pingForUserUpdate(); 380} 381 382CameraService::~CameraService() { 383 if (mModule) { 384 delete mModule; 385 mModule = nullptr; 386 } 387 VendorTagDescriptor::clearGlobalVendorTagDescriptor(); 388} 389 390void CameraService::onDeviceStatusChanged(const String8& id, 391 CameraDeviceStatus newHalStatus) { 392 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__, 393 id.string(), newHalStatus); 394 395 StatusInternal newStatus = mapToInternal(newHalStatus); 396 397 std::shared_ptr<CameraState> state = getCameraState(id); 398 399 if (state == nullptr) { 400 ALOGE("%s: Bad camera ID %s", __FUNCTION__, id.string()); 401 return; 402 } 403 404 StatusInternal oldStatus = state->getStatus(); 405 406 if (oldStatus == newStatus) { 407 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus); 408 return; 409 } 410 411 if (newStatus == StatusInternal::NOT_PRESENT) { 412 logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus, 413 newStatus)); 414 sp<BasicClient> clientToDisconnect; 415 { 416 // Don't do this in updateStatus to avoid deadlock over mServiceLock 417 Mutex::Autolock lock(mServiceLock); 418 419 // Set the device status to NOT_PRESENT, clients will no longer be able to connect 420 // to this device until the status changes 421 updateStatus(StatusInternal::NOT_PRESENT, id); 422 423 // Remove cached shim parameters 424 state->setShimParams(CameraParameters()); 425 426 // Remove the client from the list of active clients, if there is one 427 clientToDisconnect = removeClientLocked(id); 428 } 429 430 // Disconnect client 431 if (clientToDisconnect.get() != nullptr) { 432 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL", 433 __FUNCTION__, id.string()); 434 // Notify the client of disconnection 435 clientToDisconnect->notifyError( 436 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED, 437 CaptureResultExtras{}); 438 // Ensure not in binder RPC so client disconnect PID checks work correctly 439 LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(), 440 "onDeviceStatusChanged must be called from the camera service process!"); 441 clientToDisconnect->disconnect(); 442 } 443 444 } else { 445 if (oldStatus == StatusInternal::NOT_PRESENT) { 446 logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus, 447 newStatus)); 448 } 449 updateStatus(newStatus, id); 450 } 451 452} 453 454void CameraService::onTorchStatusChanged(const String8& cameraId, 455 TorchModeStatus newStatus) { 456 Mutex::Autolock al(mTorchStatusMutex); 457 onTorchStatusChangedLocked(cameraId, newStatus); 458} 459 460void CameraService::onTorchStatusChangedLocked(const String8& cameraId, 461 TorchModeStatus newStatus) { 462 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d", 463 __FUNCTION__, cameraId.string(), newStatus); 464 465 TorchModeStatus status; 466 status_t res = getTorchStatusLocked(cameraId, &status); 467 if (res) { 468 ALOGE("%s: cannot get torch status of camera %s: %s (%d)", 469 __FUNCTION__, cameraId.string(), strerror(-res), res); 470 return; 471 } 472 if (status == newStatus) { 473 return; 474 } 475 476 res = setTorchStatusLocked(cameraId, newStatus); 477 if (res) { 478 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__, 479 (uint32_t)newStatus, strerror(-res), res); 480 return; 481 } 482 483 { 484 // Update battery life logging for flashlight 485 Mutex::Autolock al(mTorchUidMapMutex); 486 auto iter = mTorchUidMap.find(cameraId); 487 if (iter != mTorchUidMap.end()) { 488 int oldUid = iter->second.second; 489 int newUid = iter->second.first; 490 BatteryNotifier& notifier(BatteryNotifier::getInstance()); 491 if (oldUid != newUid) { 492 // If the UID has changed, log the status and update current UID in mTorchUidMap 493 if (status == TorchModeStatus::AVAILABLE_ON) { 494 notifier.noteFlashlightOff(cameraId, oldUid); 495 } 496 if (newStatus == TorchModeStatus::AVAILABLE_ON) { 497 notifier.noteFlashlightOn(cameraId, newUid); 498 } 499 iter->second.second = newUid; 500 } else { 501 // If the UID has not changed, log the status 502 if (newStatus == TorchModeStatus::AVAILABLE_ON) { 503 notifier.noteFlashlightOn(cameraId, oldUid); 504 } else { 505 notifier.noteFlashlightOff(cameraId, oldUid); 506 } 507 } 508 } 509 } 510 511 { 512 Mutex::Autolock lock(mStatusListenerLock); 513 for (auto& i : mListenerList) { 514 i->onTorchStatusChanged(mapToInterface(newStatus), String16{cameraId}); 515 } 516 } 517} 518 519Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) { 520 ATRACE_CALL(); 521 switch (type) { 522 case CAMERA_TYPE_BACKWARD_COMPATIBLE: 523 *numCameras = mNumberOfNormalCameras; 524 break; 525 case CAMERA_TYPE_ALL: 526 *numCameras = mNumberOfCameras; 527 break; 528 default: 529 ALOGW("%s: Unknown camera type %d", 530 __FUNCTION__, type); 531 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, 532 "Unknown camera type %d", type); 533 } 534 return Status::ok(); 535} 536 537Status CameraService::getCameraInfo(int cameraId, 538 CameraInfo* cameraInfo) { 539 ATRACE_CALL(); 540 if (!mInitialized) { 541 return STATUS_ERROR(ERROR_DISCONNECTED, 542 "Camera subsystem is not available"); 543 } 544 545 if (cameraId < 0 || cameraId >= mNumberOfCameras) { 546 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, 547 "CameraId is not valid"); 548 } 549 550 Status ret = Status::ok(); 551 if (mModule != nullptr) { 552 struct camera_info info; 553 ret = filterGetInfoErrorCode(mModule->getCameraInfo(cameraId, &info)); 554 555 if (ret.isOk()) { 556 cameraInfo->facing = info.facing; 557 cameraInfo->orientation = info.orientation; 558 // CameraInfo is for android.hardware.Camera which does not 559 // support external camera facing. The closest approximation would be 560 // front camera. 561 if (cameraInfo->facing == CAMERA_FACING_EXTERNAL) { 562 cameraInfo->facing = hardware::CAMERA_FACING_FRONT; 563 } 564 } 565 } else { 566 status_t err = mCameraProviderManager->getCameraInfo(std::to_string(cameraId), cameraInfo); 567 if (err != OK) { 568 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, 569 "Error retrieving camera info from device %d: %s (%d)", cameraId, 570 strerror(-err), err); 571 } 572 } 573 return ret; 574} 575 576int CameraService::cameraIdToInt(const String8& cameraId) { 577 int id; 578 bool success = base::ParseInt(cameraId.string(), &id, 0); 579 if (!success) { 580 return -1; 581 } 582 return id; 583} 584 585Status CameraService::getCameraCharacteristics(const String16& cameraId, 586 CameraMetadata* cameraInfo) { 587 ATRACE_CALL(); 588 if (!cameraInfo) { 589 ALOGE("%s: cameraInfo is NULL", __FUNCTION__); 590 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL"); 591 } 592 593 if (!mInitialized) { 594 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__); 595 return STATUS_ERROR(ERROR_DISCONNECTED, 596 "Camera subsystem is not available");; 597 } 598 599 Status ret{}; 600 601 if (mModule != nullptr) { 602 int id = cameraIdToInt(String8(cameraId)); 603 604 if (id < 0 || id >= mNumberOfCameras) { 605 ALOGE("%s: Invalid camera id: %d", __FUNCTION__, id); 606 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, 607 "Invalid camera id: %d", id); 608 } 609 610 int version = getDeviceVersion(String8(cameraId)); 611 if (version < CAMERA_DEVICE_API_VERSION_3_0) { 612 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Can't get camera characteristics" 613 " for devices with HAL version < 3.0, %d is version %x", id, version); 614 } 615 616 struct camera_info info; 617 ret = filterGetInfoErrorCode(mModule->getCameraInfo(id, &info)); 618 if (ret.isOk()) { 619 *cameraInfo = info.static_camera_characteristics; 620 } 621 } else { 622 status_t res = mCameraProviderManager->getCameraCharacteristics( 623 String16::std_string(cameraId), cameraInfo); 624 if (res != OK) { 625 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera " 626 "characteristics for device %s: %s (%d)", String8(cameraId).string(), 627 strerror(-res), res); 628 } 629 } 630 631 return ret; 632} 633 634int CameraService::getCallingPid() { 635 return IPCThreadState::self()->getCallingPid(); 636} 637 638int CameraService::getCallingUid() { 639 return IPCThreadState::self()->getCallingUid(); 640} 641 642String8 CameraService::getFormattedCurrentTime() { 643 time_t now = time(nullptr); 644 char formattedTime[64]; 645 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now)); 646 return String8(formattedTime); 647} 648 649Status CameraService::getCameraVendorTagDescriptor( 650 /*out*/ 651 hardware::camera2::params::VendorTagDescriptor* desc) { 652 ATRACE_CALL(); 653 if (!mInitialized) { 654 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__); 655 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available"); 656 } 657 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor(); 658 if (globalDescriptor != nullptr) { 659 *desc = *(globalDescriptor.get()); 660 } 661 return Status::ok(); 662} 663 664int CameraService::getDeviceVersion(const String8& cameraId, int* facing) { 665 ATRACE_CALL(); 666 667 int deviceVersion = 0; 668 669 if (mModule != nullptr) { 670 int id = cameraIdToInt(cameraId); 671 if (id < 0) return -1; 672 673 struct camera_info info; 674 if (mModule->getCameraInfo(id, &info) != OK) { 675 return -1; 676 } 677 678 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) { 679 deviceVersion = info.device_version; 680 } else { 681 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0; 682 } 683 684 if (facing) { 685 *facing = info.facing; 686 } 687 } else { 688 status_t res; 689 hardware::hidl_version maxVersion{0,0}; 690 res = mCameraProviderManager->getHighestSupportedVersion(String8::std_string(cameraId), 691 &maxVersion); 692 if (res != OK) return -1; 693 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor()); 694 695 hardware::CameraInfo info; 696 if (facing) { 697 res = mCameraProviderManager->getCameraInfo(String8::std_string(cameraId), &info); 698 if (res != OK) return -1; 699 *facing = info.facing; 700 } 701 } 702 return deviceVersion; 703} 704 705Status CameraService::filterGetInfoErrorCode(status_t err) { 706 switch(err) { 707 case NO_ERROR: 708 return Status::ok(); 709 case BAD_VALUE: 710 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, 711 "CameraId is not valid for HAL module"); 712 case NO_INIT: 713 return STATUS_ERROR(ERROR_DISCONNECTED, 714 "Camera device not available"); 715 default: 716 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, 717 "Camera HAL encountered error %d: %s", 718 err, strerror(-err)); 719 } 720} 721 722bool CameraService::setUpVendorTags() { 723 ATRACE_CALL(); 724 if (mModule == nullptr) return false; 725 726 vendor_tag_ops_t vOps = vendor_tag_ops_t(); 727 728 // Check if vendor operations have been implemented 729 if (!mModule->isVendorTagDefined()) { 730 ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__); 731 return false; 732 } 733 734 mModule->getVendorTagOps(&vOps); 735 736 // Ensure all vendor operations are present 737 if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL || 738 vOps.get_section_name == NULL || vOps.get_tag_name == NULL || 739 vOps.get_tag_type == NULL) { 740 ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions." 741 , __FUNCTION__); 742 return false; 743 } 744 745 // Read all vendor tag definitions into a descriptor 746 sp<VendorTagDescriptor> desc; 747 status_t res; 748 if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc)) 749 != OK) { 750 ALOGE("%s: Could not generate descriptor from vendor tag operations," 751 "received error %s (%d). Camera clients will not be able to use" 752 "vendor tags", __FUNCTION__, strerror(res), res); 753 return false; 754 } 755 756 // Set the global descriptor to use with camera metadata 757 VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc); 758 return true; 759} 760 761Status CameraService::makeClient(const sp<CameraService>& cameraService, 762 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId, 763 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode, 764 int halVersion, int deviceVersion, apiLevel effectiveApiLevel, 765 /*out*/sp<BasicClient>* client) { 766 767 if (halVersion < 0 || halVersion == deviceVersion) { 768 // Default path: HAL version is unspecified by caller, create CameraClient 769 // based on device version reported by the HAL. 770 switch(deviceVersion) { 771 case CAMERA_DEVICE_API_VERSION_1_0: 772 if (effectiveApiLevel == API_1) { // Camera1 API route 773 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get()); 774 *client = new CameraClient(cameraService, tmp, packageName, cameraIdToInt(cameraId), 775 facing, clientPid, clientUid, getpid(), legacyMode); 776 } else { // Camera2 API route 777 ALOGW("Camera using old HAL version: %d", deviceVersion); 778 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL, 779 "Camera device \"%s\" HAL version %d does not support camera2 API", 780 cameraId.string(), deviceVersion); 781 } 782 break; 783 case CAMERA_DEVICE_API_VERSION_3_0: 784 case CAMERA_DEVICE_API_VERSION_3_1: 785 case CAMERA_DEVICE_API_VERSION_3_2: 786 case CAMERA_DEVICE_API_VERSION_3_3: 787 case CAMERA_DEVICE_API_VERSION_3_4: 788 if (effectiveApiLevel == API_1) { // Camera1 API route 789 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get()); 790 *client = new Camera2Client(cameraService, tmp, packageName, cameraIdToInt(cameraId), 791 facing, clientPid, clientUid, servicePid, legacyMode); 792 } else { // Camera2 API route 793 sp<hardware::camera2::ICameraDeviceCallbacks> tmp = 794 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get()); 795 *client = new CameraDeviceClient(cameraService, tmp, packageName, cameraId, 796 facing, clientPid, clientUid, servicePid); 797 } 798 break; 799 default: 800 // Should not be reachable 801 ALOGE("Unknown camera device HAL version: %d", deviceVersion); 802 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, 803 "Camera device \"%s\" has unknown HAL version %d", 804 cameraId.string(), deviceVersion); 805 } 806 } else { 807 // A particular HAL version is requested by caller. Create CameraClient 808 // based on the requested HAL version. 809 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 && 810 halVersion == CAMERA_DEVICE_API_VERSION_1_0) { 811 // Only support higher HAL version device opened as HAL1.0 device. 812 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get()); 813 *client = new CameraClient(cameraService, tmp, packageName, cameraIdToInt(cameraId), 814 facing, clientPid, clientUid, servicePid, legacyMode); 815 } else { 816 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet. 817 ALOGE("Invalid camera HAL version %x: HAL %x device can only be" 818 " opened as HAL %x device", halVersion, deviceVersion, 819 CAMERA_DEVICE_API_VERSION_1_0); 820 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, 821 "Camera device \"%s\" (HAL version %d) cannot be opened as HAL version %d", 822 cameraId.string(), deviceVersion, halVersion); 823 } 824 } 825 return Status::ok(); 826} 827 828String8 CameraService::toString(std::set<userid_t> intSet) { 829 String8 s(""); 830 bool first = true; 831 for (userid_t i : intSet) { 832 if (first) { 833 s.appendFormat("%d", i); 834 first = false; 835 } else { 836 s.appendFormat(", %d", i); 837 } 838 } 839 return s; 840} 841 842int32_t CameraService::mapToInterface(TorchModeStatus status) { 843 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE; 844 switch (status) { 845 case TorchModeStatus::NOT_AVAILABLE: 846 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE; 847 break; 848 case TorchModeStatus::AVAILABLE_OFF: 849 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF; 850 break; 851 case TorchModeStatus::AVAILABLE_ON: 852 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON; 853 break; 854 default: 855 ALOGW("Unknown new flash status: %d", status); 856 } 857 return serviceStatus; 858} 859 860CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) { 861 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT; 862 switch (status) { 863 case CameraDeviceStatus::NOT_PRESENT: 864 serviceStatus = StatusInternal::NOT_PRESENT; 865 break; 866 case CameraDeviceStatus::PRESENT: 867 serviceStatus = StatusInternal::PRESENT; 868 break; 869 case CameraDeviceStatus::ENUMERATING: 870 serviceStatus = StatusInternal::ENUMERATING; 871 break; 872 default: 873 ALOGW("Unknown new HAL device status: %d", status); 874 } 875 return serviceStatus; 876} 877 878int32_t CameraService::mapToInterface(StatusInternal status) { 879 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT; 880 switch (status) { 881 case StatusInternal::NOT_PRESENT: 882 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT; 883 break; 884 case StatusInternal::PRESENT: 885 serviceStatus = ICameraServiceListener::STATUS_PRESENT; 886 break; 887 case StatusInternal::ENUMERATING: 888 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING; 889 break; 890 case StatusInternal::NOT_AVAILABLE: 891 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE; 892 break; 893 case StatusInternal::UNKNOWN: 894 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN; 895 break; 896 default: 897 ALOGW("Unknown new internal device status: %d", status); 898 } 899 return serviceStatus; 900} 901 902Status CameraService::initializeShimMetadata(int cameraId) { 903 int uid = getCallingUid(); 904 905 String16 internalPackageName("cameraserver"); 906 String8 id = String8::format("%d", cameraId); 907 Status ret = Status::ok(); 908 sp<Client> tmp = nullptr; 909 if (!(ret = connectHelper<ICameraClient,Client>( 910 sp<ICameraClient>{nullptr}, id, static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED), 911 internalPackageName, uid, USE_CALLING_PID, 912 API_1, /*legacyMode*/ false, /*shimUpdateOnly*/ true, 913 /*out*/ tmp) 914 ).isOk()) { 915 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().string()); 916 } 917 return ret; 918} 919 920Status CameraService::getLegacyParametersLazy(int cameraId, 921 /*out*/ 922 CameraParameters* parameters) { 923 924 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId); 925 926 Status ret = Status::ok(); 927 928 if (parameters == NULL) { 929 ALOGE("%s: parameters must not be null", __FUNCTION__); 930 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null"); 931 } 932 933 String8 id = String8::format("%d", cameraId); 934 935 // Check if we already have parameters 936 { 937 // Scope for service lock 938 Mutex::Autolock lock(mServiceLock); 939 auto cameraState = getCameraState(id); 940 if (cameraState == nullptr) { 941 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string()); 942 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, 943 "Invalid camera ID: %s", id.string()); 944 } 945 CameraParameters p = cameraState->getShimParams(); 946 if (!p.isEmpty()) { 947 *parameters = p; 948 return ret; 949 } 950 } 951 952 int64_t token = IPCThreadState::self()->clearCallingIdentity(); 953 ret = initializeShimMetadata(cameraId); 954 IPCThreadState::self()->restoreCallingIdentity(token); 955 if (!ret.isOk()) { 956 // Error already logged by callee 957 return ret; 958 } 959 960 // Check for parameters again 961 { 962 // Scope for service lock 963 Mutex::Autolock lock(mServiceLock); 964 auto cameraState = getCameraState(id); 965 if (cameraState == nullptr) { 966 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string()); 967 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, 968 "Invalid camera ID: %s", id.string()); 969 } 970 CameraParameters p = cameraState->getShimParams(); 971 if (!p.isEmpty()) { 972 *parameters = p; 973 return ret; 974 } 975 } 976 977 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.", 978 __FUNCTION__); 979 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters"); 980} 981 982// Can camera service trust the caller based on the calling UID? 983static bool isTrustedCallingUid(uid_t uid) { 984 switch (uid) { 985 case AID_MEDIA: // mediaserver 986 case AID_CAMERASERVER: // cameraserver 987 case AID_RADIO: // telephony 988 return true; 989 default: 990 return false; 991 } 992} 993 994Status CameraService::validateConnectLocked(const String8& cameraId, 995 const String8& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid, 996 /*out*/int& originalClientPid) const { 997 998#ifdef __BRILLO__ 999 UNUSED(clientName8); 1000 UNUSED(clientUid); 1001 UNUSED(clientPid); 1002 UNUSED(originalClientPid); 1003#else 1004 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid, 1005 originalClientPid); 1006 if (!allowed.isOk()) { 1007 return allowed; 1008 } 1009#endif // __BRILLO__ 1010 1011 int callingPid = getCallingPid(); 1012 1013 if (!mInitialized) { 1014 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)", 1015 callingPid); 1016 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, 1017 "No camera HAL module available to open camera device \"%s\"", cameraId.string()); 1018 } 1019 1020 if (getCameraState(cameraId) == nullptr) { 1021 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid, 1022 cameraId.string()); 1023 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, 1024 "No camera device with ID \"%s\" available", cameraId.string()); 1025 } 1026 1027 status_t err = checkIfDeviceIsUsable(cameraId); 1028 if (err != NO_ERROR) { 1029 switch(err) { 1030 case -ENODEV: 1031 case -EBUSY: 1032 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, 1033 "No camera device with ID \"%s\" currently available", cameraId.string()); 1034 default: 1035 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, 1036 "Unknown error connecting to ID \"%s\"", cameraId.string()); 1037 } 1038 } 1039 return Status::ok(); 1040} 1041 1042Status CameraService::validateClientPermissionsLocked(const String8& cameraId, 1043 const String8& clientName8, int& clientUid, int& clientPid, 1044 /*out*/int& originalClientPid) const { 1045 int callingPid = getCallingPid(); 1046 int callingUid = getCallingUid(); 1047 1048 // Check if we can trust clientUid 1049 if (clientUid == USE_CALLING_UID) { 1050 clientUid = callingUid; 1051 } else if (!isTrustedCallingUid(callingUid)) { 1052 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected " 1053 "(don't trust clientUid %d)", callingPid, callingUid, clientUid); 1054 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED, 1055 "Untrusted caller (calling PID %d, UID %d) trying to " 1056 "forward camera access to camera %s for client %s (PID %d, UID %d)", 1057 callingPid, callingUid, cameraId.string(), 1058 clientName8.string(), clientUid, clientPid); 1059 } 1060 1061 // Check if we can trust clientPid 1062 if (clientPid == USE_CALLING_PID) { 1063 clientPid = callingPid; 1064 } else if (!isTrustedCallingUid(callingUid)) { 1065 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected " 1066 "(don't trust clientPid %d)", callingPid, callingUid, clientPid); 1067 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED, 1068 "Untrusted caller (calling PID %d, UID %d) trying to " 1069 "forward camera access to camera %s for client %s (PID %d, UID %d)", 1070 callingPid, callingUid, cameraId.string(), 1071 clientName8.string(), clientUid, clientPid); 1072 } 1073 1074 // If it's not calling from cameraserver, check the permission. 1075 if (callingPid != getpid() && 1076 !checkPermission(String16("android.permission.CAMERA"), clientPid, clientUid)) { 1077 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid); 1078 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED, 1079 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission", 1080 clientName8.string(), clientUid, clientPid, cameraId.string()); 1081 } 1082 1083 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's 1084 // connected to camera service directly. 1085 originalClientPid = clientPid; 1086 clientPid = callingPid; 1087 1088 userid_t clientUserId = multiuser_get_user_id(clientUid); 1089 1090 // Only allow clients who are being used by the current foreground device user, unless calling 1091 // from our own process. 1092 if (callingPid != getpid() && (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) { 1093 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from " 1094 "device user %d, currently allowed device users: %s)", callingPid, clientUserId, 1095 toString(mAllowedUsers).string()); 1096 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED, 1097 "Callers from device user %d are not currently allowed to connect to camera \"%s\"", 1098 clientUserId, cameraId.string()); 1099 } 1100 1101 return Status::ok(); 1102} 1103 1104status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const { 1105 auto cameraState = getCameraState(cameraId); 1106 int callingPid = getCallingPid(); 1107 if (cameraState == nullptr) { 1108 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid, 1109 cameraId.string()); 1110 return -ENODEV; 1111 } 1112 1113 StatusInternal currentStatus = cameraState->getStatus(); 1114 if (currentStatus == StatusInternal::NOT_PRESENT) { 1115 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)", 1116 callingPid, cameraId.string()); 1117 return -ENODEV; 1118 } else if (currentStatus == StatusInternal::ENUMERATING) { 1119 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)", 1120 callingPid, cameraId.string()); 1121 return -EBUSY; 1122 } 1123 1124 return NO_ERROR; 1125} 1126 1127void CameraService::finishConnectLocked(const sp<BasicClient>& client, 1128 const CameraService::DescriptorPtr& desc) { 1129 1130 // Make a descriptor for the incoming client 1131 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc); 1132 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor); 1133 1134 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()), 1135 String8(client->getPackageName())); 1136 1137 if (evicted.size() > 0) { 1138 // This should never happen - clients should already have been removed in disconnect 1139 for (auto& i : evicted) { 1140 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect", 1141 __FUNCTION__, i->getKey().string()); 1142 } 1143 1144 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly", 1145 __FUNCTION__); 1146 } 1147 1148 // And register a death notification for the client callback. Do 1149 // this last to avoid Binder policy where a nested Binder 1150 // transaction might be pre-empted to service the client death 1151 // notification if the client process dies before linkToDeath is 1152 // invoked. 1153 sp<IBinder> remoteCallback = client->getRemote(); 1154 if (remoteCallback != nullptr) { 1155 remoteCallback->linkToDeath(this); 1156 } 1157} 1158 1159status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid, 1160 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName, 1161 /*out*/ 1162 sp<BasicClient>* client, 1163 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) { 1164 ATRACE_CALL(); 1165 status_t ret = NO_ERROR; 1166 std::vector<DescriptorPtr> evictedClients; 1167 DescriptorPtr clientDescriptor; 1168 { 1169 if (effectiveApiLevel == API_1) { 1170 // If we are using API1, any existing client for this camera ID with the same remote 1171 // should be returned rather than evicted to allow MediaRecorder to work properly. 1172 1173 auto current = mActiveClientManager.get(cameraId); 1174 if (current != nullptr) { 1175 auto clientSp = current->getValue(); 1176 if (clientSp.get() != nullptr) { // should never be needed 1177 if (!clientSp->canCastToApiClient(effectiveApiLevel)) { 1178 ALOGW("CameraService connect called from same client, but with a different" 1179 " API level, evicting prior client..."); 1180 } else if (clientSp->getRemote() == remoteCallback) { 1181 ALOGI("CameraService::connect X (PID %d) (second call from same" 1182 " app binder, returning the same client)", clientPid); 1183 *client = clientSp; 1184 return NO_ERROR; 1185 } 1186 } 1187 } 1188 } 1189 1190 // Get current active client PIDs 1191 std::vector<int> ownerPids(mActiveClientManager.getAllOwners()); 1192 ownerPids.push_back(clientPid); 1193 1194 std::vector<int> priorityScores(ownerPids.size()); 1195 std::vector<int> states(ownerPids.size()); 1196 1197 // Get priority scores of all active PIDs 1198 status_t err = ProcessInfoService::getProcessStatesScoresFromPids( 1199 ownerPids.size(), &ownerPids[0], /*out*/&states[0], 1200 /*out*/&priorityScores[0]); 1201 if (err != OK) { 1202 ALOGE("%s: Priority score query failed: %d", 1203 __FUNCTION__, err); 1204 return err; 1205 } 1206 1207 // Update all active clients' priorities 1208 std::map<int,resource_policy::ClientPriority> pidToPriorityMap; 1209 for (size_t i = 0; i < ownerPids.size() - 1; i++) { 1210 pidToPriorityMap.emplace(ownerPids[i], 1211 resource_policy::ClientPriority(priorityScores[i], states[i])); 1212 } 1213 mActiveClientManager.updatePriorities(pidToPriorityMap); 1214 1215 // Get state for the given cameraId 1216 auto state = getCameraState(cameraId); 1217 if (state == nullptr) { 1218 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)", 1219 clientPid, cameraId.string()); 1220 // Should never get here because validateConnectLocked should have errored out 1221 return BAD_VALUE; 1222 } 1223 1224 // Make descriptor for incoming client 1225 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId, 1226 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()), 1227 state->getConflicting(), 1228 priorityScores[priorityScores.size() - 1], 1229 clientPid, 1230 states[states.size() - 1]); 1231 1232 // Find clients that would be evicted 1233 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor); 1234 1235 // If the incoming client was 'evicted,' higher priority clients have the camera in the 1236 // background, so we cannot do evictions 1237 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) { 1238 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher" 1239 " priority).", clientPid); 1240 1241 sp<BasicClient> clientSp = clientDescriptor->getValue(); 1242 String8 curTime = getFormattedCurrentTime(); 1243 auto incompatibleClients = 1244 mActiveClientManager.getIncompatibleClients(clientDescriptor); 1245 1246 String8 msg = String8::format("%s : DENIED connect device %s client for package %s " 1247 "(PID %d, score %d state %d) due to eviction policy", curTime.string(), 1248 cameraId.string(), packageName.string(), clientPid, 1249 priorityScores[priorityScores.size() - 1], 1250 states[states.size() - 1]); 1251 1252 for (auto& i : incompatibleClients) { 1253 msg.appendFormat("\n - Blocked by existing device %s client for package %s" 1254 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")", 1255 i->getKey().string(), 1256 String8{i->getValue()->getPackageName()}.string(), 1257 i->getOwnerId(), i->getPriority().getScore(), 1258 i->getPriority().getState()); 1259 ALOGE(" Conflicts with: Device %s, client package %s (PID %" 1260 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().string(), 1261 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(), 1262 i->getPriority().getScore(), i->getPriority().getState()); 1263 } 1264 1265 // Log the client's attempt 1266 Mutex::Autolock l(mLogLock); 1267 mEventLog.add(msg); 1268 1269 return -EBUSY; 1270 } 1271 1272 for (auto& i : evicted) { 1273 sp<BasicClient> clientSp = i->getValue(); 1274 if (clientSp.get() == nullptr) { 1275 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__); 1276 1277 // TODO: Remove this 1278 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list", 1279 __FUNCTION__); 1280 mActiveClientManager.remove(i); 1281 continue; 1282 } 1283 1284 ALOGE("CameraService::connect evicting conflicting client for camera ID %s", 1285 i->getKey().string()); 1286 evictedClients.push_back(i); 1287 1288 // Log the clients evicted 1289 logEvent(String8::format("EVICT device %s client held by package %s (PID" 1290 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for" 1291 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")", 1292 i->getKey().string(), String8{clientSp->getPackageName()}.string(), 1293 i->getOwnerId(), i->getPriority().getScore(), 1294 i->getPriority().getState(), cameraId.string(), 1295 packageName.string(), clientPid, 1296 priorityScores[priorityScores.size() - 1], 1297 states[states.size() - 1])); 1298 1299 // Notify the client of disconnection 1300 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED, 1301 CaptureResultExtras()); 1302 } 1303 } 1304 1305 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking 1306 // other clients from connecting in mServiceLockWrapper if held 1307 mServiceLock.unlock(); 1308 1309 // Clear caller identity temporarily so client disconnect PID checks work correctly 1310 int64_t token = IPCThreadState::self()->clearCallingIdentity(); 1311 1312 // Destroy evicted clients 1313 for (auto& i : evictedClients) { 1314 // Disconnect is blocking, and should only have returned when HAL has cleaned up 1315 i->getValue()->disconnect(); // Clients will remove themselves from the active client list 1316 } 1317 1318 IPCThreadState::self()->restoreCallingIdentity(token); 1319 1320 for (const auto& i : evictedClients) { 1321 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")", 1322 __FUNCTION__, i->getKey().string(), i->getOwnerId()); 1323 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS); 1324 if (ret == TIMED_OUT) { 1325 ALOGE("%s: Timed out waiting for client for device %s to disconnect, " 1326 "current clients:\n%s", __FUNCTION__, i->getKey().string(), 1327 mActiveClientManager.toString().string()); 1328 return -EBUSY; 1329 } 1330 if (ret != NO_ERROR) { 1331 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), " 1332 "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret), 1333 ret, mActiveClientManager.toString().string()); 1334 return ret; 1335 } 1336 } 1337 1338 evictedClients.clear(); 1339 1340 // Once clients have been disconnected, relock 1341 mServiceLock.lock(); 1342 1343 // Check again if the device was unplugged or something while we weren't holding mServiceLock 1344 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) { 1345 return ret; 1346 } 1347 1348 *partial = clientDescriptor; 1349 return NO_ERROR; 1350} 1351 1352Status CameraService::connect( 1353 const sp<ICameraClient>& cameraClient, 1354 int cameraId, 1355 const String16& clientPackageName, 1356 int clientUid, 1357 int clientPid, 1358 /*out*/ 1359 sp<ICamera>* device) { 1360 1361 ATRACE_CALL(); 1362 Status ret = Status::ok(); 1363 String8 id = String8::format("%d", cameraId); 1364 sp<Client> client = nullptr; 1365 ret = connectHelper<ICameraClient,Client>(cameraClient, id, 1366 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, clientPid, API_1, 1367 /*legacyMode*/ false, /*shimUpdateOnly*/ false, 1368 /*out*/client); 1369 1370 if(!ret.isOk()) { 1371 logRejected(id, getCallingPid(), String8(clientPackageName), 1372 ret.toString8()); 1373 return ret; 1374 } 1375 1376 *device = client; 1377 return ret; 1378} 1379 1380Status CameraService::connectLegacy( 1381 const sp<ICameraClient>& cameraClient, 1382 int cameraId, int halVersion, 1383 const String16& clientPackageName, 1384 int clientUid, 1385 /*out*/ 1386 sp<ICamera>* device) { 1387 1388 ATRACE_CALL(); 1389 String8 id = String8::format("%d", cameraId); 1390 if (mModule != nullptr) { 1391 int apiVersion = mModule->getModuleApiVersion(); 1392 if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED && 1393 apiVersion < CAMERA_MODULE_API_VERSION_2_3) { 1394 /* 1395 * Either the HAL version is unspecified in which case this just creates 1396 * a camera client selected by the latest device version, or 1397 * it's a particular version in which case the HAL must supported 1398 * the open_legacy call 1399 */ 1400 String8 msg = String8::format("Camera HAL module version %x too old for connectLegacy!", 1401 apiVersion); 1402 ALOGE("%s: %s", 1403 __FUNCTION__, msg.string()); 1404 logRejected(id, getCallingPid(), String8(clientPackageName), 1405 msg); 1406 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string()); 1407 } 1408 } 1409 1410 Status ret = Status::ok(); 1411 sp<Client> client = nullptr; 1412 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion, 1413 clientPackageName, clientUid, USE_CALLING_PID, API_1, 1414 /*legacyMode*/ true, /*shimUpdateOnly*/ false, 1415 /*out*/client); 1416 1417 if(!ret.isOk()) { 1418 logRejected(id, getCallingPid(), String8(clientPackageName), 1419 ret.toString8()); 1420 return ret; 1421 } 1422 1423 *device = client; 1424 return ret; 1425} 1426 1427Status CameraService::connectDevice( 1428 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb, 1429 const String16& cameraId, 1430 const String16& clientPackageName, 1431 int clientUid, 1432 /*out*/ 1433 sp<hardware::camera2::ICameraDeviceUser>* device) { 1434 1435 ATRACE_CALL(); 1436 Status ret = Status::ok(); 1437 String8 id = String8(cameraId); 1438 sp<CameraDeviceClient> client = nullptr; 1439 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id, 1440 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, 1441 clientUid, USE_CALLING_PID, API_2, 1442 /*legacyMode*/ false, /*shimUpdateOnly*/ false, 1443 /*out*/client); 1444 1445 if(!ret.isOk()) { 1446 logRejected(id, getCallingPid(), String8(clientPackageName), 1447 ret.toString8()); 1448 return ret; 1449 } 1450 1451 *device = client; 1452 return ret; 1453} 1454 1455template<class CALLBACK, class CLIENT> 1456Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId, 1457 int halVersion, const String16& clientPackageName, int clientUid, int clientPid, 1458 apiLevel effectiveApiLevel, bool legacyMode, bool shimUpdateOnly, 1459 /*out*/sp<CLIENT>& device) { 1460 binder::Status ret = binder::Status::ok(); 1461 1462 String8 clientName8(clientPackageName); 1463 1464 int originalClientPid = 0; 1465 1466 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and " 1467 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(), 1468 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(), 1469 static_cast<int>(effectiveApiLevel)); 1470 1471 sp<CLIENT> client = nullptr; 1472 { 1473 // Acquire mServiceLock and prevent other clients from connecting 1474 std::unique_ptr<AutoConditionLock> lock = 1475 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS); 1476 1477 if (lock == nullptr) { 1478 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)." 1479 , clientPid); 1480 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE, 1481 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting", 1482 cameraId.string(), clientName8.string(), clientPid); 1483 } 1484 1485 // Enforce client permissions and do basic sanity checks 1486 if(!(ret = validateConnectLocked(cameraId, clientName8, 1487 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) { 1488 return ret; 1489 } 1490 1491 // Check the shim parameters after acquiring lock, if they have already been updated and 1492 // we were doing a shim update, return immediately 1493 if (shimUpdateOnly) { 1494 auto cameraState = getCameraState(cameraId); 1495 if (cameraState != nullptr) { 1496 if (!cameraState->getShimParams().isEmpty()) return ret; 1497 } 1498 } 1499 1500 status_t err; 1501 1502 sp<BasicClient> clientTmp = nullptr; 1503 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial; 1504 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel, 1505 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp, 1506 /*out*/&partial)) != NO_ERROR) { 1507 switch (err) { 1508 case -ENODEV: 1509 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, 1510 "No camera device with ID \"%s\" currently available", 1511 cameraId.string()); 1512 case -EBUSY: 1513 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE, 1514 "Higher-priority client using camera, ID \"%s\" currently unavailable", 1515 cameraId.string()); 1516 default: 1517 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, 1518 "Unexpected error %s (%d) opening camera \"%s\"", 1519 strerror(-err), err, cameraId.string()); 1520 } 1521 } 1522 1523 if (clientTmp.get() != nullptr) { 1524 // Handle special case for API1 MediaRecorder where the existing client is returned 1525 device = static_cast<CLIENT*>(clientTmp.get()); 1526 return ret; 1527 } 1528 1529 // give flashlight a chance to close devices if necessary. 1530 mFlashlight->prepareDeviceOpen(cameraId); 1531 1532 int facing = -1; 1533 int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing); 1534 if (facing == -1) { 1535 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.string()); 1536 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, 1537 "Unable to get camera device \"%s\" facing", cameraId.string()); 1538 } 1539 1540 sp<BasicClient> tmp = nullptr; 1541 if(!(ret = makeClient(this, cameraCb, clientPackageName, cameraId, facing, clientPid, 1542 clientUid, getpid(), legacyMode, halVersion, deviceVersion, effectiveApiLevel, 1543 /*out*/&tmp)).isOk()) { 1544 return ret; 1545 } 1546 client = static_cast<CLIENT*>(tmp.get()); 1547 1548 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state", 1549 __FUNCTION__); 1550 1551 if (mModule != nullptr) { 1552 err = client->initialize(mModule); 1553 } else { 1554 err = client->initialize(mCameraProviderManager); 1555 } 1556 1557 if (err != OK) { 1558 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__); 1559 // Errors could be from the HAL module open call or from AppOpsManager 1560 switch(err) { 1561 case BAD_VALUE: 1562 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, 1563 "Illegal argument to HAL module for camera \"%s\"", cameraId.string()); 1564 case -EBUSY: 1565 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE, 1566 "Camera \"%s\" is already open", cameraId.string()); 1567 case -EUSERS: 1568 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE, 1569 "Too many cameras already open, cannot open camera \"%s\"", 1570 cameraId.string()); 1571 case PERMISSION_DENIED: 1572 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED, 1573 "No permission to open camera \"%s\"", cameraId.string()); 1574 case -EACCES: 1575 return STATUS_ERROR_FMT(ERROR_DISABLED, 1576 "Camera \"%s\" disabled by policy", cameraId.string()); 1577 case -ENODEV: 1578 default: 1579 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, 1580 "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(), 1581 strerror(-err), err); 1582 } 1583 } 1584 1585 // Update shim paremeters for legacy clients 1586 if (effectiveApiLevel == API_1) { 1587 // Assume we have always received a Client subclass for API1 1588 sp<Client> shimClient = reinterpret_cast<Client*>(client.get()); 1589 String8 rawParams = shimClient->getParameters(); 1590 CameraParameters params(rawParams); 1591 1592 auto cameraState = getCameraState(cameraId); 1593 if (cameraState != nullptr) { 1594 cameraState->setShimParams(params); 1595 } else { 1596 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.", 1597 __FUNCTION__, cameraId.string()); 1598 } 1599 } 1600 1601 if (shimUpdateOnly) { 1602 // If only updating legacy shim parameters, immediately disconnect client 1603 mServiceLock.unlock(); 1604 client->disconnect(); 1605 mServiceLock.lock(); 1606 } else { 1607 // Otherwise, add client to active clients list 1608 finishConnectLocked(client, partial); 1609 } 1610 } // lock is destroyed, allow further connect calls 1611 1612 // Important: release the mutex here so the client can call back into the service from its 1613 // destructor (can be at the end of the call) 1614 device = client; 1615 return ret; 1616} 1617 1618Status CameraService::setTorchMode(const String16& cameraId, bool enabled, 1619 const sp<IBinder>& clientBinder) { 1620 Mutex::Autolock lock(mServiceLock); 1621 1622 ATRACE_CALL(); 1623 if (enabled && clientBinder == nullptr) { 1624 ALOGE("%s: torch client binder is NULL", __FUNCTION__); 1625 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, 1626 "Torch client Binder is null"); 1627 } 1628 1629 String8 id = String8(cameraId.string()); 1630 int uid = getCallingUid(); 1631 1632 // verify id is valid. 1633 auto state = getCameraState(id); 1634 if (state == nullptr) { 1635 ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string()); 1636 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, 1637 "Camera ID \"%s\" is a not valid camera ID", id.string()); 1638 } 1639 1640 StatusInternal cameraStatus = state->getStatus(); 1641 if (cameraStatus != StatusInternal::PRESENT && 1642 cameraStatus != StatusInternal::NOT_AVAILABLE) { 1643 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, id.string(), (int)cameraStatus); 1644 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, 1645 "Camera ID \"%s\" is a not valid camera ID", id.string()); 1646 } 1647 1648 { 1649 Mutex::Autolock al(mTorchStatusMutex); 1650 TorchModeStatus status; 1651 status_t err = getTorchStatusLocked(id, &status); 1652 if (err != OK) { 1653 if (err == NAME_NOT_FOUND) { 1654 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, 1655 "Camera \"%s\" does not have a flash unit", id.string()); 1656 } 1657 ALOGE("%s: getting current torch status failed for camera %s", 1658 __FUNCTION__, id.string()); 1659 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, 1660 "Error updating torch status for camera \"%s\": %s (%d)", id.string(), 1661 strerror(-err), err); 1662 } 1663 1664 if (status == TorchModeStatus::NOT_AVAILABLE) { 1665 if (cameraStatus == StatusInternal::NOT_AVAILABLE) { 1666 ALOGE("%s: torch mode of camera %s is not available because " 1667 "camera is in use", __FUNCTION__, id.string()); 1668 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE, 1669 "Torch for camera \"%s\" is not available due to an existing camera user", 1670 id.string()); 1671 } else { 1672 ALOGE("%s: torch mode of camera %s is not available due to " 1673 "insufficient resources", __FUNCTION__, id.string()); 1674 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE, 1675 "Torch for camera \"%s\" is not available due to insufficient resources", 1676 id.string()); 1677 } 1678 } 1679 } 1680 1681 { 1682 // Update UID map - this is used in the torch status changed callbacks, so must be done 1683 // before setTorchMode 1684 Mutex::Autolock al(mTorchUidMapMutex); 1685 if (mTorchUidMap.find(id) == mTorchUidMap.end()) { 1686 mTorchUidMap[id].first = uid; 1687 mTorchUidMap[id].second = uid; 1688 } else { 1689 // Set the pending UID 1690 mTorchUidMap[id].first = uid; 1691 } 1692 } 1693 1694 status_t err = mFlashlight->setTorchMode(id, enabled); 1695 1696 if (err != OK) { 1697 int32_t errorCode; 1698 String8 msg; 1699 switch (err) { 1700 case -ENOSYS: 1701 msg = String8::format("Camera \"%s\" has no flashlight", 1702 id.string()); 1703 errorCode = ERROR_ILLEGAL_ARGUMENT; 1704 break; 1705 default: 1706 msg = String8::format( 1707 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)", 1708 id.string(), enabled, strerror(-err), err); 1709 errorCode = ERROR_INVALID_OPERATION; 1710 } 1711 ALOGE("%s: %s", __FUNCTION__, msg.string()); 1712 return STATUS_ERROR(errorCode, msg.string()); 1713 } 1714 1715 { 1716 // update the link to client's death 1717 Mutex::Autolock al(mTorchClientMapMutex); 1718 ssize_t index = mTorchClientMap.indexOfKey(id); 1719 if (enabled) { 1720 if (index == NAME_NOT_FOUND) { 1721 mTorchClientMap.add(id, clientBinder); 1722 } else { 1723 mTorchClientMap.valueAt(index)->unlinkToDeath(this); 1724 mTorchClientMap.replaceValueAt(index, clientBinder); 1725 } 1726 clientBinder->linkToDeath(this); 1727 } else if (index != NAME_NOT_FOUND) { 1728 mTorchClientMap.valueAt(index)->unlinkToDeath(this); 1729 } 1730 } 1731 1732 return Status::ok(); 1733} 1734 1735Status CameraService::notifySystemEvent(int32_t eventId, 1736 const std::vector<int32_t>& args) { 1737 ATRACE_CALL(); 1738 1739 switch(eventId) { 1740 case ICameraService::EVENT_USER_SWITCHED: { 1741 doUserSwitch(/*newUserIds*/ args); 1742 break; 1743 } 1744 case ICameraService::EVENT_NONE: 1745 default: { 1746 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__, 1747 eventId); 1748 break; 1749 } 1750 } 1751 return Status::ok(); 1752} 1753 1754Status CameraService::addListener(const sp<ICameraServiceListener>& listener, 1755 /*out*/ 1756 std::vector<hardware::CameraStatus> *cameraStatuses) { 1757 ATRACE_CALL(); 1758 1759 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get()); 1760 1761 if (listener == nullptr) { 1762 ALOGE("%s: Listener must not be null", __FUNCTION__); 1763 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener"); 1764 } 1765 1766 Mutex::Autolock lock(mServiceLock); 1767 1768 { 1769 Mutex::Autolock lock(mStatusListenerLock); 1770 for (auto& it : mListenerList) { 1771 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) { 1772 ALOGW("%s: Tried to add listener %p which was already subscribed", 1773 __FUNCTION__, listener.get()); 1774 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered"); 1775 } 1776 } 1777 1778 mListenerList.push_back(listener); 1779 } 1780 1781 /* Collect current devices and status */ 1782 { 1783 Mutex::Autolock lock(mCameraStatesLock); 1784 for (auto& i : mCameraStates) { 1785 cameraStatuses->emplace_back(i.first, mapToInterface(i.second->getStatus())); 1786 } 1787 } 1788 1789 /* 1790 * Immediately signal current torch status to this listener only 1791 * This may be a subset of all the devices, so don't include it in the response directly 1792 */ 1793 { 1794 Mutex::Autolock al(mTorchStatusMutex); 1795 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) { 1796 String16 id = String16(mTorchStatusMap.keyAt(i).string()); 1797 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id); 1798 } 1799 } 1800 1801 return Status::ok(); 1802} 1803 1804Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) { 1805 ATRACE_CALL(); 1806 1807 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get()); 1808 1809 if (listener == 0) { 1810 ALOGE("%s: Listener must not be null", __FUNCTION__); 1811 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener"); 1812 } 1813 1814 Mutex::Autolock lock(mServiceLock); 1815 1816 { 1817 Mutex::Autolock lock(mStatusListenerLock); 1818 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) { 1819 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) { 1820 mListenerList.erase(it); 1821 return Status::ok(); 1822 } 1823 } 1824 } 1825 1826 ALOGW("%s: Tried to remove a listener %p which was not subscribed", 1827 __FUNCTION__, listener.get()); 1828 1829 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener"); 1830} 1831 1832Status CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) { 1833 1834 ATRACE_CALL(); 1835 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId); 1836 1837 if (parameters == NULL) { 1838 ALOGE("%s: parameters must not be null", __FUNCTION__); 1839 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null"); 1840 } 1841 1842 Status ret = Status::ok(); 1843 1844 CameraParameters shimParams; 1845 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) { 1846 // Error logged by caller 1847 return ret; 1848 } 1849 1850 String8 shimParamsString8 = shimParams.flatten(); 1851 String16 shimParamsString16 = String16(shimParamsString8); 1852 1853 *parameters = shimParamsString16; 1854 1855 return ret; 1856} 1857 1858Status CameraService::supportsCameraApi(const String16& cameraId, int apiVersion, 1859 /*out*/ bool *isSupported) { 1860 ATRACE_CALL(); 1861 1862 const String8 id = String8(cameraId); 1863 1864 ALOGV("%s: for camera ID = %s", __FUNCTION__, id.string()); 1865 1866 switch (apiVersion) { 1867 case API_VERSION_1: 1868 case API_VERSION_2: 1869 break; 1870 default: 1871 String8 msg = String8::format("Unknown API version %d", apiVersion); 1872 ALOGE("%s: %s", __FUNCTION__, msg.string()); 1873 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string()); 1874 } 1875 1876 int deviceVersion = getDeviceVersion(id); 1877 switch(deviceVersion) { 1878 case CAMERA_DEVICE_API_VERSION_1_0: 1879 case CAMERA_DEVICE_API_VERSION_3_0: 1880 case CAMERA_DEVICE_API_VERSION_3_1: 1881 if (apiVersion == API_VERSION_2) { 1882 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without shim", 1883 __FUNCTION__, id.string(), deviceVersion); 1884 *isSupported = false; 1885 } else { // if (apiVersion == API_VERSION_1) { 1886 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always supported", 1887 __FUNCTION__, id.string()); 1888 *isSupported = true; 1889 } 1890 break; 1891 case CAMERA_DEVICE_API_VERSION_3_2: 1892 case CAMERA_DEVICE_API_VERSION_3_3: 1893 case CAMERA_DEVICE_API_VERSION_3_4: 1894 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly", 1895 __FUNCTION__, id.string()); 1896 *isSupported = true; 1897 break; 1898 case -1: { 1899 String8 msg = String8::format("Unknown camera ID %s", id.string()); 1900 ALOGE("%s: %s", __FUNCTION__, msg.string()); 1901 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.string()); 1902 } 1903 default: { 1904 String8 msg = String8::format("Unknown device version %x for device %s", 1905 deviceVersion, id.string()); 1906 ALOGE("%s: %s", __FUNCTION__, msg.string()); 1907 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.string()); 1908 } 1909 } 1910 1911 return Status::ok(); 1912} 1913 1914void CameraService::removeByClient(const BasicClient* client) { 1915 Mutex::Autolock lock(mServiceLock); 1916 for (auto& i : mActiveClientManager.getAll()) { 1917 auto clientSp = i->getValue(); 1918 if (clientSp.get() == client) { 1919 mActiveClientManager.remove(i); 1920 } 1921 } 1922} 1923 1924bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) { 1925 const int callingPid = getCallingPid(); 1926 const int servicePid = getpid(); 1927 bool ret = false; 1928 { 1929 // Acquire mServiceLock and prevent other clients from connecting 1930 std::unique_ptr<AutoConditionLock> lock = 1931 AutoConditionLock::waitAndAcquire(mServiceLockWrapper); 1932 1933 1934 std::vector<sp<BasicClient>> evicted; 1935 for (auto& i : mActiveClientManager.getAll()) { 1936 auto clientSp = i->getValue(); 1937 if (clientSp.get() == nullptr) { 1938 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__); 1939 mActiveClientManager.remove(i); 1940 continue; 1941 } 1942 if (remote == clientSp->getRemote() && (callingPid == servicePid || 1943 callingPid == clientSp->getClientPid())) { 1944 mActiveClientManager.remove(i); 1945 evicted.push_back(clientSp); 1946 1947 // Notify the client of disconnection 1948 clientSp->notifyError( 1949 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED, 1950 CaptureResultExtras()); 1951 } 1952 } 1953 1954 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking 1955 // other clients from connecting in mServiceLockWrapper if held 1956 mServiceLock.unlock(); 1957 1958 // Do not clear caller identity, remote caller should be client proccess 1959 1960 for (auto& i : evicted) { 1961 if (i.get() != nullptr) { 1962 i->disconnect(); 1963 ret = true; 1964 } 1965 } 1966 1967 // Reacquire mServiceLock 1968 mServiceLock.lock(); 1969 1970 } // lock is destroyed, allow further connect calls 1971 1972 return ret; 1973} 1974 1975 1976/** 1977 * Check camera capabilities, such as support for basic color operation 1978 * Also check that the device HAL version is still in support 1979 */ 1980int CameraService::checkCameraCapabilities(int id, camera_info info, int *latestStrangeCameraId) { 1981 if (mModule == nullptr) return NO_INIT; 1982 1983 // device_version undefined in CAMERA_MODULE_API_VERSION_1_0, 1984 // All CAMERA_MODULE_API_VERSION_1_0 devices are backward-compatible 1985 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) { 1986 // Verify the device version is in the supported range 1987 switch (info.device_version) { 1988 case CAMERA_DEVICE_API_VERSION_1_0: 1989 case CAMERA_DEVICE_API_VERSION_3_0: 1990 case CAMERA_DEVICE_API_VERSION_3_1: 1991 case CAMERA_DEVICE_API_VERSION_3_2: 1992 case CAMERA_DEVICE_API_VERSION_3_3: 1993 case CAMERA_DEVICE_API_VERSION_3_4: 1994 // in support 1995 break; 1996 case CAMERA_DEVICE_API_VERSION_2_0: 1997 case CAMERA_DEVICE_API_VERSION_2_1: 1998 // no longer supported 1999 default: 2000 ALOGE("%s: Device %d has HAL version %x, which is not supported", 2001 __FUNCTION__, id, info.device_version); 2002 String8 msg = String8::format( 2003 "Unsupported device HAL version %x for device %d", 2004 info.device_version, id); 2005 logServiceError(msg.string(), NO_INIT); 2006 return NO_INIT; 2007 } 2008 } 2009 2010 // Assume all devices pre-v3.3 are backward-compatible 2011 bool isBackwardCompatible = true; 2012 if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0 2013 && info.device_version >= CAMERA_DEVICE_API_VERSION_3_3) { 2014 isBackwardCompatible = false; 2015 status_t res; 2016 camera_metadata_ro_entry_t caps; 2017 res = find_camera_metadata_ro_entry( 2018 info.static_camera_characteristics, 2019 ANDROID_REQUEST_AVAILABLE_CAPABILITIES, 2020 &caps); 2021 if (res != 0) { 2022 ALOGW("%s: Unable to find camera capabilities for camera device %d", 2023 __FUNCTION__, id); 2024 caps.count = 0; 2025 } 2026 for (size_t i = 0; i < caps.count; i++) { 2027 if (caps.data.u8[i] == 2028 ANDROID_REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE) { 2029 isBackwardCompatible = true; 2030 break; 2031 } 2032 } 2033 } 2034 2035 if (!isBackwardCompatible) { 2036 mNumberOfNormalCameras--; 2037 *latestStrangeCameraId = id; 2038 } else { 2039 if (id > *latestStrangeCameraId) { 2040 ALOGE("%s: Normal camera ID %d higher than strange camera ID %d. " 2041 "This is not allowed due backward-compatibility requirements", 2042 __FUNCTION__, id, *latestStrangeCameraId); 2043 logServiceError("Invalid order of camera devices", NO_INIT); 2044 mNumberOfCameras = 0; 2045 mNumberOfNormalCameras = 0; 2046 return NO_INIT; 2047 } 2048 } 2049 return OK; 2050} 2051 2052std::shared_ptr<CameraService::CameraState> CameraService::getCameraState( 2053 const String8& cameraId) const { 2054 std::shared_ptr<CameraState> state; 2055 { 2056 Mutex::Autolock lock(mCameraStatesLock); 2057 auto iter = mCameraStates.find(cameraId); 2058 if (iter != mCameraStates.end()) { 2059 state = iter->second; 2060 } 2061 } 2062 return state; 2063} 2064 2065sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) { 2066 // Remove from active clients list 2067 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId); 2068 if (clientDescriptorPtr == nullptr) { 2069 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__, 2070 cameraId.string()); 2071 return sp<BasicClient>{nullptr}; 2072 } 2073 2074 return clientDescriptorPtr->getValue(); 2075} 2076 2077void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) { 2078 // Acquire mServiceLock and prevent other clients from connecting 2079 std::unique_ptr<AutoConditionLock> lock = 2080 AutoConditionLock::waitAndAcquire(mServiceLockWrapper); 2081 2082 std::set<userid_t> newAllowedUsers; 2083 for (size_t i = 0; i < newUserIds.size(); i++) { 2084 if (newUserIds[i] < 0) { 2085 ALOGE("%s: Bad user ID %d given during user switch, ignoring.", 2086 __FUNCTION__, newUserIds[i]); 2087 return; 2088 } 2089 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i])); 2090 } 2091 2092 2093 if (newAllowedUsers == mAllowedUsers) { 2094 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__); 2095 return; 2096 } 2097 2098 logUserSwitch(mAllowedUsers, newAllowedUsers); 2099 2100 mAllowedUsers = std::move(newAllowedUsers); 2101 2102 // Current user has switched, evict all current clients. 2103 std::vector<sp<BasicClient>> evicted; 2104 for (auto& i : mActiveClientManager.getAll()) { 2105 auto clientSp = i->getValue(); 2106 2107 if (clientSp.get() == nullptr) { 2108 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__); 2109 continue; 2110 } 2111 2112 // Don't evict clients that are still allowed. 2113 uid_t clientUid = clientSp->getClientUid(); 2114 userid_t clientUserId = multiuser_get_user_id(clientUid); 2115 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) { 2116 continue; 2117 } 2118 2119 evicted.push_back(clientSp); 2120 2121 String8 curTime = getFormattedCurrentTime(); 2122 2123 ALOGE("Evicting conflicting client for camera ID %s due to user change", 2124 i->getKey().string()); 2125 2126 // Log the clients evicted 2127 logEvent(String8::format("EVICT device %s client held by package %s (PID %" 2128 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due" 2129 " to user switch.", i->getKey().string(), 2130 String8{clientSp->getPackageName()}.string(), 2131 i->getOwnerId(), i->getPriority().getScore(), 2132 i->getPriority().getState())); 2133 2134 } 2135 2136 // Do not hold mServiceLock while disconnecting clients, but retain the condition 2137 // blocking other clients from connecting in mServiceLockWrapper if held. 2138 mServiceLock.unlock(); 2139 2140 // Clear caller identity temporarily so client disconnect PID checks work correctly 2141 int64_t token = IPCThreadState::self()->clearCallingIdentity(); 2142 2143 for (auto& i : evicted) { 2144 i->disconnect(); 2145 } 2146 2147 IPCThreadState::self()->restoreCallingIdentity(token); 2148 2149 // Reacquire mServiceLock 2150 mServiceLock.lock(); 2151} 2152 2153void CameraService::logEvent(const char* event) { 2154 String8 curTime = getFormattedCurrentTime(); 2155 Mutex::Autolock l(mLogLock); 2156 mEventLog.add(String8::format("%s : %s", curTime.string(), event)); 2157} 2158 2159void CameraService::logDisconnected(const char* cameraId, int clientPid, 2160 const char* clientPackage) { 2161 // Log the clients evicted 2162 logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId, 2163 clientPackage, clientPid)); 2164} 2165 2166void CameraService::logConnected(const char* cameraId, int clientPid, 2167 const char* clientPackage) { 2168 // Log the clients evicted 2169 logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId, 2170 clientPackage, clientPid)); 2171} 2172 2173void CameraService::logRejected(const char* cameraId, int clientPid, 2174 const char* clientPackage, const char* reason) { 2175 // Log the client rejected 2176 logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)", 2177 cameraId, clientPackage, clientPid, reason)); 2178} 2179 2180void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds, 2181 const std::set<userid_t>& newUserIds) { 2182 String8 newUsers = toString(newUserIds); 2183 String8 oldUsers = toString(oldUserIds); 2184 if (oldUsers.size() == 0) { 2185 oldUsers = "<None>"; 2186 } 2187 // Log the new and old users 2188 logEvent(String8::format("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s", 2189 oldUsers.string(), newUsers.string())); 2190} 2191 2192void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) { 2193 // Log the device removal 2194 logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason)); 2195} 2196 2197void CameraService::logDeviceAdded(const char* cameraId, const char* reason) { 2198 // Log the device removal 2199 logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason)); 2200} 2201 2202void CameraService::logClientDied(int clientPid, const char* reason) { 2203 // Log the device removal 2204 logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason)); 2205} 2206 2207void CameraService::logServiceError(const char* msg, int errorCode) { 2208 String8 curTime = getFormattedCurrentTime(); 2209 logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode))); 2210} 2211 2212status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply, 2213 uint32_t flags) { 2214 2215 const int pid = getCallingPid(); 2216 const int selfPid = getpid(); 2217 2218 // Permission checks 2219 switch (code) { 2220 case BnCameraService::NOTIFYSYSTEMEVENT: { 2221 if (pid != selfPid) { 2222 // Ensure we're being called by system_server, or similar process with 2223 // permissions to notify the camera service about system events 2224 if (!checkCallingPermission( 2225 String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) { 2226 const int uid = getCallingUid(); 2227 ALOGE("Permission Denial: cannot send updates to camera service about system" 2228 " events from pid=%d, uid=%d", pid, uid); 2229 return PERMISSION_DENIED; 2230 } 2231 } 2232 break; 2233 } 2234 } 2235 2236 return BnCameraService::onTransact(code, data, reply, flags); 2237} 2238 2239// We share the media players for shutter and recording sound for all clients. 2240// A reference count is kept to determine when we will actually release the 2241// media players. 2242 2243MediaPlayer* CameraService::newMediaPlayer(const char *file) { 2244 MediaPlayer* mp = new MediaPlayer(); 2245 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) { 2246 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE); 2247 mp->prepare(); 2248 } else { 2249 ALOGE("Failed to load CameraService sounds: %s", file); 2250 return NULL; 2251 } 2252 return mp; 2253} 2254 2255void CameraService::loadSound() { 2256 ATRACE_CALL(); 2257 2258 Mutex::Autolock lock(mSoundLock); 2259 LOG1("CameraService::loadSound ref=%d", mSoundRef); 2260 if (mSoundRef++) return; 2261 2262 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg"); 2263 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg"); 2264 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg"); 2265} 2266 2267void CameraService::releaseSound() { 2268 Mutex::Autolock lock(mSoundLock); 2269 LOG1("CameraService::releaseSound ref=%d", mSoundRef); 2270 if (--mSoundRef) return; 2271 2272 for (int i = 0; i < NUM_SOUNDS; i++) { 2273 if (mSoundPlayer[i] != 0) { 2274 mSoundPlayer[i]->disconnect(); 2275 mSoundPlayer[i].clear(); 2276 } 2277 } 2278} 2279 2280void CameraService::playSound(sound_kind kind) { 2281 ATRACE_CALL(); 2282 2283 LOG1("playSound(%d)", kind); 2284 Mutex::Autolock lock(mSoundLock); 2285 sp<MediaPlayer> player = mSoundPlayer[kind]; 2286 if (player != 0) { 2287 player->seekTo(0); 2288 player->start(); 2289 } 2290} 2291 2292// ---------------------------------------------------------------------------- 2293 2294CameraService::Client::Client(const sp<CameraService>& cameraService, 2295 const sp<ICameraClient>& cameraClient, 2296 const String16& clientPackageName, 2297 const String8& cameraIdStr, int cameraFacing, 2298 int clientPid, uid_t clientUid, 2299 int servicePid) : 2300 CameraService::BasicClient(cameraService, 2301 IInterface::asBinder(cameraClient), 2302 clientPackageName, 2303 cameraIdStr, cameraFacing, 2304 clientPid, clientUid, 2305 servicePid), 2306 mCameraId(CameraService::cameraIdToInt(cameraIdStr)) 2307{ 2308 int callingPid = getCallingPid(); 2309 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId); 2310 2311 mRemoteCallback = cameraClient; 2312 2313 cameraService->loadSound(); 2314 2315 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId); 2316} 2317 2318// tear down the client 2319CameraService::Client::~Client() { 2320 ALOGV("~Client"); 2321 mDestructionStarted = true; 2322 2323 sCameraService->releaseSound(); 2324 // unconditionally disconnect. function is idempotent 2325 Client::disconnect(); 2326} 2327 2328sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService; 2329 2330CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService, 2331 const sp<IBinder>& remoteCallback, 2332 const String16& clientPackageName, 2333 const String8& cameraIdStr, int cameraFacing, 2334 int clientPid, uid_t clientUid, 2335 int servicePid): 2336 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), 2337 mClientPackageName(clientPackageName), mClientPid(clientPid), mClientUid(clientUid), 2338 mServicePid(servicePid), 2339 mDisconnected(false), 2340 mRemoteBinder(remoteCallback) 2341{ 2342 if (sCameraService == nullptr) { 2343 sCameraService = cameraService; 2344 } 2345 mOpsActive = false; 2346 mDestructionStarted = false; 2347 2348 // In some cases the calling code has no access to the package it runs under. 2349 // For example, NDK camera API. 2350 // In this case we will get the packages for the calling UID and pick the first one 2351 // for attributing the app op. This will work correctly for runtime permissions 2352 // as for legacy apps we will toggle the app op for all packages in the UID. 2353 // The caveat is that the operation may be attributed to the wrong package and 2354 // stats based on app ops may be slightly off. 2355 if (mClientPackageName.size() <= 0) { 2356 sp<IServiceManager> sm = defaultServiceManager(); 2357 sp<IBinder> binder = sm->getService(String16(kPermissionServiceName)); 2358 if (binder == 0) { 2359 ALOGE("Cannot get permission service"); 2360 // Leave mClientPackageName unchanged (empty) and the further interaction 2361 // with camera will fail in BasicClient::startCameraOps 2362 return; 2363 } 2364 2365 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder); 2366 Vector<String16> packages; 2367 2368 permCtrl->getPackagesForUid(mClientUid, packages); 2369 2370 if (packages.isEmpty()) { 2371 ALOGE("No packages for calling UID"); 2372 // Leave mClientPackageName unchanged (empty) and the further interaction 2373 // with camera will fail in BasicClient::startCameraOps 2374 return; 2375 } 2376 mClientPackageName = packages[0]; 2377 } 2378} 2379 2380CameraService::BasicClient::~BasicClient() { 2381 ALOGV("~BasicClient"); 2382 mDestructionStarted = true; 2383} 2384 2385binder::Status CameraService::BasicClient::disconnect() { 2386 binder::Status res = Status::ok(); 2387 if (mDisconnected) { 2388 return res; 2389 } 2390 mDisconnected = true; 2391 2392 sCameraService->removeByClient(this); 2393 sCameraService->logDisconnected(mCameraIdStr, mClientPid, 2394 String8(mClientPackageName)); 2395 2396 sp<IBinder> remote = getRemote(); 2397 if (remote != nullptr) { 2398 remote->unlinkToDeath(sCameraService); 2399 } 2400 2401 finishCameraOps(); 2402 // Notify flashlight that a camera device is closed. 2403 sCameraService->mFlashlight->deviceClosed(mCameraIdStr); 2404 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.string(), 2405 mClientPid); 2406 2407 // client shouldn't be able to call into us anymore 2408 mClientPid = 0; 2409 2410 return res; 2411} 2412 2413status_t CameraService::BasicClient::dump(int, const Vector<String16>&) { 2414 // No dumping of clients directly over Binder, 2415 // must go through CameraService::dump 2416 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403", 2417 IPCThreadState::self()->getCallingUid(), NULL, 0); 2418 return OK; 2419} 2420 2421String16 CameraService::BasicClient::getPackageName() const { 2422 return mClientPackageName; 2423} 2424 2425 2426int CameraService::BasicClient::getClientPid() const { 2427 return mClientPid; 2428} 2429 2430uid_t CameraService::BasicClient::getClientUid() const { 2431 return mClientUid; 2432} 2433 2434bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const { 2435 // Defaults to API2. 2436 return level == API_2; 2437} 2438 2439status_t CameraService::BasicClient::startCameraOps() { 2440 ATRACE_CALL(); 2441 2442 int32_t res; 2443 // Notify app ops that the camera is not available 2444 mOpsCallback = new OpsCallback(this); 2445 2446 { 2447 ALOGV("%s: Start camera ops, package name = %s, client UID = %d", 2448 __FUNCTION__, String8(mClientPackageName).string(), mClientUid); 2449 } 2450 2451 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA, 2452 mClientPackageName, mOpsCallback); 2453 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA, 2454 mClientUid, mClientPackageName); 2455 2456 if (res == AppOpsManager::MODE_ERRORED) { 2457 ALOGI("Camera %s: Access for \"%s\" has been revoked", 2458 mCameraIdStr.string(), String8(mClientPackageName).string()); 2459 return PERMISSION_DENIED; 2460 } 2461 2462 if (res == AppOpsManager::MODE_IGNORED) { 2463 ALOGI("Camera %s: Access for \"%s\" has been restricted", 2464 mCameraIdStr.string(), String8(mClientPackageName).string()); 2465 // Return the same error as for device policy manager rejection 2466 return -EACCES; 2467 } 2468 2469 mOpsActive = true; 2470 2471 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE 2472 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr); 2473 2474 // Transition device state to OPEN 2475 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN, 2476 mCameraIdStr); 2477 2478 return OK; 2479} 2480 2481status_t CameraService::BasicClient::finishCameraOps() { 2482 ATRACE_CALL(); 2483 2484 // Check if startCameraOps succeeded, and if so, finish the camera op 2485 if (mOpsActive) { 2486 // Notify app ops that the camera is available again 2487 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid, 2488 mClientPackageName); 2489 mOpsActive = false; 2490 2491 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT, 2492 StatusInternal::ENUMERATING}; 2493 2494 // Transition to PRESENT if the camera is not in either of the rejected states 2495 sCameraService->updateStatus(StatusInternal::PRESENT, 2496 mCameraIdStr, rejected); 2497 2498 // Transition device state to CLOSED 2499 sCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED, 2500 mCameraIdStr); 2501 } 2502 // Always stop watching, even if no camera op is active 2503 if (mOpsCallback != NULL) { 2504 mAppOpsManager.stopWatchingMode(mOpsCallback); 2505 } 2506 mOpsCallback.clear(); 2507 2508 return OK; 2509} 2510 2511void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) { 2512 ATRACE_CALL(); 2513 2514 String8 name(packageName); 2515 String8 myName(mClientPackageName); 2516 2517 if (op != AppOpsManager::OP_CAMERA) { 2518 ALOGW("Unexpected app ops notification received: %d", op); 2519 return; 2520 } 2521 2522 int32_t res; 2523 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA, 2524 mClientUid, mClientPackageName); 2525 ALOGV("checkOp returns: %d, %s ", res, 2526 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" : 2527 res == AppOpsManager::MODE_IGNORED ? "IGNORED" : 2528 res == AppOpsManager::MODE_ERRORED ? "ERRORED" : 2529 "UNKNOWN"); 2530 2531 if (res != AppOpsManager::MODE_ALLOWED) { 2532 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.string(), 2533 myName.string()); 2534 // Reset the client PID to allow server-initiated disconnect, 2535 // and to prevent further calls by client. 2536 mClientPid = getCallingPid(); 2537 CaptureResultExtras resultExtras; // a dummy result (invalid) 2538 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras); 2539 disconnect(); 2540 } 2541} 2542 2543// ---------------------------------------------------------------------------- 2544 2545void CameraService::Client::notifyError(int32_t errorCode, 2546 const CaptureResultExtras& resultExtras) { 2547 (void) errorCode; 2548 (void) resultExtras; 2549 if (mRemoteCallback != NULL) { 2550 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0); 2551 } else { 2552 ALOGE("mRemoteCallback is NULL!!"); 2553 } 2554} 2555 2556// NOTE: function is idempotent 2557binder::Status CameraService::Client::disconnect() { 2558 ALOGV("Client::disconnect"); 2559 return BasicClient::disconnect(); 2560} 2561 2562bool CameraService::Client::canCastToApiClient(apiLevel level) const { 2563 return level == API_1; 2564} 2565 2566CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client): 2567 mClient(client) { 2568} 2569 2570void CameraService::Client::OpsCallback::opChanged(int32_t op, 2571 const String16& packageName) { 2572 sp<BasicClient> client = mClient.promote(); 2573 if (client != NULL) { 2574 client->opChanged(op, packageName); 2575 } 2576} 2577 2578// ---------------------------------------------------------------------------- 2579// CameraState 2580// ---------------------------------------------------------------------------- 2581 2582CameraService::CameraState::CameraState(const String8& id, int cost, 2583 const std::set<String8>& conflicting) : mId(id), 2584 mStatus(StatusInternal::PRESENT), mCost(cost), mConflicting(conflicting) {} 2585 2586CameraService::CameraState::~CameraState() {} 2587 2588CameraService::StatusInternal CameraService::CameraState::getStatus() const { 2589 Mutex::Autolock lock(mStatusLock); 2590 return mStatus; 2591} 2592 2593CameraParameters CameraService::CameraState::getShimParams() const { 2594 return mShimParams; 2595} 2596 2597void CameraService::CameraState::setShimParams(const CameraParameters& params) { 2598 mShimParams = params; 2599} 2600 2601int CameraService::CameraState::getCost() const { 2602 return mCost; 2603} 2604 2605std::set<String8> CameraService::CameraState::getConflicting() const { 2606 return mConflicting; 2607} 2608 2609String8 CameraService::CameraState::getId() const { 2610 return mId; 2611} 2612 2613// ---------------------------------------------------------------------------- 2614// ClientEventListener 2615// ---------------------------------------------------------------------------- 2616 2617void CameraService::ClientEventListener::onClientAdded( 2618 const resource_policy::ClientDescriptor<String8, 2619 sp<CameraService::BasicClient>>& descriptor) { 2620 const auto& basicClient = descriptor.getValue(); 2621 if (basicClient.get() != nullptr) { 2622 BatteryNotifier& notifier(BatteryNotifier::getInstance()); 2623 notifier.noteStartCamera(descriptor.getKey(), 2624 static_cast<int>(basicClient->getClientUid())); 2625 } 2626} 2627 2628void CameraService::ClientEventListener::onClientRemoved( 2629 const resource_policy::ClientDescriptor<String8, 2630 sp<CameraService::BasicClient>>& descriptor) { 2631 const auto& basicClient = descriptor.getValue(); 2632 if (basicClient.get() != nullptr) { 2633 BatteryNotifier& notifier(BatteryNotifier::getInstance()); 2634 notifier.noteStopCamera(descriptor.getKey(), 2635 static_cast<int>(basicClient->getClientUid())); 2636 } 2637} 2638 2639 2640// ---------------------------------------------------------------------------- 2641// CameraClientManager 2642// ---------------------------------------------------------------------------- 2643 2644CameraService::CameraClientManager::CameraClientManager() { 2645 setListener(std::make_shared<ClientEventListener>()); 2646} 2647 2648CameraService::CameraClientManager::~CameraClientManager() {} 2649 2650sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient( 2651 const String8& id) const { 2652 auto descriptor = get(id); 2653 if (descriptor == nullptr) { 2654 return sp<BasicClient>{nullptr}; 2655 } 2656 return descriptor->getValue(); 2657} 2658 2659String8 CameraService::CameraClientManager::toString() const { 2660 auto all = getAll(); 2661 String8 ret("["); 2662 bool hasAny = false; 2663 for (auto& i : all) { 2664 hasAny = true; 2665 String8 key = i->getKey(); 2666 int32_t cost = i->getCost(); 2667 int32_t pid = i->getOwnerId(); 2668 int32_t score = i->getPriority().getScore(); 2669 int32_t state = i->getPriority().getState(); 2670 auto conflicting = i->getConflicting(); 2671 auto clientSp = i->getValue(); 2672 String8 packageName; 2673 userid_t clientUserId = 0; 2674 if (clientSp.get() != nullptr) { 2675 packageName = String8{clientSp->getPackageName()}; 2676 uid_t clientUid = clientSp->getClientUid(); 2677 clientUserId = multiuser_get_user_id(clientUid); 2678 } 2679 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %" 2680 PRId32 ", State: %" PRId32, key.string(), cost, pid, score, state); 2681 2682 if (clientSp.get() != nullptr) { 2683 ret.appendFormat("User Id: %d, ", clientUserId); 2684 } 2685 if (packageName.size() != 0) { 2686 ret.appendFormat("Client Package Name: %s", packageName.string()); 2687 } 2688 2689 ret.append(", Conflicting Client Devices: {"); 2690 for (auto& j : conflicting) { 2691 ret.appendFormat("%s, ", j.string()); 2692 } 2693 ret.append("})"); 2694 } 2695 if (hasAny) ret.append("\n"); 2696 ret.append("]\n"); 2697 return ret; 2698} 2699 2700CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor( 2701 const String8& key, const sp<BasicClient>& value, int32_t cost, 2702 const std::set<String8>& conflictingKeys, int32_t score, int32_t ownerId, 2703 int32_t state) { 2704 2705 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>( 2706 key, value, cost, conflictingKeys, score, ownerId, state); 2707} 2708 2709CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor( 2710 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) { 2711 return makeClientDescriptor(partial->getKey(), value, partial->getCost(), 2712 partial->getConflicting(), partial->getPriority().getScore(), 2713 partial->getOwnerId(), partial->getPriority().getState()); 2714} 2715 2716// ---------------------------------------------------------------------------- 2717 2718static const int kDumpLockRetries = 50; 2719static const int kDumpLockSleep = 60000; 2720 2721static bool tryLock(Mutex& mutex) 2722{ 2723 bool locked = false; 2724 for (int i = 0; i < kDumpLockRetries; ++i) { 2725 if (mutex.tryLock() == NO_ERROR) { 2726 locked = true; 2727 break; 2728 } 2729 usleep(kDumpLockSleep); 2730 } 2731 return locked; 2732} 2733 2734status_t CameraService::dump(int fd, const Vector<String16>& args) { 2735 ATRACE_CALL(); 2736 2737 if (checkCallingPermission(String16("android.permission.DUMP")) == false) { 2738 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n", 2739 getCallingPid(), 2740 getCallingUid()); 2741 return NO_ERROR; 2742 } 2743 bool locked = tryLock(mServiceLock); 2744 // failed to lock - CameraService is probably deadlocked 2745 if (!locked) { 2746 dprintf(fd, "!! CameraService may be deadlocked !!\n"); 2747 } 2748 2749 if (!mInitialized) { 2750 dprintf(fd, "!! No camera HAL available !!\n"); 2751 2752 // Dump event log for error information 2753 dumpEventLog(fd); 2754 2755 if (locked) mServiceLock.unlock(); 2756 return NO_ERROR; 2757 } 2758 dprintf(fd, "\n== Service global info: ==\n\n"); 2759 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras); 2760 dprintf(fd, "Number of normal camera devices: %d\n", mNumberOfNormalCameras); 2761 String8 activeClientString = mActiveClientManager.toString(); 2762 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.string()); 2763 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).string()); 2764 2765 dumpEventLog(fd); 2766 2767 bool stateLocked = tryLock(mCameraStatesLock); 2768 if (!stateLocked) { 2769 dprintf(fd, "CameraStates in use, may be deadlocked\n"); 2770 } 2771 2772 for (auto& state : mCameraStates) { 2773 String8 cameraId = state.first; 2774 2775 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.string()); 2776 2777 CameraParameters p = state.second->getShimParams(); 2778 if (!p.isEmpty()) { 2779 dprintf(fd, " Camera1 API shim is using parameters:\n "); 2780 p.dump(fd, args); 2781 } 2782 2783 auto clientDescriptor = mActiveClientManager.get(cameraId); 2784 if (clientDescriptor != nullptr) { 2785 dprintf(fd, " Device %s is open. Client instance dump:\n", 2786 cameraId.string()); 2787 dprintf(fd, " Client priority score: %d state: %d\n", 2788 clientDescriptor->getPriority().getScore(), 2789 clientDescriptor->getPriority().getState()); 2790 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId()); 2791 2792 auto client = clientDescriptor->getValue(); 2793 dprintf(fd, " Client package: %s\n", 2794 String8(client->getPackageName()).string()); 2795 2796 client->dumpClient(fd, args); 2797 } else { 2798 dprintf(fd, " Device %s is closed, no client instance\n", 2799 cameraId.string()); 2800 } 2801 2802 if (mModule != nullptr) { 2803 dprintf(fd, "== Camera HAL device %s static information: ==\n", cameraId.string()); 2804 2805 camera_info info; 2806 status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info); 2807 int deviceVersion = -1; 2808 if (rc != OK) { 2809 dprintf(fd, " Error reading static information!\n"); 2810 } else { 2811 dprintf(fd, " Facing: %s\n", 2812 info.facing == CAMERA_FACING_BACK ? "BACK" : 2813 info.facing == CAMERA_FACING_FRONT ? "FRONT" : "EXTERNAL"); 2814 dprintf(fd, " Orientation: %d\n", info.orientation); 2815 2816 if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0) { 2817 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0; 2818 } else { 2819 deviceVersion = info.device_version; 2820 } 2821 } 2822 2823 auto conflicting = state.second->getConflicting(); 2824 dprintf(fd, " Resource Cost: %d\n", state.second->getCost()); 2825 dprintf(fd, " Conflicting Devices:"); 2826 for (auto& id : conflicting) { 2827 dprintf(fd, " %s", id.string()); 2828 } 2829 if (conflicting.size() == 0) { 2830 dprintf(fd, " NONE"); 2831 } 2832 dprintf(fd, "\n"); 2833 2834 dprintf(fd, " Device version: %#x\n", deviceVersion); 2835 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_3_0) { 2836 dprintf(fd, " Device static metadata:\n"); 2837 dump_indented_camera_metadata(info.static_camera_characteristics, 2838 fd, /*verbosity*/2, /*indentation*/4); 2839 } 2840 } 2841 2842 } 2843 2844 if (stateLocked) mCameraStatesLock.unlock(); 2845 2846 if (locked) mServiceLock.unlock(); 2847 2848 if (mModule == nullptr) { 2849 mCameraProviderManager->dump(fd, args); 2850 } else { 2851 dprintf(fd, "\n== Camera Module HAL static info: ==\n"); 2852 dprintf(fd, "Camera module HAL API version: 0x%x\n", mModule->getHalApiVersion()); 2853 dprintf(fd, "Camera module API version: 0x%x\n", mModule->getModuleApiVersion()); 2854 dprintf(fd, "Camera module name: %s\n", mModule->getModuleName()); 2855 dprintf(fd, "Camera module author: %s\n", mModule->getModuleAuthor()); 2856 } 2857 2858 dprintf(fd, "\n== Vendor tags: ==\n\n"); 2859 2860 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor(); 2861 if (desc == NULL) { 2862 dprintf(fd, "No vendor tags.\n"); 2863 } else { 2864 desc->dump(fd, /*verbosity*/2, /*indentation*/2); 2865 } 2866 2867 // Dump camera traces if there were any 2868 dprintf(fd, "\n"); 2869 camera3::CameraTraces::dump(fd, args); 2870 2871 // Process dump arguments, if any 2872 int n = args.size(); 2873 String16 verboseOption("-v"); 2874 String16 unreachableOption("--unreachable"); 2875 for (int i = 0; i < n; i++) { 2876 if (args[i] == verboseOption) { 2877 // change logging level 2878 if (i + 1 >= n) continue; 2879 String8 levelStr(args[i+1]); 2880 int level = atoi(levelStr.string()); 2881 dprintf(fd, "\nSetting log level to %d.\n", level); 2882 setLogLevel(level); 2883 } else if (args[i] == unreachableOption) { 2884 // Dump memory analysis 2885 // TODO - should limit be an argument parameter? 2886 UnreachableMemoryInfo info; 2887 bool success = GetUnreachableMemory(info, /*limit*/ 10000); 2888 if (!success) { 2889 dprintf(fd, "\n== Unable to dump unreachable memory. " 2890 "Try disabling SELinux enforcement. ==\n"); 2891 } else { 2892 dprintf(fd, "\n== Dumping unreachable memory: ==\n"); 2893 std::string s = info.ToString(/*log_contents*/ true); 2894 write(fd, s.c_str(), s.size()); 2895 } 2896 } 2897 } 2898 return NO_ERROR; 2899} 2900 2901void CameraService::dumpEventLog(int fd) { 2902 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n"); 2903 2904 Mutex::Autolock l(mLogLock); 2905 for (const auto& msg : mEventLog) { 2906 dprintf(fd, " %s\n", msg.string()); 2907 } 2908 2909 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) { 2910 dprintf(fd, " ...\n"); 2911 } else if (mEventLog.size() == 0) { 2912 dprintf(fd, " [no events yet]\n"); 2913 } 2914 dprintf(fd, "\n"); 2915} 2916 2917void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) { 2918 Mutex::Autolock al(mTorchClientMapMutex); 2919 for (size_t i = 0; i < mTorchClientMap.size(); i++) { 2920 if (mTorchClientMap[i] == who) { 2921 // turn off the torch mode that was turned on by dead client 2922 String8 cameraId = mTorchClientMap.keyAt(i); 2923 status_t res = mFlashlight->setTorchMode(cameraId, false); 2924 if (res) { 2925 ALOGE("%s: torch client died but couldn't turn off torch: " 2926 "%s (%d)", __FUNCTION__, strerror(-res), res); 2927 return; 2928 } 2929 mTorchClientMap.removeItemsAt(i); 2930 break; 2931 } 2932 } 2933} 2934 2935/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) { 2936 2937 /** 2938 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the 2939 * binder driver 2940 */ 2941 2942 logClientDied(getCallingPid(), String8("Binder died unexpectedly")); 2943 2944 // check torch client 2945 handleTorchClientBinderDied(who); 2946 2947 // check camera device client 2948 if(!evictClientIdByRemote(who)) { 2949 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__); 2950 return; 2951 } 2952 2953 ALOGE("%s: Java client's binder died, removing it from the list of active clients", 2954 __FUNCTION__); 2955} 2956 2957void CameraService::updateStatus(StatusInternal status, const String8& cameraId) { 2958 updateStatus(status, cameraId, {}); 2959} 2960 2961void CameraService::updateStatus(StatusInternal status, const String8& cameraId, 2962 std::initializer_list<StatusInternal> rejectSourceStates) { 2963 // Do not lock mServiceLock here or can get into a deadlock from 2964 // connect() -> disconnect -> updateStatus 2965 2966 auto state = getCameraState(cameraId); 2967 2968 if (state == nullptr) { 2969 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__, 2970 cameraId.string()); 2971 return; 2972 } 2973 2974 // Update the status for this camera state, then send the onStatusChangedCallbacks to each 2975 // of the listeners with both the mStatusStatus and mStatusListenerLock held 2976 state->updateStatus(status, cameraId, rejectSourceStates, [this] 2977 (const String8& cameraId, StatusInternal status) { 2978 2979 if (status != StatusInternal::ENUMERATING) { 2980 // Update torch status if it has a flash unit. 2981 Mutex::Autolock al(mTorchStatusMutex); 2982 TorchModeStatus torchStatus; 2983 if (getTorchStatusLocked(cameraId, &torchStatus) != 2984 NAME_NOT_FOUND) { 2985 TorchModeStatus newTorchStatus = 2986 status == StatusInternal::PRESENT ? 2987 TorchModeStatus::AVAILABLE_OFF : 2988 TorchModeStatus::NOT_AVAILABLE; 2989 if (torchStatus != newTorchStatus) { 2990 onTorchStatusChangedLocked(cameraId, newTorchStatus); 2991 } 2992 } 2993 } 2994 2995 Mutex::Autolock lock(mStatusListenerLock); 2996 2997 for (auto& listener : mListenerList) { 2998 listener->onStatusChanged(mapToInterface(status), String16(cameraId)); 2999 } 3000 }); 3001} 3002 3003template<class Func> 3004void CameraService::CameraState::updateStatus(StatusInternal status, 3005 const String8& cameraId, 3006 std::initializer_list<StatusInternal> rejectSourceStates, 3007 Func onStatusUpdatedLocked) { 3008 Mutex::Autolock lock(mStatusLock); 3009 StatusInternal oldStatus = mStatus; 3010 mStatus = status; 3011 3012 if (oldStatus == status) { 3013 return; 3014 } 3015 3016 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__, 3017 cameraId.string(), oldStatus, status); 3018 3019 if (oldStatus == StatusInternal::NOT_PRESENT && 3020 (status != StatusInternal::PRESENT && 3021 status != StatusInternal::ENUMERATING)) { 3022 3023 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING", 3024 __FUNCTION__); 3025 mStatus = oldStatus; 3026 return; 3027 } 3028 3029 /** 3030 * Sometimes we want to conditionally do a transition. 3031 * For example if a client disconnects, we want to go to PRESENT 3032 * only if we weren't already in NOT_PRESENT or ENUMERATING. 3033 */ 3034 for (auto& rejectStatus : rejectSourceStates) { 3035 if (oldStatus == rejectStatus) { 3036 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source " 3037 "state was was in one of the bad states.", __FUNCTION__, cameraId.string()); 3038 mStatus = oldStatus; 3039 return; 3040 } 3041 } 3042 3043 onStatusUpdatedLocked(cameraId, status); 3044} 3045 3046void CameraService::updateProxyDeviceState(ICameraServiceProxy::CameraState newState, 3047 const String8& cameraId) { 3048 sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy(); 3049 if (proxyBinder == nullptr) return; 3050 String16 id(cameraId); 3051 proxyBinder->notifyCameraState(id, newState); 3052} 3053 3054status_t CameraService::getTorchStatusLocked( 3055 const String8& cameraId, 3056 TorchModeStatus *status) const { 3057 if (!status) { 3058 return BAD_VALUE; 3059 } 3060 ssize_t index = mTorchStatusMap.indexOfKey(cameraId); 3061 if (index == NAME_NOT_FOUND) { 3062 // invalid camera ID or the camera doesn't have a flash unit 3063 return NAME_NOT_FOUND; 3064 } 3065 3066 *status = mTorchStatusMap.valueAt(index); 3067 return OK; 3068} 3069 3070status_t CameraService::setTorchStatusLocked(const String8& cameraId, 3071 TorchModeStatus status) { 3072 ssize_t index = mTorchStatusMap.indexOfKey(cameraId); 3073 if (index == NAME_NOT_FOUND) { 3074 return BAD_VALUE; 3075 } 3076 mTorchStatusMap.editValueAt(index) = status; 3077 3078 return OK; 3079} 3080 3081}; // namespace android 3082