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