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