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