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