CameraService.cpp revision 9efdf956cc2eef63fef609375901d6c8df6351b6
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 LOG_NDEBUG 0 19 20#include <algorithm> 21#include <climits> 22#include <stdio.h> 23#include <cstring> 24#include <ctime> 25#include <string> 26#include <sys/types.h> 27#include <inttypes.h> 28#include <pthread.h> 29 30#include <binder/AppOpsManager.h> 31#include <binder/IPCThreadState.h> 32#include <binder/IServiceManager.h> 33#include <binder/MemoryBase.h> 34#include <binder/MemoryHeapBase.h> 35#include <binder/ProcessInfoService.h> 36#include <cutils/atomic.h> 37#include <cutils/properties.h> 38#include <cutils/multiuser.h> 39#include <gui/Surface.h> 40#include <hardware/hardware.h> 41#include <media/AudioSystem.h> 42#include <media/IMediaHTTPService.h> 43#include <media/mediaplayer.h> 44#include <utils/Errors.h> 45#include <utils/Log.h> 46#include <utils/String16.h> 47#include <utils/Trace.h> 48#include <system/camera_vendor_tags.h> 49#include <system/camera_metadata.h> 50#include <system/camera.h> 51 52#include "CameraService.h" 53#include "api1/CameraClient.h" 54#include "api1/Camera2Client.h" 55#include "api2/CameraDeviceClient.h" 56#include "utils/CameraTraces.h" 57#include "CameraDeviceFactory.h" 58 59namespace android { 60 61// ---------------------------------------------------------------------------- 62// Logging support -- this is for debugging only 63// Use "adb shell dumpsys media.camera -v 1" to change it. 64volatile int32_t gLogLevel = 0; 65 66#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__); 67#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__); 68 69static void setLogLevel(int level) { 70 android_atomic_write(level, &gLogLevel); 71} 72 73// ---------------------------------------------------------------------------- 74 75extern "C" { 76static void camera_device_status_change( 77 const struct camera_module_callbacks* callbacks, 78 int camera_id, 79 int new_status) { 80 sp<CameraService> cs = const_cast<CameraService*>( 81 static_cast<const CameraService*>(callbacks)); 82 83 cs->onDeviceStatusChanged(static_cast<camera_device_status_t>(camera_id), 84 static_cast<camera_device_status_t>(new_status)); 85} 86 87static void torch_mode_status_change( 88 const struct camera_module_callbacks* callbacks, 89 const char* camera_id, 90 int new_status) { 91 if (!callbacks || !camera_id) { 92 ALOGE("%s invalid parameters. callbacks %p, camera_id %p", __FUNCTION__, 93 callbacks, camera_id); 94 } 95 sp<CameraService> cs = const_cast<CameraService*>( 96 static_cast<const CameraService*>(callbacks)); 97 98 ICameraServiceListener::TorchStatus status; 99 switch (new_status) { 100 case TORCH_MODE_STATUS_NOT_AVAILABLE: 101 status = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE; 102 break; 103 case TORCH_MODE_STATUS_AVAILABLE_OFF: 104 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF; 105 break; 106 case TORCH_MODE_STATUS_AVAILABLE_ON: 107 status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON; 108 break; 109 default: 110 ALOGE("Unknown torch status %d", new_status); 111 return; 112 } 113 114 cs->onTorchStatusChanged( 115 String8(camera_id), 116 status); 117} 118} // extern "C" 119 120// ---------------------------------------------------------------------------- 121 122// This is ugly and only safe if we never re-create the CameraService, but 123// should be ok for now. 124static CameraService *gCameraService; 125 126CameraService::CameraService() 127 : mEventLog(DEFAULT_EVICTION_LOG_LENGTH), mSoundRef(0), mModule(0), mFlashlight(0) 128{ 129 ALOGI("CameraService started (pid=%d)", getpid()); 130 gCameraService = this; 131 132 this->camera_device_status_change = android::camera_device_status_change; 133 this->torch_mode_status_change = android::torch_mode_status_change; 134 135 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock); 136} 137 138void CameraService::onFirstRef() 139{ 140 ALOGI("CameraService process starting"); 141 142 BnCameraService::onFirstRef(); 143 144 camera_module_t *rawModule; 145 if (hw_get_module(CAMERA_HARDWARE_MODULE_ID, 146 (const hw_module_t **)&rawModule) < 0) { 147 ALOGE("Could not load camera HAL module"); 148 mNumberOfCameras = 0; 149 } 150 else { 151 mModule = new CameraModule(rawModule); 152 const hw_module_t *common = mModule->getRawModule(); 153 ALOGI("Loaded \"%s\" camera module", common->name); 154 mNumberOfCameras = mModule->getNumberOfCameras(); 155 156 mFlashlight = new CameraFlashlight(*mModule, *this); 157 status_t res = mFlashlight->findFlashUnits(); 158 if (res) { 159 // impossible because we haven't open any camera devices. 160 ALOGE("Failed to find flash units."); 161 } 162 163 for (int i = 0; i < mNumberOfCameras; i++) { 164 String8 cameraId = String8::format("%d", i); 165 166 // Defaults to use for cost and conflicting devices 167 int cost = 100; 168 char** conflicting_devices = nullptr; 169 size_t conflicting_devices_length = 0; 170 171 // If using post-2.4 module version, query the cost + conflicting devices from the HAL 172 if (common->module_api_version >= CAMERA_MODULE_API_VERSION_2_4) { 173 struct camera_info info; 174 status_t rc = mModule->getCameraInfo(i, &info); 175 if (rc == NO_ERROR) { 176 cost = info.resource_cost; 177 conflicting_devices = info.conflicting_devices; 178 conflicting_devices_length = info.conflicting_devices_length; 179 } else { 180 ALOGE("%s: Received error loading camera info for device %d, cost and" 181 " conflicting devices fields set to defaults for this device.", 182 __FUNCTION__, i); 183 } 184 } 185 186 std::set<String8> conflicting; 187 for (size_t i = 0; i < conflicting_devices_length; i++) { 188 conflicting.emplace(String8(conflicting_devices[i])); 189 } 190 191 // Initialize state for each camera device 192 { 193 Mutex::Autolock lock(mCameraStatesLock); 194 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost, 195 conflicting)); 196 } 197 198 if (mFlashlight->hasFlashUnit(cameraId)) { 199 mTorchStatusMap.add(cameraId, 200 ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF); 201 } 202 } 203 204 if (common->module_api_version >= CAMERA_MODULE_API_VERSION_2_1) { 205 mModule->setCallbacks(this); 206 } 207 208 VendorTagDescriptor::clearGlobalVendorTagDescriptor(); 209 210 if (common->module_api_version >= CAMERA_MODULE_API_VERSION_2_2) { 211 setUpVendorTags(); 212 } 213 214 CameraDeviceFactory::registerService(this); 215 } 216} 217 218CameraService::~CameraService() { 219 if (mModule) { 220 delete mModule; 221 mModule = nullptr; 222 } 223 VendorTagDescriptor::clearGlobalVendorTagDescriptor(); 224 gCameraService = nullptr; 225} 226 227void CameraService::onDeviceStatusChanged(camera_device_status_t cameraId, 228 camera_device_status_t newStatus) { 229 ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__, 230 cameraId, newStatus); 231 232 String8 id = String8::format("%d", cameraId); 233 std::shared_ptr<CameraState> state = getCameraState(id); 234 235 if (state == nullptr) { 236 ALOGE("%s: Bad camera ID %d", __FUNCTION__, cameraId); 237 return; 238 } 239 240 ICameraServiceListener::Status oldStatus = state->getStatus(); 241 242 if (oldStatus == static_cast<ICameraServiceListener::Status>(newStatus)) { 243 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus); 244 return; 245 } 246 247 if (newStatus == CAMERA_DEVICE_STATUS_NOT_PRESENT) { 248 sp<BasicClient> clientToDisconnect; 249 { 250 // Don't do this in updateStatus to avoid deadlock over mServiceLock 251 Mutex::Autolock lock(mServiceLock); 252 253 // Set the device status to NOT_PRESENT, clients will no longer be able to connect 254 // to this device until the status changes 255 updateStatus(ICameraServiceListener::STATUS_NOT_PRESENT, id); 256 257 // Remove cached shim parameters 258 state->setShimParams(CameraParameters()); 259 260 // Remove the client from the list of active clients 261 clientToDisconnect = removeClientLocked(id); 262 263 // Notify the client of disconnection 264 clientToDisconnect->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED, 265 CaptureResultExtras{}); 266 } 267 268 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL", 269 __FUNCTION__, id.string()); 270 271 // Disconnect client 272 if (clientToDisconnect.get() != nullptr) { 273 // Ensure not in binder RPC so client disconnect PID checks work correctly 274 LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(), 275 "onDeviceStatusChanged must be called from the camera service process!"); 276 clientToDisconnect->disconnect(); 277 } 278 279 } else { 280 updateStatus(static_cast<ICameraServiceListener::Status>(newStatus), id); 281 } 282 283} 284 285void CameraService::onTorchStatusChanged(const String8& cameraId, 286 ICameraServiceListener::TorchStatus newStatus) { 287 Mutex::Autolock al(mTorchStatusMutex); 288 onTorchStatusChangedLocked(cameraId, newStatus); 289} 290 291void CameraService::onTorchStatusChangedLocked(const String8& cameraId, 292 ICameraServiceListener::TorchStatus newStatus) { 293 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d", 294 __FUNCTION__, cameraId.string(), newStatus); 295 296 ICameraServiceListener::TorchStatus status; 297 status_t res = getTorchStatusLocked(cameraId, &status); 298 if (res) { 299 ALOGE("%s: cannot get torch status of camera %s", cameraId.string()); 300 return; 301 } 302 if (status == newStatus) { 303 ALOGE("%s: Torch state transition to the same status 0x%x not allowed", 304 __FUNCTION__, (uint32_t)newStatus); 305 return; 306 } 307 308 res = setTorchStatusLocked(cameraId, newStatus); 309 if (res) { 310 ALOGE("%s: Failed to set the torch status", __FUNCTION__, 311 (uint32_t)newStatus); 312 return; 313 } 314 315 { 316 Mutex::Autolock lock(mStatusListenerLock); 317 for (auto& i : mListenerList) { 318 i->onTorchStatusChanged(newStatus, String16{cameraId}); 319 } 320 } 321} 322 323 324int32_t CameraService::getNumberOfCameras() { 325 return mNumberOfCameras; 326} 327 328status_t CameraService::getCameraInfo(int cameraId, 329 struct CameraInfo* cameraInfo) { 330 if (!mModule) { 331 return -ENODEV; 332 } 333 334 if (cameraId < 0 || cameraId >= mNumberOfCameras) { 335 return BAD_VALUE; 336 } 337 338 struct camera_info info; 339 status_t rc = filterGetInfoErrorCode( 340 mModule->getCameraInfo(cameraId, &info)); 341 cameraInfo->facing = info.facing; 342 cameraInfo->orientation = info.orientation; 343 return rc; 344} 345 346int CameraService::cameraIdToInt(const String8& cameraId) { 347 errno = 0; 348 size_t pos = 0; 349 int ret = stoi(std::string{cameraId.string()}, &pos); 350 if (errno != 0 || pos != cameraId.size()) { 351 return -1; 352 } 353 return ret; 354} 355 356status_t CameraService::generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo) { 357 status_t ret = OK; 358 struct CameraInfo info; 359 if ((ret = getCameraInfo(cameraId, &info)) != OK) { 360 return ret; 361 } 362 363 CameraMetadata shimInfo; 364 int32_t orientation = static_cast<int32_t>(info.orientation); 365 if ((ret = shimInfo.update(ANDROID_SENSOR_ORIENTATION, &orientation, 1)) != OK) { 366 return ret; 367 } 368 369 uint8_t facing = (info.facing == CAMERA_FACING_FRONT) ? 370 ANDROID_LENS_FACING_FRONT : ANDROID_LENS_FACING_BACK; 371 if ((ret = shimInfo.update(ANDROID_LENS_FACING, &facing, 1)) != OK) { 372 return ret; 373 } 374 375 CameraParameters shimParams; 376 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) { 377 // Error logged by callee 378 return ret; 379 } 380 381 Vector<Size> sizes; 382 Vector<Size> jpegSizes; 383 Vector<int32_t> formats; 384 const char* supportedPreviewFormats; 385 { 386 shimParams.getSupportedPreviewSizes(/*out*/sizes); 387 shimParams.getSupportedPreviewFormats(/*out*/formats); 388 shimParams.getSupportedPictureSizes(/*out*/jpegSizes); 389 } 390 391 // Always include IMPLEMENTATION_DEFINED 392 formats.add(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED); 393 394 const size_t INTS_PER_CONFIG = 4; 395 396 // Build available stream configurations metadata 397 size_t streamConfigSize = (sizes.size() * formats.size() + jpegSizes.size()) * INTS_PER_CONFIG; 398 399 Vector<int32_t> streamConfigs; 400 streamConfigs.setCapacity(streamConfigSize); 401 402 for (size_t i = 0; i < formats.size(); ++i) { 403 for (size_t j = 0; j < sizes.size(); ++j) { 404 streamConfigs.add(formats[i]); 405 streamConfigs.add(sizes[j].width); 406 streamConfigs.add(sizes[j].height); 407 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT); 408 } 409 } 410 411 for (size_t i = 0; i < jpegSizes.size(); ++i) { 412 streamConfigs.add(HAL_PIXEL_FORMAT_BLOB); 413 streamConfigs.add(jpegSizes[i].width); 414 streamConfigs.add(jpegSizes[i].height); 415 streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT); 416 } 417 418 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS, 419 streamConfigs.array(), streamConfigSize)) != OK) { 420 return ret; 421 } 422 423 int64_t fakeMinFrames[0]; 424 // TODO: Fixme, don't fake min frame durations. 425 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS, 426 fakeMinFrames, 0)) != OK) { 427 return ret; 428 } 429 430 int64_t fakeStalls[0]; 431 // TODO: Fixme, don't fake stall durations. 432 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STALL_DURATIONS, 433 fakeStalls, 0)) != OK) { 434 return ret; 435 } 436 437 *cameraInfo = shimInfo; 438 return OK; 439} 440 441status_t CameraService::getCameraCharacteristics(int cameraId, 442 CameraMetadata* cameraInfo) { 443 if (!cameraInfo) { 444 ALOGE("%s: cameraInfo is NULL", __FUNCTION__); 445 return BAD_VALUE; 446 } 447 448 if (!mModule) { 449 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__); 450 return -ENODEV; 451 } 452 453 if (cameraId < 0 || cameraId >= mNumberOfCameras) { 454 ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId); 455 return BAD_VALUE; 456 } 457 458 int facing; 459 status_t ret = OK; 460 if (mModule->getRawModule()->module_api_version < CAMERA_MODULE_API_VERSION_2_0 || 461 getDeviceVersion(cameraId, &facing) <= CAMERA_DEVICE_API_VERSION_2_1 ) { 462 /** 463 * Backwards compatibility mode for old HALs: 464 * - Convert CameraInfo into static CameraMetadata properties. 465 * - Retrieve cached CameraParameters for this camera. If none exist, 466 * attempt to open CameraClient and retrieve the CameraParameters. 467 * - Convert cached CameraParameters into static CameraMetadata 468 * properties. 469 */ 470 ALOGI("%s: Switching to HAL1 shim implementation...", __FUNCTION__); 471 472 if ((ret = generateShimMetadata(cameraId, cameraInfo)) != OK) { 473 return ret; 474 } 475 476 } else { 477 /** 478 * Normal HAL 2.1+ codepath. 479 */ 480 struct camera_info info; 481 ret = filterGetInfoErrorCode(mModule->getCameraInfo(cameraId, &info)); 482 *cameraInfo = info.static_camera_characteristics; 483 } 484 485 return ret; 486} 487 488int CameraService::getCallingPid() { 489 return IPCThreadState::self()->getCallingPid(); 490} 491 492int CameraService::getCallingUid() { 493 return IPCThreadState::self()->getCallingUid(); 494} 495 496String8 CameraService::getFormattedCurrentTime() { 497 time_t now = time(nullptr); 498 char formattedTime[64]; 499 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now)); 500 return String8(formattedTime); 501} 502 503int CameraService::getCameraPriorityFromProcState(int procState) { 504 // Find the priority for the camera usage based on the process state. Higher priority clients 505 // win for evictions. 506 // Note: Unlike the ordering for ActivityManager, persistent system processes will always lose 507 // the camera to the top/foreground applications. 508 switch(procState) { 509 case PROCESS_STATE_TOP: // User visible 510 return 100; 511 case PROCESS_STATE_IMPORTANT_FOREGROUND: // Foreground 512 return 90; 513 case PROCESS_STATE_PERSISTENT: // Persistent system services 514 case PROCESS_STATE_PERSISTENT_UI: 515 return 80; 516 case PROCESS_STATE_IMPORTANT_BACKGROUND: // "Important" background processes 517 return 70; 518 case PROCESS_STATE_BACKUP: // Everything else 519 case PROCESS_STATE_HEAVY_WEIGHT: 520 case PROCESS_STATE_SERVICE: 521 case PROCESS_STATE_RECEIVER: 522 case PROCESS_STATE_HOME: 523 case PROCESS_STATE_LAST_ACTIVITY: 524 case PROCESS_STATE_CACHED_ACTIVITY: 525 case PROCESS_STATE_CACHED_ACTIVITY_CLIENT: 526 case PROCESS_STATE_CACHED_EMPTY: 527 return 1; 528 case PROCESS_STATE_NONEXISTENT: 529 return -1; 530 default: 531 ALOGE("%s: Received unknown process state from ActivityManagerService!", __FUNCTION__); 532 return -1; 533 } 534} 535 536status_t CameraService::getCameraVendorTagDescriptor(/*out*/sp<VendorTagDescriptor>& desc) { 537 if (!mModule) { 538 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__); 539 return -ENODEV; 540 } 541 542 desc = VendorTagDescriptor::getGlobalVendorTagDescriptor(); 543 return OK; 544} 545 546int CameraService::getDeviceVersion(int cameraId, int* facing) { 547 struct camera_info info; 548 if (mModule->getCameraInfo(cameraId, &info) != OK) { 549 return -1; 550 } 551 552 int deviceVersion; 553 if (mModule->getRawModule()->module_api_version >= CAMERA_MODULE_API_VERSION_2_0) { 554 deviceVersion = info.device_version; 555 } else { 556 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0; 557 } 558 559 if (facing) { 560 *facing = info.facing; 561 } 562 563 return deviceVersion; 564} 565 566status_t CameraService::filterGetInfoErrorCode(status_t err) { 567 switch(err) { 568 case NO_ERROR: 569 case -EINVAL: 570 return err; 571 default: 572 break; 573 } 574 return -ENODEV; 575} 576 577bool CameraService::setUpVendorTags() { 578 vendor_tag_ops_t vOps = vendor_tag_ops_t(); 579 580 // Check if vendor operations have been implemented 581 if (!mModule->isVendorTagDefined()) { 582 ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__); 583 return false; 584 } 585 586 ATRACE_BEGIN("camera3->get_metadata_vendor_tag_ops"); 587 mModule->getVendorTagOps(&vOps); 588 ATRACE_END(); 589 590 // Ensure all vendor operations are present 591 if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL || 592 vOps.get_section_name == NULL || vOps.get_tag_name == NULL || 593 vOps.get_tag_type == NULL) { 594 ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions." 595 , __FUNCTION__); 596 return false; 597 } 598 599 // Read all vendor tag definitions into a descriptor 600 sp<VendorTagDescriptor> desc; 601 status_t res; 602 if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc)) 603 != OK) { 604 ALOGE("%s: Could not generate descriptor from vendor tag operations," 605 "received error %s (%d). Camera clients will not be able to use" 606 "vendor tags", __FUNCTION__, strerror(res), res); 607 return false; 608 } 609 610 // Set the global descriptor to use with camera metadata 611 VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc); 612 return true; 613} 614 615status_t CameraService::makeClient(const sp<CameraService>& cameraService, 616 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId, 617 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode, 618 int halVersion, int deviceVersion, apiLevel effectiveApiLevel, 619 /*out*/sp<BasicClient>* client) { 620 621 // TODO: Update CameraClients + HAL interface to use strings for Camera IDs 622 int id = cameraIdToInt(cameraId); 623 if (id == -1) { 624 ALOGE("%s: Invalid camera ID %s, cannot convert to integer.", __FUNCTION__, 625 cameraId.string()); 626 return BAD_VALUE; 627 } 628 629 if (halVersion < 0 || halVersion == deviceVersion) { 630 // Default path: HAL version is unspecified by caller, create CameraClient 631 // based on device version reported by the HAL. 632 switch(deviceVersion) { 633 case CAMERA_DEVICE_API_VERSION_1_0: 634 if (effectiveApiLevel == API_1) { // Camera1 API route 635 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get()); 636 *client = new CameraClient(cameraService, tmp, packageName, id, facing, 637 clientPid, clientUid, getpid(), legacyMode); 638 } else { // Camera2 API route 639 ALOGW("Camera using old HAL version: %d", deviceVersion); 640 return -EOPNOTSUPP; 641 } 642 break; 643 case CAMERA_DEVICE_API_VERSION_2_0: 644 case CAMERA_DEVICE_API_VERSION_2_1: 645 case CAMERA_DEVICE_API_VERSION_3_0: 646 case CAMERA_DEVICE_API_VERSION_3_1: 647 case CAMERA_DEVICE_API_VERSION_3_2: 648 case CAMERA_DEVICE_API_VERSION_3_3: 649 if (effectiveApiLevel == API_1) { // Camera1 API route 650 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get()); 651 *client = new Camera2Client(cameraService, tmp, packageName, id, facing, 652 clientPid, clientUid, servicePid, legacyMode); 653 } else { // Camera2 API route 654 sp<ICameraDeviceCallbacks> tmp = 655 static_cast<ICameraDeviceCallbacks*>(cameraCb.get()); 656 *client = new CameraDeviceClient(cameraService, tmp, packageName, id, 657 facing, clientPid, clientUid, servicePid); 658 } 659 break; 660 default: 661 // Should not be reachable 662 ALOGE("Unknown camera device HAL version: %d", deviceVersion); 663 return INVALID_OPERATION; 664 } 665 } else { 666 // A particular HAL version is requested by caller. Create CameraClient 667 // based on the requested HAL version. 668 if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 && 669 halVersion == CAMERA_DEVICE_API_VERSION_1_0) { 670 // Only support higher HAL version device opened as HAL1.0 device. 671 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get()); 672 *client = new CameraClient(cameraService, tmp, packageName, id, facing, 673 clientPid, clientUid, servicePid, legacyMode); 674 } else { 675 // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet. 676 ALOGE("Invalid camera HAL version %x: HAL %x device can only be" 677 " opened as HAL %x device", halVersion, deviceVersion, 678 CAMERA_DEVICE_API_VERSION_1_0); 679 return INVALID_OPERATION; 680 } 681 } 682 return NO_ERROR; 683} 684 685status_t CameraService::initializeShimMetadata(int cameraId) { 686 int uid = getCallingUid(); 687 688 String16 internalPackageName("media"); 689 String8 id = String8::format("%d", cameraId); 690 status_t ret = NO_ERROR; 691 sp<Client> tmp = nullptr; 692 if ((ret = connectHelper<ICameraClient,Client>(sp<ICameraClient>{nullptr}, id, 693 static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED), internalPackageName, uid, API_1, 694 false, true, tmp)) != NO_ERROR) { 695 ALOGE("%s: Error %d (%s) initializing shim metadata.", __FUNCTION__, ret, strerror(ret)); 696 return ret; 697 } 698 return NO_ERROR; 699} 700 701status_t CameraService::getLegacyParametersLazy(int cameraId, 702 /*out*/ 703 CameraParameters* parameters) { 704 705 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId); 706 707 status_t ret = 0; 708 709 if (parameters == NULL) { 710 ALOGE("%s: parameters must not be null", __FUNCTION__); 711 return BAD_VALUE; 712 } 713 714 String8 id = String8::format("%d", cameraId); 715 716 // Check if we already have parameters 717 { 718 // Scope for service lock 719 Mutex::Autolock lock(mServiceLock); 720 auto cameraState = getCameraState(id); 721 if (cameraState == nullptr) { 722 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string()); 723 return BAD_VALUE; 724 } 725 CameraParameters p = cameraState->getShimParams(); 726 if (!p.isEmpty()) { 727 *parameters = p; 728 return NO_ERROR; 729 } 730 } 731 732 int64_t token = IPCThreadState::self()->clearCallingIdentity(); 733 ret = initializeShimMetadata(cameraId); 734 IPCThreadState::self()->restoreCallingIdentity(token); 735 if (ret != NO_ERROR) { 736 // Error already logged by callee 737 return ret; 738 } 739 740 // Check for parameters again 741 { 742 // Scope for service lock 743 Mutex::Autolock lock(mServiceLock); 744 auto cameraState = getCameraState(id); 745 if (cameraState == nullptr) { 746 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string()); 747 return BAD_VALUE; 748 } 749 CameraParameters p = cameraState->getShimParams(); 750 if (!p.isEmpty()) { 751 *parameters = p; 752 return NO_ERROR; 753 } 754 } 755 756 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.", 757 __FUNCTION__); 758 return INVALID_OPERATION; 759} 760 761status_t CameraService::validateConnect(const String8& cameraId, /*inout*/int& clientUid) const { 762 763 int callingPid = getCallingPid(); 764 765 if (clientUid == USE_CALLING_UID) { 766 clientUid = getCallingUid(); 767 } else { 768 // We only trust our own process to forward client UIDs 769 if (callingPid != getpid()) { 770 ALOGE("CameraService::connect X (PID %d) rejected (don't trust clientUid)", 771 callingPid); 772 return PERMISSION_DENIED; 773 } 774 } 775 776 if (!mModule) { 777 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)", 778 callingPid); 779 return -ENODEV; 780 } 781 782 if (getCameraState(cameraId) == nullptr) { 783 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid, 784 cameraId.string()); 785 return -ENODEV; 786 } 787 788 // Check device policy for this camera 789 char value[PROPERTY_VALUE_MAX]; 790 char key[PROPERTY_KEY_MAX]; 791 int clientUserId = multiuser_get_user_id(clientUid); 792 snprintf(key, PROPERTY_KEY_MAX, "sys.secpolicy.camera.off_%d", clientUserId); 793 property_get(key, value, "0"); 794 if (strcmp(value, "1") == 0) { 795 // Camera is disabled by DevicePolicyManager. 796 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is disabled by device " 797 "policy)", callingPid, cameraId.string()); 798 return -EACCES; 799 } 800 801 return checkIfDeviceIsUsable(cameraId); 802} 803 804status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const { 805 auto cameraState = getCameraState(cameraId); 806 int callingPid = getCallingPid(); 807 if (cameraState == nullptr) { 808 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid, 809 cameraId.string()); 810 return -ENODEV; 811 } 812 813 ICameraServiceListener::Status currentStatus = cameraState->getStatus(); 814 if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) { 815 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)", 816 callingPid, cameraId.string()); 817 return -ENODEV; 818 } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) { 819 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)", 820 callingPid, cameraId.string()); 821 return -EBUSY; 822 } 823 824 return NO_ERROR; 825} 826 827void CameraService::finishConnectLocked(const sp<BasicClient>& client, 828 const CameraService::DescriptorPtr& desc) { 829 830 // Make a descriptor for the incoming client 831 auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc); 832 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor); 833 834 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()), 835 String8(client->getPackageName())); 836 837 if (evicted.size() > 0) { 838 // This should never happen - clients should already have been removed in disconnect 839 for (auto& i : evicted) { 840 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect", 841 __FUNCTION__, i->getKey().string()); 842 } 843 844 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly", 845 __FUNCTION__); 846 } 847} 848 849status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid, 850 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName, 851 /*out*/ 852 sp<BasicClient>* client, 853 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) { 854 855 status_t ret = NO_ERROR; 856 std::vector<sp<BasicClient>> evictedClients; 857 DescriptorPtr clientDescriptor; 858 { 859 if (effectiveApiLevel == API_1) { 860 // If we are using API1, any existing client for this camera ID with the same remote 861 // should be returned rather than evicted to allow MediaRecorder to work properly. 862 863 auto current = mActiveClientManager.get(cameraId); 864 if (current != nullptr) { 865 auto clientSp = current->getValue(); 866 if (clientSp.get() != nullptr) { // should never be needed 867 if (clientSp->getRemote() == remoteCallback) { 868 ALOGI("CameraService::connect X (PID %d) (second call from same" 869 "app binder, returning the same client)", clientPid); 870 *client = clientSp; 871 return NO_ERROR; 872 } 873 } 874 } 875 } 876 877 // Return error if the device was unplugged or removed by the HAL for some reason 878 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) { 879 return ret; 880 } 881 882 // Get current active client PIDs 883 std::vector<int> ownerPids(mActiveClientManager.getAllOwners()); 884 ownerPids.push_back(clientPid); 885 886 // Use the value +PROCESS_STATE_NONEXISTENT, to avoid taking 887 // address of PROCESS_STATE_NONEXISTENT as a reference argument 888 // for the vector constructor. PROCESS_STATE_NONEXISTENT does 889 // not have an out-of-class definition. 890 std::vector<int> priorities(ownerPids.size(), +PROCESS_STATE_NONEXISTENT); 891 892 // Get priorites of all active PIDs 893 ProcessInfoService::getProcessStatesFromPids(ownerPids.size(), &ownerPids[0], 894 /*out*/&priorities[0]); 895 896 // Update all active clients' priorities 897 std::map<int,int> pidToPriorityMap; 898 for (size_t i = 0; i < ownerPids.size() - 1; i++) { 899 pidToPriorityMap.emplace(ownerPids[i], getCameraPriorityFromProcState(priorities[i])); 900 } 901 mActiveClientManager.updatePriorities(pidToPriorityMap); 902 903 // Get state for the given cameraId 904 auto state = getCameraState(cameraId); 905 if (state == nullptr) { 906 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)", 907 clientPid, cameraId.string()); 908 return BAD_VALUE; 909 } 910 911 // Make descriptor for incoming client 912 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId, 913 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()), 914 state->getConflicting(), 915 getCameraPriorityFromProcState(priorities[priorities.size() - 1]), clientPid); 916 917 // Find clients that would be evicted 918 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor); 919 920 // If the incoming client was 'evicted,' higher priority clients have the camera in the 921 // background, so we cannot do evictions 922 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) { 923 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher" 924 " priority).", clientPid); 925 926 sp<BasicClient> clientSp = clientDescriptor->getValue(); 927 String8 curTime = getFormattedCurrentTime(); 928 auto incompatibleClients = 929 mActiveClientManager.getIncompatibleClients(clientDescriptor); 930 931 String8 msg = String8::format("%s : DENIED connect device %s client for package %s " 932 "(PID %d, priority %d)", curTime.string(), 933 cameraId.string(), packageName.string(), clientPid, 934 getCameraPriorityFromProcState(priorities[priorities.size() - 1])); 935 936 for (auto& i : incompatibleClients) { 937 msg.appendFormat("\n - Blocked by existing device %s client for package %s" 938 "(PID %" PRId32 ", priority %" PRId32 ")", i->getKey().string(), 939 String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(), 940 i->getPriority()); 941 } 942 943 // Log the client's attempt 944 mEventLog.add(msg); 945 946 return -EBUSY; 947 } 948 949 for (auto& i : evicted) { 950 sp<BasicClient> clientSp = i->getValue(); 951 if (clientSp.get() == nullptr) { 952 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__); 953 954 // TODO: Remove this 955 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list", 956 __FUNCTION__); 957 mActiveClientManager.remove(i); 958 continue; 959 } 960 961 ALOGE("CameraService::connect evicting conflicting client for camera ID %s", 962 i->getKey().string()); 963 evictedClients.push_back(clientSp); 964 965 String8 curTime = getFormattedCurrentTime(); 966 967 // Log the clients evicted 968 mEventLog.add(String8::format("%s : EVICT device %s client for package %s (PID %" 969 PRId32 ", priority %" PRId32 ")\n - Evicted by device %s client for " 970 "package %s (PID %d, priority %" PRId32 ")", curTime.string(), 971 i->getKey().string(), String8{clientSp->getPackageName()}.string(), 972 i->getOwnerId(), i->getPriority(), cameraId.string(), 973 packageName.string(), clientPid, 974 getCameraPriorityFromProcState(priorities[priorities.size() - 1]))); 975 976 // Notify the client of disconnection 977 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED, 978 CaptureResultExtras()); 979 } 980 } 981 982 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking 983 // other clients from connecting in mServiceLockWrapper if held 984 mServiceLock.unlock(); 985 986 // Clear caller identity temporarily so client disconnect PID checks work correctly 987 int64_t token = IPCThreadState::self()->clearCallingIdentity(); 988 989 // Destroy evicted clients 990 for (auto& i : evictedClients) { 991 // Disconnect is blocking, and should only have returned when HAL has cleaned up 992 i->disconnect(); // Clients will remove themselves from the active client list here 993 } 994 evictedClients.clear(); 995 996 IPCThreadState::self()->restoreCallingIdentity(token); 997 998 // Once clients have been disconnected, relock 999 mServiceLock.lock(); 1000 1001 // Check again if the device was unplugged or something while we weren't holding mServiceLock 1002 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) { 1003 return ret; 1004 } 1005 1006 *partial = clientDescriptor; 1007 return NO_ERROR; 1008} 1009 1010status_t CameraService::connect( 1011 const sp<ICameraClient>& cameraClient, 1012 int cameraId, 1013 const String16& clientPackageName, 1014 int clientUid, 1015 /*out*/ 1016 sp<ICamera>& device) { 1017 1018 status_t ret = NO_ERROR; 1019 String8 id = String8::format("%d", cameraId); 1020 sp<Client> client = nullptr; 1021 ret = connectHelper<ICameraClient,Client>(cameraClient, id, CAMERA_HAL_API_VERSION_UNSPECIFIED, 1022 clientPackageName, clientUid, API_1, false, false, /*out*/client); 1023 1024 if(ret != NO_ERROR) { 1025 return ret; 1026 } 1027 1028 device = client; 1029 return NO_ERROR; 1030} 1031 1032status_t CameraService::connectLegacy( 1033 const sp<ICameraClient>& cameraClient, 1034 int cameraId, int halVersion, 1035 const String16& clientPackageName, 1036 int clientUid, 1037 /*out*/ 1038 sp<ICamera>& device) { 1039 1040 int apiVersion = mModule->getRawModule()->module_api_version; 1041 if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED && 1042 apiVersion < CAMERA_MODULE_API_VERSION_2_3) { 1043 /* 1044 * Either the HAL version is unspecified in which case this just creates 1045 * a camera client selected by the latest device version, or 1046 * it's a particular version in which case the HAL must supported 1047 * the open_legacy call 1048 */ 1049 ALOGE("%s: camera HAL module version %x doesn't support connecting to legacy HAL devices!", 1050 __FUNCTION__, apiVersion); 1051 return INVALID_OPERATION; 1052 } 1053 1054 status_t ret = NO_ERROR; 1055 String8 id = String8::format("%d", cameraId); 1056 sp<Client> client = nullptr; 1057 ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion, clientPackageName, 1058 clientUid, API_1, true, false, /*out*/client); 1059 1060 if(ret != NO_ERROR) { 1061 return ret; 1062 } 1063 1064 device = client; 1065 return NO_ERROR; 1066} 1067 1068status_t CameraService::connectDevice( 1069 const sp<ICameraDeviceCallbacks>& cameraCb, 1070 int cameraId, 1071 const String16& clientPackageName, 1072 int clientUid, 1073 /*out*/ 1074 sp<ICameraDeviceUser>& device) { 1075 1076 status_t ret = NO_ERROR; 1077 String8 id = String8::format("%d", cameraId); 1078 sp<CameraDeviceClient> client = nullptr; 1079 ret = connectHelper<ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id, 1080 CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, API_2, false, false, 1081 /*out*/client); 1082 1083 if(ret != NO_ERROR) { 1084 return ret; 1085 } 1086 1087 device = client; 1088 return NO_ERROR; 1089} 1090 1091status_t CameraService::setTorchMode(const String16& cameraId, bool enabled, 1092 const sp<IBinder>& clientBinder) { 1093 if (enabled && clientBinder == NULL) { 1094 ALOGE("%s: torch client binder is NULL", __FUNCTION__); 1095 return -EINVAL; 1096 } 1097 1098 String8 id = String8(cameraId.string()); 1099 1100 // verify id is valid. 1101 auto state = getCameraState(id); 1102 if (state == nullptr) { 1103 ALOGE("%s: camera id is invalid %s", id.string()); 1104 return -EINVAL; 1105 } 1106 1107 ICameraServiceListener::Status cameraStatus = state->getStatus(); 1108 if (cameraStatus != ICameraServiceListener::STATUS_PRESENT && 1109 cameraStatus != ICameraServiceListener::STATUS_NOT_AVAILABLE) { 1110 ALOGE("%s: camera id is invalid %s", id.string()); 1111 return -EINVAL; 1112 } 1113 1114 { 1115 Mutex::Autolock al(mTorchStatusMutex); 1116 ICameraServiceListener::TorchStatus status; 1117 status_t res = getTorchStatusLocked(id, &status); 1118 if (res) { 1119 ALOGE("%s: getting current torch status failed for camera %s", 1120 __FUNCTION__, id.string()); 1121 return -EINVAL; 1122 } 1123 1124 if (status == ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE) { 1125 if (cameraStatus == ICameraServiceListener::STATUS_NOT_AVAILABLE) { 1126 ALOGE("%s: torch mode of camera %s is not available because " 1127 "camera is in use", __FUNCTION__, id.string()); 1128 return -EBUSY; 1129 } else { 1130 ALOGE("%s: torch mode of camera %s is not available due to " 1131 "insufficient resources", __FUNCTION__, id.string()); 1132 return -EUSERS; 1133 } 1134 } 1135 } 1136 1137 status_t res = mFlashlight->setTorchMode(id, enabled); 1138 if (res) { 1139 ALOGE("%s: setting torch mode of camera %s to %d failed. %s (%d)", 1140 __FUNCTION__, id.string(), enabled, strerror(-res), res); 1141 return res; 1142 } 1143 1144 { 1145 // update the link to client's death 1146 Mutex::Autolock al(mTorchClientMapMutex); 1147 ssize_t index = mTorchClientMap.indexOfKey(id); 1148 if (enabled) { 1149 if (index == NAME_NOT_FOUND) { 1150 mTorchClientMap.add(id, clientBinder); 1151 } else { 1152 const sp<IBinder> oldBinder = mTorchClientMap.valueAt(index); 1153 oldBinder->unlinkToDeath(this); 1154 1155 mTorchClientMap.replaceValueAt(index, clientBinder); 1156 } 1157 clientBinder->linkToDeath(this); 1158 } else if (index != NAME_NOT_FOUND) { 1159 sp<IBinder> oldBinder = mTorchClientMap.valueAt(index); 1160 oldBinder->unlinkToDeath(this); 1161 } 1162 } 1163 1164 return OK; 1165} 1166 1167status_t CameraService::addListener( 1168 const sp<ICameraServiceListener>& listener) { 1169 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get()); 1170 1171 if (listener == 0) { 1172 ALOGE("%s: Listener must not be null", __FUNCTION__); 1173 return BAD_VALUE; 1174 } 1175 1176 Mutex::Autolock lock(mServiceLock); 1177 1178 { 1179 Mutex::Autolock lock(mStatusListenerLock); 1180 for (auto& it : mListenerList) { 1181 if (IInterface::asBinder(it) == IInterface::asBinder(listener)) { 1182 ALOGW("%s: Tried to add listener %p which was already subscribed", 1183 __FUNCTION__, listener.get()); 1184 return ALREADY_EXISTS; 1185 } 1186 } 1187 1188 mListenerList.push_back(listener); 1189 } 1190 1191 1192 /* Immediately signal current status to this listener only */ 1193 { 1194 Mutex::Autolock lock(mCameraStatesLock); 1195 for (auto& i : mCameraStates) { 1196 // TODO: Update binder to use String16 for camera IDs and remove; 1197 int id = cameraIdToInt(i.first); 1198 if (id == -1) continue; 1199 1200 listener->onStatusChanged(i.second->getStatus(), id); 1201 } 1202 } 1203 1204 /* Immediately signal current torch status to this listener only */ 1205 { 1206 Mutex::Autolock al(mTorchStatusMutex); 1207 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) { 1208 String16 id = String16(mTorchStatusMap.keyAt(i).string()); 1209 listener->onTorchStatusChanged(mTorchStatusMap.valueAt(i), id); 1210 } 1211 } 1212 1213 return OK; 1214} 1215 1216status_t CameraService::removeListener(const sp<ICameraServiceListener>& listener) { 1217 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get()); 1218 1219 if (listener == 0) { 1220 ALOGE("%s: Listener must not be null", __FUNCTION__); 1221 return BAD_VALUE; 1222 } 1223 1224 Mutex::Autolock lock(mServiceLock); 1225 1226 { 1227 Mutex::Autolock lock(mStatusListenerLock); 1228 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) { 1229 if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) { 1230 mListenerList.erase(it); 1231 return OK; 1232 } 1233 } 1234 } 1235 1236 ALOGW("%s: Tried to remove a listener %p which was not subscribed", 1237 __FUNCTION__, listener.get()); 1238 1239 return BAD_VALUE; 1240} 1241 1242status_t CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) { 1243 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId); 1244 1245 if (parameters == NULL) { 1246 ALOGE("%s: parameters must not be null", __FUNCTION__); 1247 return BAD_VALUE; 1248 } 1249 1250 status_t ret = 0; 1251 1252 CameraParameters shimParams; 1253 if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) { 1254 // Error logged by caller 1255 return ret; 1256 } 1257 1258 String8 shimParamsString8 = shimParams.flatten(); 1259 String16 shimParamsString16 = String16(shimParamsString8); 1260 1261 *parameters = shimParamsString16; 1262 1263 return OK; 1264} 1265 1266status_t CameraService::supportsCameraApi(int cameraId, int apiVersion) { 1267 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId); 1268 1269 switch (apiVersion) { 1270 case API_VERSION_1: 1271 case API_VERSION_2: 1272 break; 1273 default: 1274 ALOGE("%s: Bad API version %d", __FUNCTION__, apiVersion); 1275 return BAD_VALUE; 1276 } 1277 1278 int facing = -1; 1279 int deviceVersion = getDeviceVersion(cameraId, &facing); 1280 1281 switch(deviceVersion) { 1282 case CAMERA_DEVICE_API_VERSION_1_0: 1283 case CAMERA_DEVICE_API_VERSION_2_0: 1284 case CAMERA_DEVICE_API_VERSION_2_1: 1285 case CAMERA_DEVICE_API_VERSION_3_0: 1286 case CAMERA_DEVICE_API_VERSION_3_1: 1287 if (apiVersion == API_VERSION_2) { 1288 ALOGV("%s: Camera id %d uses HAL prior to HAL3.2, doesn't support api2 without shim", 1289 __FUNCTION__, cameraId); 1290 return -EOPNOTSUPP; 1291 } else { // if (apiVersion == API_VERSION_1) { 1292 ALOGV("%s: Camera id %d uses older HAL before 3.2, but api1 is always supported", 1293 __FUNCTION__, cameraId); 1294 return OK; 1295 } 1296 case CAMERA_DEVICE_API_VERSION_3_2: 1297 case CAMERA_DEVICE_API_VERSION_3_3: 1298 ALOGV("%s: Camera id %d uses HAL3.2 or newer, supports api1/api2 directly", 1299 __FUNCTION__, cameraId); 1300 return OK; 1301 case -1: 1302 ALOGE("%s: Invalid camera id %d", __FUNCTION__, cameraId); 1303 return BAD_VALUE; 1304 default: 1305 ALOGE("%s: Unknown camera device HAL version: %d", __FUNCTION__, deviceVersion); 1306 return INVALID_OPERATION; 1307 } 1308 1309 return OK; 1310} 1311 1312void CameraService::removeByClient(const BasicClient* client) { 1313 Mutex::Autolock lock(mServiceLock); 1314 for (auto& i : mActiveClientManager.getAll()) { 1315 auto clientSp = i->getValue(); 1316 if (clientSp.get() == client) { 1317 mActiveClientManager.remove(i); 1318 } 1319 } 1320} 1321 1322bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) { 1323 const int callingPid = getCallingPid(); 1324 const int servicePid = getpid(); 1325 bool ret = false; 1326 { 1327 // Acquire mServiceLock and prevent other clients from connecting 1328 std::unique_ptr<AutoConditionLock> lock = 1329 AutoConditionLock::waitAndAcquire(mServiceLockWrapper); 1330 1331 1332 std::vector<sp<BasicClient>> evicted; 1333 for (auto& i : mActiveClientManager.getAll()) { 1334 auto clientSp = i->getValue(); 1335 if (clientSp.get() == nullptr) { 1336 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__); 1337 mActiveClientManager.remove(i); 1338 continue; 1339 } 1340 if (remote == clientSp->getRemote() && (callingPid == servicePid || 1341 callingPid == clientSp->getClientPid())) { 1342 mActiveClientManager.remove(i); 1343 evicted.push_back(clientSp); 1344 1345 // Notify the client of disconnection 1346 clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED, 1347 CaptureResultExtras()); 1348 } 1349 } 1350 1351 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking 1352 // other clients from connecting in mServiceLockWrapper if held 1353 mServiceLock.unlock(); 1354 1355 for (auto& i : evicted) { 1356 if (i.get() != nullptr) { 1357 i->disconnect(); 1358 ret = true; 1359 } 1360 } 1361 1362 // Reacquire mServiceLock 1363 mServiceLock.lock(); 1364 1365 } // lock is destroyed, allow further connect calls 1366 1367 return ret; 1368} 1369 1370 1371std::shared_ptr<CameraService::CameraState> CameraService::getCameraState( 1372 const String8& cameraId) const { 1373 std::shared_ptr<CameraState> state; 1374 { 1375 Mutex::Autolock lock(mCameraStatesLock); 1376 auto iter = mCameraStates.find(cameraId); 1377 if (iter != mCameraStates.end()) { 1378 state = iter->second; 1379 } 1380 } 1381 return state; 1382} 1383 1384sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) { 1385 // Remove from active clients list 1386 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId); 1387 if (clientDescriptorPtr == nullptr) { 1388 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__, 1389 cameraId.string()); 1390 return sp<BasicClient>{nullptr}; 1391 } 1392 1393 return clientDescriptorPtr->getValue(); 1394} 1395 1396 1397void CameraService::logDisconnected(const String8& cameraId, int clientPid, 1398 const String8& clientPackage) { 1399 1400 String8 curTime = getFormattedCurrentTime(); 1401 // Log the clients evicted 1402 mEventLog.add(String8::format("%s : DISCONNECT device %s client for package %s (PID %d)", 1403 curTime.string(), cameraId.string(), clientPackage.string(), clientPid)); 1404} 1405 1406void CameraService::logConnected(const String8& cameraId, int clientPid, 1407 const String8& clientPackage) { 1408 1409 String8 curTime = getFormattedCurrentTime(); 1410 // Log the clients evicted 1411 mEventLog.add(String8::format("%s : CONNECT device %s client for package %s (PID %d)", 1412 curTime.string(), cameraId.string(), clientPackage.string(), clientPid)); 1413} 1414 1415status_t CameraService::onTransact( 1416 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { 1417 // Permission checks 1418 switch (code) { 1419 case BnCameraService::CONNECT: 1420 case BnCameraService::CONNECT_DEVICE: 1421 case BnCameraService::CONNECT_LEGACY: 1422 const int pid = getCallingPid(); 1423 const int self_pid = getpid(); 1424 if (pid != self_pid) { 1425 // we're called from a different process, do the real check 1426 if (!checkCallingPermission( 1427 String16("android.permission.CAMERA"))) { 1428 const int uid = getCallingUid(); 1429 ALOGE("Permission Denial: " 1430 "can't use the camera pid=%d, uid=%d", pid, uid); 1431 return PERMISSION_DENIED; 1432 } 1433 } 1434 break; 1435 } 1436 1437 return BnCameraService::onTransact(code, data, reply, flags); 1438} 1439 1440// We share the media players for shutter and recording sound for all clients. 1441// A reference count is kept to determine when we will actually release the 1442// media players. 1443 1444MediaPlayer* CameraService::newMediaPlayer(const char *file) { 1445 MediaPlayer* mp = new MediaPlayer(); 1446 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) { 1447 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE); 1448 mp->prepare(); 1449 } else { 1450 ALOGE("Failed to load CameraService sounds: %s", file); 1451 return NULL; 1452 } 1453 return mp; 1454} 1455 1456void CameraService::loadSound() { 1457 Mutex::Autolock lock(mSoundLock); 1458 LOG1("CameraService::loadSound ref=%d", mSoundRef); 1459 if (mSoundRef++) return; 1460 1461 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg"); 1462 mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg"); 1463} 1464 1465void CameraService::releaseSound() { 1466 Mutex::Autolock lock(mSoundLock); 1467 LOG1("CameraService::releaseSound ref=%d", mSoundRef); 1468 if (--mSoundRef) return; 1469 1470 for (int i = 0; i < NUM_SOUNDS; i++) { 1471 if (mSoundPlayer[i] != 0) { 1472 mSoundPlayer[i]->disconnect(); 1473 mSoundPlayer[i].clear(); 1474 } 1475 } 1476} 1477 1478void CameraService::playSound(sound_kind kind) { 1479 LOG1("playSound(%d)", kind); 1480 Mutex::Autolock lock(mSoundLock); 1481 sp<MediaPlayer> player = mSoundPlayer[kind]; 1482 if (player != 0) { 1483 player->seekTo(0); 1484 player->start(); 1485 } 1486} 1487 1488// ---------------------------------------------------------------------------- 1489 1490CameraService::Client::Client(const sp<CameraService>& cameraService, 1491 const sp<ICameraClient>& cameraClient, 1492 const String16& clientPackageName, 1493 int cameraId, int cameraFacing, 1494 int clientPid, uid_t clientUid, 1495 int servicePid) : 1496 CameraService::BasicClient(cameraService, 1497 IInterface::asBinder(cameraClient), 1498 clientPackageName, 1499 cameraId, cameraFacing, 1500 clientPid, clientUid, 1501 servicePid) 1502{ 1503 int callingPid = getCallingPid(); 1504 LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId); 1505 1506 mRemoteCallback = cameraClient; 1507 1508 cameraService->loadSound(); 1509 1510 LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId); 1511} 1512 1513// tear down the client 1514CameraService::Client::~Client() { 1515 ALOGV("~Client"); 1516 mDestructionStarted = true; 1517 1518 mCameraService->releaseSound(); 1519 // unconditionally disconnect. function is idempotent 1520 Client::disconnect(); 1521} 1522 1523CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService, 1524 const sp<IBinder>& remoteCallback, 1525 const String16& clientPackageName, 1526 int cameraId, int cameraFacing, 1527 int clientPid, uid_t clientUid, 1528 int servicePid): 1529 mClientPackageName(clientPackageName), mDisconnected(false) 1530{ 1531 mCameraService = cameraService; 1532 mRemoteBinder = remoteCallback; 1533 mCameraId = cameraId; 1534 mCameraFacing = cameraFacing; 1535 mClientPid = clientPid; 1536 mClientUid = clientUid; 1537 mServicePid = servicePid; 1538 mOpsActive = false; 1539 mDestructionStarted = false; 1540} 1541 1542CameraService::BasicClient::~BasicClient() { 1543 ALOGV("~BasicClient"); 1544 mDestructionStarted = true; 1545} 1546 1547void CameraService::BasicClient::disconnect() { 1548 if (mDisconnected) return; 1549 mDisconnected = true;; 1550 1551 mCameraService->removeByClient(this); 1552 mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid, 1553 String8(mClientPackageName)); 1554 1555 sp<IBinder> remote = getRemote(); 1556 if (remote != nullptr) { 1557 remote->unlinkToDeath(mCameraService); 1558 } 1559 1560 finishCameraOps(); 1561 ALOGI("%s: Disconnected client for camera %d for PID %d", __FUNCTION__, mCameraId, mClientPid); 1562 1563 // client shouldn't be able to call into us anymore 1564 mClientPid = 0; 1565} 1566 1567String16 CameraService::BasicClient::getPackageName() const { 1568 return mClientPackageName; 1569} 1570 1571 1572int CameraService::BasicClient::getClientPid() const { 1573 return mClientPid; 1574} 1575 1576status_t CameraService::BasicClient::startCameraOps() { 1577 int32_t res; 1578 // Notify app ops that the camera is not available 1579 mOpsCallback = new OpsCallback(this); 1580 1581 { 1582 ALOGV("%s: Start camera ops, package name = %s, client UID = %d", 1583 __FUNCTION__, String8(mClientPackageName).string(), mClientUid); 1584 } 1585 1586 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA, 1587 mClientPackageName, mOpsCallback); 1588 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA, 1589 mClientUid, mClientPackageName); 1590 1591 if (res != AppOpsManager::MODE_ALLOWED) { 1592 ALOGI("Camera %d: Access for \"%s\" has been revoked", 1593 mCameraId, String8(mClientPackageName).string()); 1594 return PERMISSION_DENIED; 1595 } 1596 1597 mOpsActive = true; 1598 1599 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE 1600 mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE, 1601 String8::format("%d", mCameraId)); 1602 1603 return OK; 1604} 1605 1606status_t CameraService::BasicClient::finishCameraOps() { 1607 // Check if startCameraOps succeeded, and if so, finish the camera op 1608 if (mOpsActive) { 1609 // Notify app ops that the camera is available again 1610 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid, 1611 mClientPackageName); 1612 mOpsActive = false; 1613 1614 auto rejected = {ICameraServiceListener::STATUS_NOT_PRESENT, 1615 ICameraServiceListener::STATUS_ENUMERATING}; 1616 1617 // Transition to PRESENT if the camera is not in either of the rejected states 1618 mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT, 1619 String8::format("%d", mCameraId), rejected); 1620 1621 // Notify flashlight that a camera device is closed. 1622 mCameraService->mFlashlight->deviceClosed( 1623 String8::format("%d", mCameraId)); 1624 } 1625 // Always stop watching, even if no camera op is active 1626 if (mOpsCallback != NULL) { 1627 mAppOpsManager.stopWatchingMode(mOpsCallback); 1628 } 1629 mOpsCallback.clear(); 1630 1631 return OK; 1632} 1633 1634void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) { 1635 String8 name(packageName); 1636 String8 myName(mClientPackageName); 1637 1638 if (op != AppOpsManager::OP_CAMERA) { 1639 ALOGW("Unexpected app ops notification received: %d", op); 1640 return; 1641 } 1642 1643 int32_t res; 1644 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA, 1645 mClientUid, mClientPackageName); 1646 ALOGV("checkOp returns: %d, %s ", res, 1647 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" : 1648 res == AppOpsManager::MODE_IGNORED ? "IGNORED" : 1649 res == AppOpsManager::MODE_ERRORED ? "ERRORED" : 1650 "UNKNOWN"); 1651 1652 if (res != AppOpsManager::MODE_ALLOWED) { 1653 ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId, 1654 myName.string()); 1655 // Reset the client PID to allow server-initiated disconnect, 1656 // and to prevent further calls by client. 1657 mClientPid = getCallingPid(); 1658 CaptureResultExtras resultExtras; // a dummy result (invalid) 1659 notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras); 1660 disconnect(); 1661 } 1662} 1663 1664// ---------------------------------------------------------------------------- 1665 1666// Provide client strong pointer for callbacks. 1667sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) { 1668 String8 cameraId = String8::format("%d", (int)(intptr_t) user); 1669 auto clientDescriptor = gCameraService->mActiveClientManager.get(cameraId); 1670 if (clientDescriptor != nullptr) { 1671 return sp<Client>{ 1672 static_cast<Client*>(clientDescriptor->getValue().get())}; 1673 } 1674 return sp<Client>{nullptr}; 1675} 1676 1677void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode, 1678 const CaptureResultExtras& resultExtras) { 1679 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0); 1680} 1681 1682// NOTE: function is idempotent 1683void CameraService::Client::disconnect() { 1684 ALOGV("Client::disconnect"); 1685 BasicClient::disconnect(); 1686} 1687 1688CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client): 1689 mClient(client) { 1690} 1691 1692void CameraService::Client::OpsCallback::opChanged(int32_t op, 1693 const String16& packageName) { 1694 sp<BasicClient> client = mClient.promote(); 1695 if (client != NULL) { 1696 client->opChanged(op, packageName); 1697 } 1698} 1699 1700// ---------------------------------------------------------------------------- 1701// CameraState 1702// ---------------------------------------------------------------------------- 1703 1704CameraService::CameraState::CameraState(const String8& id, int cost, 1705 const std::set<String8>& conflicting) : mId(id), 1706 mStatus(ICameraServiceListener::STATUS_PRESENT), mCost(cost), mConflicting(conflicting) {} 1707 1708CameraService::CameraState::~CameraState() {} 1709 1710ICameraServiceListener::Status CameraService::CameraState::getStatus() const { 1711 Mutex::Autolock lock(mStatusLock); 1712 return mStatus; 1713} 1714 1715CameraParameters CameraService::CameraState::getShimParams() const { 1716 return mShimParams; 1717} 1718 1719void CameraService::CameraState::setShimParams(const CameraParameters& params) { 1720 mShimParams = params; 1721} 1722 1723int CameraService::CameraState::getCost() const { 1724 return mCost; 1725} 1726 1727std::set<String8> CameraService::CameraState::getConflicting() const { 1728 return mConflicting; 1729} 1730 1731String8 CameraService::CameraState::getId() const { 1732 return mId; 1733} 1734 1735// ---------------------------------------------------------------------------- 1736// CameraClientManager 1737// ---------------------------------------------------------------------------- 1738 1739CameraService::CameraClientManager::~CameraClientManager() {} 1740 1741sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient( 1742 const String8& id) const { 1743 auto descriptor = get(id); 1744 if (descriptor == nullptr) { 1745 return sp<BasicClient>{nullptr}; 1746 } 1747 return descriptor->getValue(); 1748} 1749 1750String8 CameraService::CameraClientManager::toString() const { 1751 auto all = getAll(); 1752 String8 ret("["); 1753 bool hasAny = false; 1754 for (auto& i : all) { 1755 hasAny = true; 1756 String8 key = i->getKey(); 1757 int32_t cost = i->getCost(); 1758 int32_t pid = i->getOwnerId(); 1759 int32_t priority = i->getPriority(); 1760 auto conflicting = i->getConflicting(); 1761 auto clientSp = i->getValue(); 1762 String8 packageName; 1763 if (clientSp.get() != nullptr) { 1764 packageName = String8{clientSp->getPackageName()}; 1765 } 1766 ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Priority: %" 1767 PRId32 ", ", key.string(), cost, pid, priority); 1768 1769 if (packageName.size() != 0) { 1770 ret.appendFormat("Client Package Name: %s", packageName.string()); 1771 } 1772 1773 ret.append(", Conflicting Client Devices: {"); 1774 for (auto& j : conflicting) { 1775 ret.appendFormat("%s, ", j.string()); 1776 } 1777 ret.append("})"); 1778 } 1779 if (hasAny) ret.append("\n"); 1780 ret.append("]\n"); 1781 return ret; 1782} 1783 1784CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor( 1785 const String8& key, const sp<BasicClient>& value, int32_t cost, 1786 const std::set<String8>& conflictingKeys, int32_t priority, int32_t ownerId) { 1787 1788 return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>( 1789 key, value, cost, conflictingKeys, priority, ownerId); 1790} 1791 1792CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor( 1793 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) { 1794 return makeClientDescriptor(partial->getKey(), value, partial->getCost(), 1795 partial->getConflicting(), partial->getPriority(), partial->getOwnerId()); 1796} 1797 1798// ---------------------------------------------------------------------------- 1799 1800static const int kDumpLockRetries = 50; 1801static const int kDumpLockSleep = 60000; 1802 1803static bool tryLock(Mutex& mutex) 1804{ 1805 bool locked = false; 1806 for (int i = 0; i < kDumpLockRetries; ++i) { 1807 if (mutex.tryLock() == NO_ERROR) { 1808 locked = true; 1809 break; 1810 } 1811 usleep(kDumpLockSleep); 1812 } 1813 return locked; 1814} 1815 1816status_t CameraService::dump(int fd, const Vector<String16>& args) { 1817 String8 result; 1818 if (checkCallingPermission(String16("android.permission.DUMP")) == false) { 1819 result.appendFormat("Permission Denial: " 1820 "can't dump CameraService from pid=%d, uid=%d\n", 1821 getCallingPid(), 1822 getCallingUid()); 1823 write(fd, result.string(), result.size()); 1824 } else { 1825 bool locked = tryLock(mServiceLock); 1826 // failed to lock - CameraService is probably deadlocked 1827 if (!locked) { 1828 result.append("CameraService may be deadlocked\n"); 1829 write(fd, result.string(), result.size()); 1830 } 1831 1832 bool hasClient = false; 1833 if (!mModule) { 1834 result = String8::format("No camera module available!\n"); 1835 write(fd, result.string(), result.size()); 1836 if (locked) mServiceLock.unlock(); 1837 return NO_ERROR; 1838 } 1839 1840 const hw_module_t* common = mModule->getRawModule(); 1841 result = String8::format("Camera module HAL API version: %#x\n", common->hal_api_version); 1842 result.appendFormat("Camera module API version: %#x\n", common->module_api_version); 1843 result.appendFormat("Camera module name: %s\n", common->name); 1844 result.appendFormat("Camera module author: %s\n", common->author); 1845 result.appendFormat("Number of camera devices: %d\n", mNumberOfCameras); 1846 String8 activeClientString = mActiveClientManager.toString(); 1847 result.appendFormat("Active Camera Clients:\n%s", activeClientString.string()); 1848 1849 1850 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor(); 1851 if (desc == NULL) { 1852 result.appendFormat("Vendor tags left unimplemented.\n"); 1853 } else { 1854 result.appendFormat("Vendor tag definitions:\n"); 1855 } 1856 1857 write(fd, result.string(), result.size()); 1858 1859 if (desc != NULL) { 1860 desc->dump(fd, /*verbosity*/2, /*indentation*/4); 1861 } 1862 1863 result = String8("Prior client events (most recent at top):\n"); 1864 1865 for (const auto& msg : mEventLog) { 1866 result.appendFormat("%s\n", msg.string()); 1867 } 1868 1869 if (mEventLog.size() == DEFAULT_EVICTION_LOG_LENGTH) { 1870 result.append("...\n"); 1871 } 1872 1873 write(fd, result.string(), result.size()); 1874 1875 bool stateLocked = tryLock(mCameraStatesLock); 1876 if (!stateLocked) { 1877 result = String8::format("CameraStates in use, may be deadlocked\n"); 1878 write(fd, result.string(), result.size()); 1879 } 1880 1881 for (auto& state : mCameraStates) { 1882 String8 cameraId = state.first; 1883 result = String8::format("Camera %s information:\n", cameraId.string()); 1884 camera_info info; 1885 1886 // TODO: Change getCameraInfo + HAL to use String cameraIds 1887 status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info); 1888 if (rc != OK) { 1889 result.appendFormat(" Error reading static information!\n"); 1890 write(fd, result.string(), result.size()); 1891 } else { 1892 result.appendFormat(" Facing: %s\n", 1893 info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT"); 1894 result.appendFormat(" Orientation: %d\n", info.orientation); 1895 int deviceVersion; 1896 if (common->module_api_version < CAMERA_MODULE_API_VERSION_2_0) { 1897 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0; 1898 } else { 1899 deviceVersion = info.device_version; 1900 } 1901 1902 auto conflicting = state.second->getConflicting(); 1903 result.appendFormat(" Resource Cost: %d\n", state.second->getCost()); 1904 result.appendFormat(" Conflicting Devices:"); 1905 for (auto& id : conflicting) { 1906 result.appendFormat(" %s", cameraId.string()); 1907 } 1908 if (conflicting.size() == 0) { 1909 result.appendFormat(" NONE"); 1910 } 1911 result.appendFormat("\n"); 1912 1913 result.appendFormat(" Device version: %#x\n", deviceVersion); 1914 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) { 1915 result.appendFormat(" Device static metadata:\n"); 1916 write(fd, result.string(), result.size()); 1917 dump_indented_camera_metadata(info.static_camera_characteristics, 1918 fd, /*verbosity*/2, /*indentation*/4); 1919 } else { 1920 write(fd, result.string(), result.size()); 1921 } 1922 1923 CameraParameters p = state.second->getShimParams(); 1924 if (!p.isEmpty()) { 1925 result = String8::format(" Camera1 API shim is using parameters:\n "); 1926 write(fd, result.string(), result.size()); 1927 p.dump(fd, args); 1928 } 1929 } 1930 1931 auto clientDescriptor = mActiveClientManager.get(cameraId); 1932 if (clientDescriptor == nullptr) { 1933 result = String8::format(" Device %s is closed, no client instance\n", 1934 cameraId.string()); 1935 write(fd, result.string(), result.size()); 1936 continue; 1937 } 1938 hasClient = true; 1939 result = String8::format(" Device %s is open. Client instance dump:\n\n", 1940 cameraId.string()); 1941 result.appendFormat("Client priority level: %d\n", clientDescriptor->getPriority()); 1942 result.appendFormat("Client PID: %d\n", clientDescriptor->getOwnerId()); 1943 1944 auto client = clientDescriptor->getValue(); 1945 result.appendFormat("Client package: %s\n", 1946 String8(client->getPackageName()).string()); 1947 write(fd, result.string(), result.size()); 1948 1949 client->dump(fd, args); 1950 } 1951 1952 if (stateLocked) mCameraStatesLock.unlock(); 1953 1954 if (!hasClient) { 1955 result = String8::format("\nNo active camera clients yet.\n"); 1956 write(fd, result.string(), result.size()); 1957 } 1958 1959 if (locked) mServiceLock.unlock(); 1960 1961 // Dump camera traces if there were any 1962 write(fd, "\n", 1); 1963 camera3::CameraTraces::dump(fd, args); 1964 1965 // change logging level 1966 int n = args.size(); 1967 for (int i = 0; i + 1 < n; i++) { 1968 String16 verboseOption("-v"); 1969 if (args[i] == verboseOption) { 1970 String8 levelStr(args[i+1]); 1971 int level = atoi(levelStr.string()); 1972 result = String8::format("\nSetting log level to %d.\n", level); 1973 setLogLevel(level); 1974 write(fd, result.string(), result.size()); 1975 } 1976 } 1977 } 1978 return NO_ERROR; 1979} 1980 1981void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) { 1982 Mutex::Autolock al(mTorchClientMapMutex); 1983 for (size_t i = 0; i < mTorchClientMap.size(); i++) { 1984 if (mTorchClientMap[i] == who) { 1985 // turn off the torch mode that was turned on by dead client 1986 String8 cameraId = mTorchClientMap.keyAt(i); 1987 status_t res = mFlashlight->setTorchMode(cameraId, false); 1988 if (res) { 1989 ALOGE("%s: torch client died but couldn't turn off torch: " 1990 "%s (%d)", __FUNCTION__, strerror(-res), res); 1991 return; 1992 } 1993 mTorchClientMap.removeItemsAt(i); 1994 break; 1995 } 1996 } 1997} 1998 1999/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) { 2000 2001 /** 2002 * While tempting to promote the wp<IBinder> into a sp, 2003 * it's actually not supported by the binder driver 2004 */ 2005 2006 // check torch client 2007 handleTorchClientBinderDied(who); 2008 2009 // check camera device client 2010 if(!evictClientIdByRemote(who)) { 2011 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__); 2012 return; 2013 } 2014 2015 ALOGE("%s: Java client's binder died, removing it from the list of active clients", 2016 __FUNCTION__); 2017} 2018 2019void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId) { 2020 updateStatus(status, cameraId, {}); 2021} 2022 2023void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId, 2024 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates) { 2025 // Do not lock mServiceLock here or can get into a deadlock from 2026 // connect() -> disconnect -> updateStatus 2027 2028 auto state = getCameraState(cameraId); 2029 2030 if (state == nullptr) { 2031 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__, 2032 cameraId.string()); 2033 return; 2034 } 2035 2036 // Update the status for this camera state, then send the onStatusChangedCallbacks to each 2037 // of the listeners with both the mStatusStatus and mStatusListenerLock held 2038 state->updateStatus(status, cameraId, rejectSourceStates, [this] 2039 (const String8& cameraId, ICameraServiceListener::Status status) { 2040 2041 // Update torch status 2042 if (status == ICameraServiceListener::STATUS_NOT_PRESENT || 2043 status == ICameraServiceListener::STATUS_NOT_AVAILABLE) { 2044 // Update torch status to not available when the camera device becomes not present 2045 // or not available. 2046 onTorchStatusChanged(cameraId, ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE); 2047 } else if (status == ICameraServiceListener::STATUS_PRESENT) { 2048 // Update torch status to available when the camera device becomes present or 2049 // available 2050 onTorchStatusChanged(cameraId, ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF); 2051 } 2052 2053 Mutex::Autolock lock(mStatusListenerLock); 2054 2055 for (auto& listener : mListenerList) { 2056 // TODO: Refactor status listeners to use strings for Camera IDs and remove this. 2057 int id = cameraIdToInt(cameraId); 2058 if (id != -1) listener->onStatusChanged(status, id); 2059 } 2060 }); 2061} 2062 2063status_t CameraService::getTorchStatusLocked( 2064 const String8& cameraId, 2065 ICameraServiceListener::TorchStatus *status) const { 2066 if (!status) { 2067 return BAD_VALUE; 2068 } 2069 ssize_t index = mTorchStatusMap.indexOfKey(cameraId); 2070 if (index == NAME_NOT_FOUND) { 2071 // invalid camera ID or the camera doesn't have a flash unit 2072 return NAME_NOT_FOUND; 2073 } 2074 2075 *status = mTorchStatusMap.valueAt(index); 2076 return OK; 2077} 2078 2079status_t CameraService::setTorchStatusLocked(const String8& cameraId, 2080 ICameraServiceListener::TorchStatus status) { 2081 ssize_t index = mTorchStatusMap.indexOfKey(cameraId); 2082 if (index == NAME_NOT_FOUND) { 2083 return BAD_VALUE; 2084 } 2085 ICameraServiceListener::TorchStatus& item = 2086 mTorchStatusMap.editValueAt(index); 2087 item = status; 2088 2089 return OK; 2090} 2091 2092}; // namespace android 2093