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