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