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