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