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