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