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