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